<template>
  <div class="main-content abnormal">
    <!-- <div class="content-header">
      <span class="title">标记经营异常状态：审核</span>
      <el-button type="warning" icon="el-icon-caret-left" size="mini" class="back-btn" @click="$router.back()">返回上一层</el-button>
    </div> -->
    <!-- <DetailHead /> -->
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="180px" label-position="right" :rules="formRules">
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>异常信息</label></div>
          </div>
          <div class="form-body">
            <el-row class="lh0">
              <el-form-item label="列入异常主体信息">
                <el-button size="medium" type="primary" @click="showEntbaseList">查看异常主体名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
                <el-button size="medium" type="primary" @click="exportEntListExcel">导出Excel<i class="el-icon" style="margin-left:5px" /></el-button>
                <el-button v-if="remList.length > 0" size="medium" type="primary" @click="showRemEntList">查看已剔除名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="列入原因" prop="reason" class="bt0">
                <el-col style="display:inline-block;">
                  <el-input v-model="form.reason" type="textarea" style="display:inline-block;width:100%" disabled />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="决定书内容" prop="decisionContent" class="bt0">
                <el-col style="display:inline-block;">
                  <el-input v-model="decisionContent" type="textarea" style="display:inline-block;width:100%" disabled :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remark" class="bt0">
                <el-input v-model="remark" type="textarea" style="display:inline-block;width:100%" :autosize="{ minRows: 2, maxRows: 6 }" disabled />
              </el-form-item>
            </el-row>
            <el-row class="p0">
              <el-form-item label="材料列表" class="bt0">
                <ul style="list-style:none;padding:0;margin:5px">
                  <li v-for="item in fileList" :key="item.id" style="line-height: 30px">
                    <el-link style="font-size:16px" @click="handlePreview(item)">{{ item.name }}</el-link>
                  </li>
                </ul>
              </el-form-item>
            </el-row>

            <!-- <el-form-item label="事实理由">
              <el-input v-model="form.spereasons" type="textarea" style="display:inline-block;width:600px" :autosize="{ minRows: 3, maxRows: 6 }" disabled />
            </el-form-item> -->

          </div>
        </div>
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>处理意见</label></div>
          </div>
          <div class="form-body history">
            <div v-if="historyLog.length == 0" class="none">暂无历史意见</div>
            <el-steps direction="vertical">
              <el-step v-for="(each,index) in historyLog" :key="'historyLog'+index" :title="each.step + '人：' + each.handler + ' ' + each.step +'日期：' + each.handledate " :description=" each.opinioncontent " status="finish" />
            </el-steps>
          </div>
        </div>
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>审核意见</label></div>
          </div>
          <div class="form-body">
            <el-row class="p0">
              <el-form-item label="是否通过" prop="nextNode">
                <el-radio v-model="form.nextNodeID" label="approvelist">通过</el-radio>
                <!--                <el-radio v-model="form.nextNodeID" label="overExptlist">不通过</el-radio>-->
                <el-radio v-model="form.nextNodeID" label="exptlistEnter">回退</el-radio>  <!-- 回退至经办人 -->
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="审核意见" prop="opinion" class="bt0">
                <el-col :span="24" style="margin-bottom:10px">
                  <el-input v-model="form.opinion" type="textarea" placeholder="请输入审核意见" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
                <el-col :span="24">
                  <label style="line-height:32px">常用语</label>
                  <el-select v-model="opinion" placeholder="请选择" clearable class="custom" style="margin-left: 10px">
                    <el-option
                      v-for="item in opinionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item v-if="form.nextNodeID == 'approvelist'" label="审批人" prop="reviewerId" class="bt0">
                <el-select v-model="form.reviewerId" filterable clearable placeholder="请选择审批人">
                  <el-option
                    v-for="item in reviewer"
                    :key="'reviewer'+item.primaryKey"
                    :label="item.name"
                    :value="item.primaryKey"
                  />
                </el-select>
              </el-form-item>
            </el-row>

          </div>
        </div>
      </el-form>
      <div class="submit-box">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">提交</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>
    <el-dialog
      title="异常主体名单"
      :visible.sync="showEntbase"
      width="90%"
    >
      <el-table
        v-loading="loading"
        :data="bizList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="210" align="left" />
        <el-table-column prop="address" :show-overflow-tooltip="true" label="经营地址" min-width="180" align="left" />
        <el-table-column prop="estDate" :show-overflow-tooltip="true" label="成立日期" min-width="80" align="left" />
        <el-table-column prop="lerepname" label="法定代表人" min-width="80" align="left" />
        <el-table-column prop="entTypeName" :show-overflow-tooltip="true" label="企业类型" min-width="120" align="left" />
        <el-table-column prop="regstateCn" :show-overflow-tooltip="true" label="企业状态" min-width="100" align="left" />
      </el-table>
      <el-row class="bl0">
        <el-col>
          <el-pagination
            :current-page="pageParam.curPage"
            small
            layout="prev, pager, next"
            :total="pageParam.total"
            @size-change="pageSizeChange"
            @current-change="pageIndexChange"
          />
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      title="已剔除主体名单"
      :visible.sync="showRemEnt"
      width="90%"
    >
      <el-table
        v-loading="loading"
        :data="remList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="210" align="left" />
        <el-table-column prop="removeReason" :show-overflow-tooltip="true" label="剔除原因" min-width="180" align="left" />
        <el-table-column
          prop="removeTime"
          :show-overflow-tooltip="true"
          label="剔除时间"
          min-width="80"
          align="left"
        />
        <el-table-column prop="removeHandler" label="剔除处理人" min-width="80" align="left" />
      </el-table>
      <div>
        <el-row class="bl0">
          <el-col :span="12">
            <el-pagination
              :current-page="remPageParam.curPage"
              small
              layout="prev, pager, next"
              :total="remPageParam.total"
              @size-change="remPageSizeChange"
              @current-change="remPageIndexChange"
            />
          </el-col>
          <el-col :span="12">
            <div class="dialog-box">
              <el-button type="primary" size="mini" @click="showRemEntList">确定</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DetailHead from '@/components/DetailHead'
import HandleDialog from '@/components/HandleDialog'
import { removeAttachementById, listAttachmentByBizseq } from '@/api/attachment'
import { nextAbnormaInclusionProcess, getBizSpeListPage, searchBizSpeByBizSeqId } from '@/api/abnormal'
import { getUsersWithPermission } from '@/api/user'
import { taskOpinion } from '@/api/task'
import { parseTime } from '@/utils'
import { getConstant } from '@/api/system'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      remPageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'rem'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      remList: [],
      showRemEnt: false,
      removeReason: '',
      decisionContent: '',
      submitLoading: false,
      remark: '',
      bizseq: '',
      workflowId: '',
      uploadPath: `${process.env.VUE_APP_BASE_API}/attachment/uploadAdvance`,
      showEntbase: false,
      batchId: this.$route.query.batch,
      entbase: [],
      // 分页数据,这里用来保存每页切割后的数据
      // 看起来格式是这样的[[{},{},{}],[{},{},{}]]
      // 数组内套数组，每个数组就是一页数据
      totalPageData: [],
      // 共几页
      pageNum: '',
      // 每页显示数量
      pageSize: 10,
      // 当前显示页码
      currentPage: 1,
      // 总共多少条数据
      total: 1,
      // 当前要显示的数据
      dataShow: [],
      form: {
        enterType: 'individual',
        nextNodeID: 'approvelist',
        spereasons: '',
        reason: '',
        opinion: ''
      },
      formRules: {
        opinion: [
          { required: true, message: '请输入审核意见', trigger: ['blur', 'change'] }
        ],
        reviewerId: [
          { required: true, message: '请选择审批人' }
        ]
      },
      reason: '',
      opinion: '',
      reasonOptions: [],
      opinionOptions: [{
        value: 0,
        label: '拟同意,呈领导审批。'
      }, {
        value: 1,
        label: '不同意，回退至经办人。'
      }, {
        value: 2,
        label: '不同意。'
      }],
      historyLog: [],
      exmainerOptions: [],
      fileList: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      reviewer: [],
      pageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'biz'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      bizList: [], // 异常主体名单分页列表
      loading: false
    }
  },
  watch: {
    // 原因渲染
    reason() {
      this.form.specause = this.reason
      let name = ''
      this.reasonOptions.forEach(each => {
        if (this.reason === each.value) {
          name = each.label
        }
      })
      this.form.reason = name
    },
    // 意见渲染
    opinion() {
      let name = ''
      this.opinionOptions.forEach(each => {
        if (this.opinion === each.value) {
          name = each.label
        }
      })
      this.form.opinion = name
    }
  },
  mounted() {
    this.bizseq = this.$route.query.bizseq
    this.workflowId = this.$route.query.workflowId
    this.tasklistid = this.$route.query.tasklistid
    // 加载常用语
    this.opinionOptions = this.$util.getCommonWordsWithModule(this.user.primaryKey, '个体户经营异常状态标记')
    // 加载处办记录
    taskOpinion(this.workflowId).then(res => {
      if (res.code === 0) {
        res.data.forEach(each => {
          switch (each.opiniontype) {
            case '0': each.step = '经办'
              break
            case '1': each.step = '审核'
              break
            case '2': each.step = '审批'
              break
          }
          this.historyLog.push(each)
        })
      } else {
        this.$message.error('加载处办记录失败')
      }
    })
    // 加载企业列入原因
    getConstant('CD75').then(res => {
      if (res.code === 0) {
        const list = []
        res.data.forEach(each => {
          list.push({
            value: each.code,
            label: each.name
          })
        })
        this.reasonOptions = list

        if (this.$util.isNotEmpty(this.reason)) {
          let name = ''
          this.reasonOptions.forEach(each => {
            if (this.reason === each.value) {
              name = each.label
            }
          })
          this.form.reason = name
        }
      }
    })
    // 加载异常名录主体
    this.loadBizSpeListPage()
    this.loadRemListPage()
    // 加载列入原因及事实理由
    // searchBizSpeByBizSeqId(this.bizseq).then(res => {
    //   if (res.code === 0) {
    //     this.reason = res.data.specause
    //     this.spereasons = res.data.spereasons
    //     this.remark = res.data.remark === 'null' ? '' : res.data.remark
    //   }
    // })

    // 加载审核人
    this.loadReviewer()

    // 加载附件清单
    listAttachmentByBizseq(this.bizseq).then(data => {
      const list = []
      data.forEach(each => {
        if (each.attachtype !== '0') {
          each.id = each.attachmentid
          each.name = each.filename
          each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
          list.push(each)
        }
      })
      this.fileList = list
    })
  },
  methods: {
    loadBizSpeListPage() {
      if (this.loading) return
      this.loading = true
      this.pageParam.customParamMap.bizseq = this.bizseq
      getBizSpeListPage(this.pageParam).then((res) => {
        const list = []
        let i = 1
        const pageStart =
          (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.records.forEach((each) => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.bizList = list
        this.loading = false
        this.pageParam.total = res.data.total
        this.reason = this.bizList[0].specause
        this.remark = this.bizList[0].remark === 'null' ? '' : this.bizList[0].remark
        if (this.bizList[0].decisionContent !== null) {
          this.$nextTick(() => {
            this.decisionContent = this.bizList[0].decisionContent
          })
        }
      })
    },
    // 加载已剔除名单
    loadRemListPage() {
      this.loading = true
      this.remPageParam.customParamMap.bizseq = this.bizseq
      getBizSpeListPage(this.remPageParam).then((res) => {
        const list = []
        let i = 1
        const pageStart =
          (this.remPageParam.curPage - 1) * this.remPageParam.pageSize
        res.data.records.forEach((each) => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.remList = list
        this.loading = false
        this.remPageParam.total = res.data.total
      })
    },
    // 剔除名单列表分页大小改变
    remPageSizeChange(pageSize) {
      this.remPageParam.pageSize = pageSize
      this.loadRemListPage()
    },
    // 剔除名单列表当前分页改变
    remPageIndexChange(curPage) {
      this.remPageParam.curPage = curPage
      this.loadRemListPage()
    },
    parseTime(...args) {
      return parseTime(...args)
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadBizSpeListPage()
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadBizSpeListPage()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 主体名单导出Excel
    exportEntListExcel() {
      this.$confirm('是否确认导出', '提示').then(() => {
        const url = location.origin + process.env.VUE_APP_BASE_API + '/bizSpeList/exportEntList?bizseq=' + this.bizseq
        window.open(url)
      })
    },
    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    // 点击文件列表中已上传文件进行下载
    handlePreview(file) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = file.name
      a.href = file.url
      a.dispatchEvent(event)
    },
    // 发送提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.$confirm('是否确认提交？', '提示').then(() => {
          this.submitLoading = true
          this.form.bizseq = this.bizseq
          this.form.workflowid = this.workflowId
          this.form.opiniontype = '1'
          this.form.handler = this.user.username
          this.form.handlerid = this.user.primaryKey
          this.form.opinioncontent = this.form.opinion
          this.form.tasklistid = this.tasklistid
          // this.form.nextPerformerids = this.user.primaryKey
          // this.form.nextPerformerNames = this.user.username
          this.form.nextPerformerids = (this.form.nextNodeID === 'exptlistEnter' || this.form.reviewerId === undefined) ? '' : this.form.reviewerId
          for (const i in this.reviewer) {
            if (this.reviewer[i].primaryKey === this.form.reviewerId) {
              this.form.nextPerformerNames = this.reviewer[i].name
            }
          }
          nextAbnormaInclusionProcess(this.form).then(res => {
            this.submitLoading = false
            if (res.code === 0) {
              this.$message.success('审核成功')
              if (isMenHu()) {
                // 信创门户环境跳转回待办
                window.location.href = '/aiccs/#/todo/list'
              } else {
                this.$router.back()
              }
            }
          })
        }).catch(() => {})
      })
    },
    // 查看异常主体名单
    showEntbaseList() {
      this.showEntbase = true
    },
    // 查看已剔除主体名单
    showRemEntList() {
      this.showRemEnt = !this.showRemEnt
    },
    // 移除文件回调
    removeFile(file) {
      removeAttachementById(file.id).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 加载审核人
    loadReviewer() {
      getUsersWithPermission('individualMarkExamine', this.user.orgId).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  font-size: $table-content-font-size;
  padding: 10pt;
  .back-btn{
    position:absolute;
    right:40pt;
  }
  .content-header,.content-body{
    background: white;
    padding:20PX 10PX;
    border:1PX solid #eee;
  }
  .content-header{
    height:60PX;
    .title{
      font-weight: 700;
      font-size: $font-size-sub-title;
    }
  }
  .content-body{
    padding:20pt;
      .tab{
        .tab-title{
          label{
            display:inline-block;
          }
        }
      }
    .form{
      margin-bottom: 20pt;
    }
  }
}
.el-row {
  border-left: 1px solid $color-border;
}
.bt0 {
  /deep/.el-form-item__label{
    border-top: 0!important;
  }
  /deep/.el-form-item__content{
    border-top: 0!important;
  }
}
/deep/.el-table .warning-row {
  background: #eaf4fe!important;
}
</style>
<style lang="scss">
.main-content.abnormal{
  .el-form-item{
    margin-bottom:0;
    background: $color-form-label;
    .el-form-item__label{
      padding-left: 10px;
      border-top: 1px solid $color-border;
    }
    .el-form-item__content{
      background: white;
      padding: 10px;
      border-top: 1px solid $color-border;
      border-right: 1px solid $color-border;
      border-left: 1px solid $color-border;
    }
  }
  .el-form-item:last-child{
    border-bottom: 1px solid $color-border;
  }
  .form-body.history{
    padding:15px;
    border:1px solid $color-border;
  }
  .el-form-item.is-error .custom .el-input__inner{
    border-color:$color-border;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    color: #1c1e23;
  }
  .handle-dialog.mid>.main-dialog{
    min-height: 300px;
    width: 75vw;
  }
  .el-step__description{
    font-size: 18px;
  }
}
</style>
