<template>
  <div class="main-content deregist">
    <DetailHead />
    <div class="content-body">
      <el-form
        ref="form"
        :model="form"
        label-width="200px"
        label-position="right"
        :rules="formRules"
      >
        <div class="form">
          <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 !== '' && entLockList.length>1" label="主体名单">
                  <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 !== '' && entLockList.length === 1" label="主体名称">
                  <span>{{ entLockList[0].entname }}</span>
                </el-form-item>
              </el-row>
              <el-row class="bt0">
                <el-form-item label="解锁原因" prop="unlockReason">
                  <div style="display:inline-block;width: 100%">
                    <el-input v-model="unlockReason" type="textarea" :autosize="{ minRows: 4 }" disabled />
                  </div>
                </el-form-item>
              </el-row>
              <el-row class="bt0 p0">
                <el-form-item label="材料列表">
                  <ul style="list-style:none;padding:0;margin:5px">
                    <li v-for="item in fileList" :key="item.id" style="line-height: 30px">
                      <el-link class="list-style" :href="item.url" target="_blank">{{ item.name }}</el-link>
                    </li>
                  </ul>
                </el-form-item>
              </el-row>

            </div>
          </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>
      </el-form>
      <div class="submit-box">
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>
    <HandleDialog :show.sync="showEntbase" title="主体名单">
      <el-table
        :data="dataShow"
        tooltip-effect="dark"
        size="mini"
        style="width: 100%; min-height: 400px;"
        :fit="true"
        :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column class="no" type="selection" min-width="20" align="center" />
        <el-table-column prop="index" label="序号" min-width="45" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="140" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="150" align="left" />
        <el-table-column prop="locktype" :show-overflow-tooltip="true" label="锁定类型" min-width="80" align="left" :formatter="lockTypeFormat" />
        <!-- <el-table-column :show-overflow-tooltip="true" label="锁定状态" min-width="80" align="left" /> -->
        <el-table-column prop="lockreason" :show-overflow-tooltip="true" label="锁定原因" min-width="200" align="left" />
        <el-table-column prop="lockusername" label="锁定人" min-width="60" align="left" />
        <el-table-column prop="lockTime" label="锁定时间" min-width="110" align="left" :formatter="dateTimeFormat" />
      </el-table>
      <el-row>
        <el-col :span="18">
          <el-pagination
            :current-page="currentPage"
            small
            layout="prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
        <el-col :span="6">
          <div class="dialog-box">
            <!-- <el-button type="danger" size="mini" @click="removeEntbaseItem">剔除</el-button> -->
            <el-button type="primary" size="mini" @click="showEntbaseList">确定</el-button>
          </div>
        </el-col>
      </el-row>
    </HandleDialog>
  </div>
</template>

<script>
import DetailHead from '@/components/DetailHead'
import HandleDialog from '@/components/HandleDialog'
import { removeAttachementById, listAttachmentByBizseq } from '@/api/attachment'
import { getPunishFromList, getLockTypeList, unlockNext, getEntLockPageandPunishFrom } from '@/api/punishment'
import { getUsersWithPermission } from '@/api/user'
import { taskOpinion } from '@/api/task'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      searchNameP: '',
      punishFrom: '',
      punishFromList: [],
      punishFromStr: '',
      lockTypeOptions: [],
      entLockList: [],
      unlockReason: '',
      uploadPath: `${process.env.VUE_APP_BASE_API}/attachment/uploadAdvance`,
      showEntbase: false,
      bizseq: '',
      workflowId: '',
      tasklistid: '',
      submitLoading: false,
      entbase: [], // 主体名单列表
      // 分页数据,这里用来保存每页切割后的数据
      // 看起来格式是这样的[[{},{},{}],[{},{},{}]]
      // 数组内套数组，每个数组就是一页数据
      totalPageData: [],
      // 共几页
      pageNum: '',
      // 每页显示数量
      pageSize: 10,
      // 当前显示页码
      currentPage: 1,
      // 总共多少条数据
      total: 1,
      // 当前要显示的数据
      dataShow: [],
      // 选中数组
      multipleSelection: [],
      form: {
        opinion: '',
        nextNodeID: 'endPunish'
      },
      formRules: {
        opinion: [
          { required: true, message: '请输入审批意见', trigger: 'blur' }
        ],
        reviewerId: [
          { required: true, message: '请选择审核人' }
        ]
      },
      complaintTypeStr: '',
      researchResult: '',
      remarks: '',
      isSet: '1',
      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: '王东'
      }],
      pageParam: {
        customParamMap: { bizseq: '', searchName: '' },
        curPage: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  watch: {
    // 意见渲染
    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 // 获取跳转携带的参数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.pageParam.customParamMap.searchName = this.searchNameP

    this.pageParam.customParamMap.bizseq = this.bizseq
    getEntLockPageandPunishFrom(this.pageParam).then(res => {
      if (res.code === 0) {
        this.unlockReason = res.data.unlockReason
        this.punishFrom = res.data.punishFrom
        const list = []
        let i = 1
        const pageStart = (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.page.forEach(each => {
          each.index = pageStart + i++
          each.uscc = each.uniscid || each.regno
          this.entbase.push(each)
        })
        this.total = this.entbase.length
        this.calcPageData()
      } else {
        this.$message.error(res.msg)
      }
    })
    // 加载处办记录
    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('加载处办记录失败')
      }
    })
    // 加载审核人
    // this.loadReviewer()
    // 加载惩戒来源
    this.punishFromList = getPunishFromList()
    // 加载锁定类型
    this.lockTypeOptions = getLockTypeList()

    // 加载附件清单
    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'
      }
    },
    dateTimeFormat(row) {
      return this.$util.formatDate.format(new Date(Date.parse(row.lockTime)), 'yyyy-MM-dd hh:mm:ss')
    },
    lockTypeFormat(row) {
      let name = ''
      this.lockTypeOptions.forEach(each => {
        if (each.value === row.locktype) {
          name = each.label
        }
      })
      return name
    },
    // 计算页数
    calcPageData() {
      // 计算页数
      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++) {
        this.totalPageData[i] = this.entbase.slice(this.pageSize * i, this.pageSize * (i + 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
      this.dataShow = this.totalPageData[newPageNum - 1]
    },
    // 剔除主体名单
    removeEntbaseItem() {
      if (this.multipleSelection.length === 0) return this.$message.error('请至少选择一个企业从此列表中剔除')
      this.$confirm('是否确认剔除', '提示').then(() => {
        console.log(this.multipleSelection)
        // 遍历获取spelistid 拼接成字符串形式
        let ids = ''
        this.multipleSelection.forEach(each => {
          ids += (each.spelistid + ';')
        })
        // 调接口
        removeBySpelistid(ids.substring(0, ids.length - 1)).then(res => {
          if (res.code === 0) {
            this.multipleSelection.forEach(each => {
            // 表示先获取这个元素的下标，然后从这个下标开始计算，删除长度为1的元素
              this.entbase.splice(this.entbase.indexOf(each), 1)
            })
            let i = 1
            const pageStart = (this.currentPage - 1) * this.pageSize
            this.entbase.forEach(each => {
              each.index = pageStart + i++
            })
            // 重新计算页数
            this.calcPageData()
            this.$message.success('剔除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 提交
    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.user.primaryKey
          this.form.nextPerformerNames = this.user.username

          // for (const i in this.reviewer) {
          //   if (this.reviewer[i].primaryKey === this.form.reviewerId) {
          //     this.form.nextPerformerNames = this.reviewer[i].name
          //   }
          // }
          this.submitLoading = true
          unlockNext(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()
              }
            }
          })
        })
      })
    },
    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        file.id = res.data.attachmentid
      }
    },
    // 查看主体名单
    showEntbaseList() {
      this.showEntbase = !this.showEntbase
    },
    // 移除文件回调
    removeFile(file) {
      removeAttachementById(file.response.data.attachmentid).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 加载审核人
    loadReviewer() {
      getUsersWithPermission('abnormalReview', this.user.orgId).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.deregist{
  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;
    }
  }
}
</style>
<style lang="scss">
.main-content.deregist{
  font-size: $table-content-font-size;
  .el-form-item{
    margin-bottom:0;
    background: $color-form-label;
    .el-form-item__label{
      padding-left: 10px;
      border-top: 1px solid $color-border;
      border-left: 1px solid $color-border;
      font-size: $table-content-font-size;
    }
    .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;
      font-size: $table-content-font-size;
    }
  }
  .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-table-column--selection .cell {
    padding-right: 0px;
  }
  .no {
    padding-left: 0px;
  }
  .el-table_9_column_61.is-left.is-leaf{
    .cell{
      padding-left: 0px;
      padding-right: 0px;
    }
  }
  .handle-dialog.mid>.main-dialog{
    min-height: 300px;
    width: 75vw;
  }
  .el-pagination{
    text-align: left;
  }
  .dialog-box{
    text-align: right;
  }
  .upload .el-form-item__label::after{
    display: inline-block;
    content: '(单个文件不能超过20M)';
    color: #F56C6C;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    color: #1c1e23;
  }
  .el-input__inner{
    margin-bottom: 5px;
  }
}
</style>
