<template>
  <div class="main-content abnormal">
    <DetailHead />
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="200px" 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 v-if="searchNameP === ''" label="移出严重违法主体信息">
                <el-button size="mini" type="primary" @click="showEntbaseList">查看严重违法企业名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item v-if="searchNameP !== '' && entbase.length>1" label="移出严重违法主体信息" class="bt0">
                <el-button type="primary" @click="showEntbaseList">查看严重违法企业名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item v-if="searchNameP !== '' && entbase.length === 1" label="移出严重违法主体" class="bt0">
                <span>{{ dataShow[0].entName }}</span>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="移出原因" prop="reason" class="bt0">
                <div style="display:inline-block;">
                  <el-input v-model="form.reason" type="textarea" style="display:inline-block;width:600px" disabled />
                </div>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="事实理由" class="bt0">
                <el-input v-model="form.lostCreditExplainrem" type="textarea" style="display:inline-block;width:600px" :autosize="{ minRows: 3, maxRows: 6 }" disabled />
              </el-form-item>
            </el-row>
            <el-row class="upload p0">
              <el-form-item label="材料上传" class="bt0">
                <el-upload
                  :action="uploadPath"
                  :data="{batchId:batchId}"
                  :on-remove="removeFile"
                  :on-success="uploadCallback"
                  :on-preview="previewFile"
                  multiple
                  :file-list="fileList"
                  style="width:min-content"
                >
                <!-- <el-button size="small" type="primary">点击上传</el-button> -->
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
              </el-form-item>
            </el-row>
          </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.handledate" :description="each.opinioncontent" status="finish" />
            </el-steps>
          </div>
        </div>
      </el-form>
      <div class="submit-box">
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>
    <el-dialog
      title="严重违法主体名单"
      :visible.sync="showEntbase"
      width="80%"
      :before-close="handleClose"
    >
      <el-table
        :data="dataShow"
        tooltip-effect="dark"
        :fit="true"
        height="500px"
        :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
      >
        <el-table-column prop="index" label="序号" min-width="35" align="center" show-overflow-tooltip />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="150" align="left" show-overflow-tooltip />
        <el-table-column prop="name" label="名称" min-width="150" align="left" show-overflow-tooltip />
        <el-table-column prop="abnTime" label="列入时间" align="left" show-overflow-tooltip />
        <el-table-column prop="serIllReaString" label="列入原因" min-width="250" align="left" show-overflow-tooltip />
      </el-table>
      <div>
        <el-row>
          <el-col>
            <el-pagination
              :current-page="currentPage"
              small
              layout="prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </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 { nextRemTask, listIllegalRem, listIllegalRemByName } from '@/api/illegal'
import { getUsersWithPermission } from '@/api/user'
import { taskOpinion } from '@/api/task'
import { getConstant } from '@/api/system'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      searchNameP: '',
      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: 'company',
        nextNodeID: 'approveSerIllegal',
        lostCreditExplainrem: '',
        reason: '',
        opinion: ''
      },
      formRules: {
        reason: [
          { required: true, message: '请输入移出原因', trigger: 'blur' }
        ],
        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: [{
        primaryKey: 0,
        name: '陈彦宇'
      }, {
        primaryKey: 1,
        name: '郭翊'
      }, {
        primaryKey: 2,
        name: '陈文云'
      }, {
        primaryKey: 3,
        name: '王东'
      }],
      submitLoading: 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.searchNameP = this.$route.query.searchName
    if (this.searchNameP === undefined) {
      this.searchNameP = ''
    }
    // 加载常用语
    this.opinionOptions = this.$util.getCommonWords(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('CD74').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
        }
      }
    })
    // 加载严重违法企业名录主体
    if (this.searchNameP === '') {
      listIllegalRem(this.bizseq).then(res => {
        if (res.code === 0) {
          // 添加分页index
          let i = 1
          const pageStart = (this.currentPage - 1) * this.pageSize
          res.data.forEach(each => {
            each.index = pageStart + i++
            each.name = each.entName
            each.uscc = each.regNO
            this.form.reason = each.remExcpResString
            this.form.lostCreditExplainrem = each.lostCreditExplainrem
            this.entbase.push(each)
          })
          // 分页处理
          this.total = this.entbase.length
          // 计算页数
          this.calcPageData()
        } else {
          this.$message.error('加载严重违法企业名录主体信息失败')
        }
      })
    } else {
      listIllegalRemByName(this.bizseq, this.searchNameP).then(res => {
        if (res.code === 0) {
          // 添加分页index
          let i = 1
          const pageStart = (this.currentPage - 1) * this.pageSize
          res.data.forEach(each => {
            each.index = pageStart + i++
            each.name = each.entName
            each.uscc = each.regNO
            this.form.reason = each.remExcpResString
            this.form.lostCreditExplainrem = each.lostCreditExplainrem
            this.entbase.push(each)
          })
          // 分页处理
          this.total = this.entbase.length
          // 计算页数
          this.calcPageData()
        } else {
          this.$message.error('加载严重违法企业名录主体信息失败')
        }
      })
    }

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

    // 加载附件清单
    listAttachmentByBizseq(this.bizseq).then(data => {
      data.forEach(each => {
        each.id = each.attachmentid
        each.name = each.filename
        each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
      })
      this.fileList = data
    })
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 计算页数
    calcPageData() {
      // 计算页数(根据后台数据的条数和每页显示数量算出一共几页,得0时设为1)
      if (this.entbase.length >= 1) {
        this.pageNum = Math.ceil(this.entbase.length / this.pageSize) || 1
        console.log('总页数:', this.pageNum)
      }
      // 数据分组
      for (let i = 0; i < this.pageNum; i++) {
        // 每一页都是一个数组 形如 [['第一页的数据'],['第二页的数据'],['第三页数据']]
        // 根据每页显示数量 将后台的数据分割到 每一页,假设pageSize为5， 则第一页是1-5条，即slice(0,5)，第二页是6-10条，即slice(5,10)...
        this.totalPageData[i] = this.entbase.slice(this.pageSize * i, this.pageSize * (i + 1))
      }
      // 获取到数据后显示第一页内容,数组下标是从0开始的，这里一定要减去1，不然会丢失一组数据
      this.dataShow = this.totalPageData[this.currentPage - 1]
      console.log(this.dataShow)
    },
    // 每页条数发生变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize
      // 重新计算页数并分组
      this.calcPageData()
    },
    // 当前页码发生变化
    handleCurrentChange(newPageNum) {
      console.log('当前页码:', newPageNum)
      this.currentPage = newPageNum
      // 这里仍然不要忘记减去1
      this.dataShow = this.totalPageData[newPageNum - 1]
    },
    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    // 发送提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.$confirm('是否确认提交？', '提示').then(() => {
          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.form.reviewerId
          for (const i in this.reviewer) {
            if (this.reviewer[i].primaryKey === this.form.reviewerId) {
              this.form.nextPerformerNames = this.reviewer[i].name
            }
          }
          this.submitLoading = true
          nextRemTask(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(() => {})
      })
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        file.id = res.data.attachmentid
      }
    },
    // 查看严重违法主体名单
    showEntbaseList() {
      this.showEntbase = true
    },
    // 移除文件回调
    removeFile(file) {
      removeAttachementById(file.id).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 加载审核人
    loadReviewer() {
      getUsersWithPermission('approveSerIllegal', 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;
      display: flex;
      align-items: center;
      .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;
    }
  }
</style>
<style lang="scss">
  .main-content.abnormal{
     font-size: $table-content-font-size;
    .el-form-item{
      margin-bottom:0;
      background: $color-form-label;
      font-size: $table-content-font-size;
      .el-form-item__label{
        padding-left: 10px;
        font-size: $table-content-font-size;
        border-top: 1px solid $color-border;
      }
      .el-form-item__content{
        background: white;
        padding: 10px;
        font-size: $table-content-font-size;
        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;
    }
  }
</style>
