<template>
  <div class="main-content deregist">
    <div class="content-header">
      <img src="../../../assets/images/icon-text.png" alt="" style="width:24px;margin-right:10px">
      <span class="title">业务办理</span>
    </div>
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="180px" 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 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 class="bt0">
                <el-form-item label="解锁原因" prop="unlockreason">
                  <div style="display:inline-block;width: 600px">
                    <el-input v-model="unlockReason" type="textarea" :autosize="{ minRows: 4 }" />
                  </div>
                </el-form-item>
              </el-row>
              <el-row class="bt0 p0">
                <el-form-item label="材料上传" class="upload">
                  <el-upload
                    :action="uploadPath"
                    :data="{bizseq:bizseq}"
                    :on-remove="removeFile"
                    :on-success="uploadCallback"
                    :on-preview="previewFile"
                    :before-upload="beforeFileUpload"
                    :before-remove="beforeRemove"
                    accept=".doc,.docx,.xlsx,.xls,.pdf,.jpg,.zip,.rar,.7z"
                    multiple
                    :file-list="fileList"
                    style="max-width:800px;display: inline-block"
                    class="uploadFileList"
                  >
                    <!-- <el-button size="small" type="primary">点击上传</el-button> -->
                    <div style="display: inline-block;">
                      <el-button style="display: inline-block;" type="primary">点击上传</el-button>
                      <div slot="tip" style="display: inline-block;" class="el-upload__tip">只能上传jpg/png/pdf/doc/docx/xls/xlsx/rar/zip/7z文件，且单个文件不能超过20M</div>
                    </div>
                  </el-upload>
                </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>
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>经办意见</label></div>
          </div>
          <div class="form-body">
            <el-row>
              <el-form-item label="经办意见" prop="opinion">
                <div style="display:inline-block;">
                  <el-col :span="24" style="margin-bottom:10px">
                    <el-input v-model="form.opinion" type="textarea" placeholder="请输入经办意见" :autosize="{ minRows: 2}" />
                  </el-col>
                  <el-col :span="24">
                    <label>常用语</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>

                </div>
              </el-form-item>
            </el-row>
            <el-row class="bt0">
              <el-form-item label="审核人" prop="reviewerId">
                <el-select v-model="form.reviewerId" clearable filterable placeholder="请选择审核人" class="custom">
                  <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>
    <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 :show-overflow-tooltip="true" label="主体名称" min-width="150" align="left">
          <template slot-scope="scope">
            <a style="color:blue;cursor:pointer" @click="Entdetail(scope.row)">{{ scope.row.entname }}</a>
          </template>
        </el-table-column>
        <!--        <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="150" 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-column prop="address" label="地址" min-width="110" align="left" />
        <el-table-column :prop="state||regstate" label="主体状态" min-width="110" align="left" :formatter="statusFormat" />
        <el-table-column prop="regorg" label="主体登记机关" min-width="110" align="left" :formatter="regOrgFormat" />
        <!--        <el-table-column prop="ulockSpecificReason" label="解锁具体原因" min-width="110" align="left" />-->
      </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 { delFile, listAttachmentByBizseq } from '@/api/attachment'
import { getPunishFromList, getLockTypeList, unlockNext, getEntLockPageandPunishFrom, getStatusList, getRegorgList } from '@/api/punishment'
import { getUsersWithPermission } from '@/api/user'
import { validBeforeUpload } from '@/api/fileUpload'
import { taskOpinion } from '@/api/task'
import { isMenHu } from '@/utils/utils'

import axios from 'axios'
export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      ReceiverName: '',
      punishFrom: '',
      punishFromList: [],
      punishFromStr: '',
      lockTypeOptions: [],
      entLockList: [],
      unlockReason: '',
      commonUnlockReason: '联合惩戒企业，现已改正失信行为，解除限制。',
      uploadPath: `${process.env.VUE_APP_BASE_API}/attachment/uploadFileByBizseq`,
      showEntbase: false,
      bizseq: '',
      workflowId: '',
      tasklistid: '',
      submitLoading: false,
      entbase: [], // 主体名单列表
      // 分页数据,这里用来保存每页切割后的数据
      // 看起来格式是这样的[[{},{},{}],[{},{},{}]]
      // 数组内套数组，每个数组就是一页数据
      totalPageData: [],
      // 共几页
      pageNum: '',
      // 每页显示数量
      pageSize: 10,
      // 当前显示页码
      currentPage: 1,
      // 总共多少条数据
      total: 1,
      // 当前要显示的数据
      dataShow: [],
      // 选中数组
      multipleSelection: [],
      form: {
        opinion: ''
      },
      formRules: {
        opinion: [
          { required: true, message: '请输入经办意见', trigger: ['blur', 'change'] }
        ],
        reviewerId: [
          { required: true, message: '请选择审核人' }
        ],
        unlockreason: [
          { required: true, message: '请输入解锁原因' }
        ]
      },
      complaintTypeStr: '',
      researchResult: '',
      remarks: '',
      isSet: '1',
      reason: '',
      opinion: '',
      reasonOptions: [],
      opinionOptions: [{
        value: 0,
        label: '拟同意,呈领导审核。'
      }],
      historyLog: [],
      exmainerOptions: [],
      fileList: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      reviewer: [],
      pageParam: {
        customParamMap: { bizseq: '' },
        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
    },
    // punishFrom() {
    //   this.punishFromList.forEach(each => {
    //     if (each.value === this.punishFrom) {
    //       // this.punishFromStr = each.label
    //       this.$set(this, 'punishFromStr', each.label)
    //       if (this.$util.isEmpty(this.unlockReason)) {
    //         this.$set(this, 'unlockReason', this.punishFromStr + this.commonUnlockReason)
    //       }
    //     }
    //   })
    // },
    // unlockReason() {
    //   this.$set(this.form, 'unlockreason', this.unlockReason)
    // }
    unlockReason() {
      if (this.unlockReason === '' || this.unlockReason === null) {
        this.unlockReason = '企业已吊销、撤销、注销或未在惩戒名单中,解除限制'
      }
      this.$set(this.form, 'unlockreason', this.unlockReason)
    }
  },
  mounted() {
    this.bizseq = this.$route.query.bizseq // 获取跳转携带的参数bizseq
    this.workflowId = this.$route.query.workflowId
    this.tasklistid = this.$route.query.tasklistid
    // 加载常用语
    this.opinionOptions = this.$util.getCommonWordsWithModule(this.user.primaryKey, '联合惩戒')

    this.pageParam.customParamMap.bizseq = this.bizseq
    this.statusList = getStatusList()
    this.regorgList = getRegorgList()
    debugger
    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
        /* 6月8日 */
        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
    },
    // 登记机关格式化6月5日新增
    regOrgFormat(row) {
      let name = ''
      this.regorgList.forEach(each => {
        if (each.value === row.regorg) {
          name = each.label
        }
      })
      return name
    },
    statusFormat(row) {
      let name = ''
      if (row.elid !== null) {
        this.statusList.forEach(each => {
          if (each.value === row.state) {
            name = each.label
          }
        })
      }
      if (row.lockstate === '0') {
        name = '解锁'
      } else if (row.lockstate === '1') {
        name = '锁定'
      }
      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
        for (const i in this.reviewer) {
          if (this.reviewer[i].primaryKey === this.form.reviewerId) {
            this.ReceiverName = this.reviewer[i].name
          }
        }
        this.$confirm('是否确认发送 ' + this.ReceiverName + ' 审核？', '提示').then(() => {
          this.form.bizseq = this.bizseq
          this.form.workflowid = this.workflowId
          this.form.opiniontype = '0'
          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
          this.form.nextNodeID = 'handlePunish'
          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()
              }
            } else {
              this.$message.error(res.msg)
            }
          })
        })
      })
    },
    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
      // downLoadFile(file.id).then(res => {
      //   this.download2(res, '')
      // })
    },
    // download2(data, fileName) {
    //   debugger
    //   if (!data) {
    //     return
    //   }
    //   const dataInfo = data
    //   const reader = new window.FileReader()
    //   // 使用readAsArrayBuffer读取文件, result属性中将包含一个 ArrayBuffer 对象以表示所读取文件的数据
    //   reader.readAsArrayBuffer(dataInfo)
    //   reader.onload = function(e) {
    //     const result = e.target.result
    //     const contentType = dataInfo.type
    //     // 生成blob图片,需要参数(字节数组, 文件类型)
    //     const blob = new Blob([result], { type: contentType })
    //     // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
    //     const url = window.URL.createObjectURL(blob)
    //     console.log(url) // 产生一个类似 blob:d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串
    //     window.open(url)
    //   }
    // },
    uploadCallback(res, file) {
      if (res.code === 0) {
        file.filename = res.data.filename
        file.id = res.data.attachmentid
        file.url = `${process.env.VUE_APP_DOWNLOAD_URL}` + res.data.temppath
        this.$message.success('上传成功')
      }
    },
    // 上传文件之前校验大小
    beforeFileUpload(file) {
      var that = this
      return validBeforeUpload(file, that)
    },
    // 移除文件前
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name} ？`)
      }
    },
    // 查看主体名单
    showEntbaseList() {
      this.showEntbase = !this.showEntbase
    },
    // 移除文件回调
    removeFile(file) {
      if (file && file.status === 'success') {
        delFile(file.id).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 加载审核人
    loadReviewer() {
      // / getUsersWithPermission('punishUnlockHandle', this.user.orgId).then(res => {
      getUsersWithPermission('punishUnlockEnter', this.user.orgId).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    },
    Entdetail(row) {
      this.$router.push({ path: '/comprehensive/details', query: { pripid: row.pripid }})
    }
  }
}
</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;
      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;
  }
  .form-body.history.none{
    font-size: 14px;
  }
  .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;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    color: #1c1e23;
  }
  .el-input__inner{
    margin-bottom: 5px;
  }
  .uploadFileList{
    .el-upload-list__item{
      display: inline-block;
      width: auto;
    }
  }
}
</style>
