<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="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 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="锁定原因">
                  <div style="display:inline-block;width: 100%">
                    <el-input v-model="lockReason" type="textarea" :autosize="{ minRows: 4 }" disabled />
                  </div>
                </el-form-item>
              </el-row>
              <el-row class="bt0">
                <el-form-item label="惩戒来源">
                  <div style="display:inline-block;width: 100%">
                    <el-input v-model="punishFromStr" type="textarea" :autosize="{ minRows: 4 }" disabled>
                      {{ showpunishFrom }}
                    </el-input>
                  </div>
                </el-form-item>
              </el-row>
              <el-row class="bt0">
                <el-form-item label="惩戒措施">
                  <div style="display:inline-block;width: 100%">
                    <el-input v-model="measure" type="textarea" :autosize="{ minRows: 4 }" disabled />
                  </div>
                </el-form-item>
              </el-row>
              <el-row class="bt0">
                <el-form-item label="锁定类型" prop="locktype">
                  <span>{{ locktype }}</span>
                </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" target="_blank" @click="previewFile(item)">{{ 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>
        <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="reviewPunish">通过</el-radio>-->
                <el-radio v-model="form.nextNodeID" label="reviewPunish">通过</el-radio>
                <!--<el-radio v-model="form.nextNodeID" label="overPunish">不通过</el-radio>-->
                <el-radio v-model="form.nextNodeID" label="punishEnter">回退</el-radio>  <!-- 回退至经办人 -->
              </el-form-item>
            </el-row>
            <el-row class="bt0">
              <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" clearable placeholder="请选择" 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 v-if="form.nextNodeID == 'reviewPunish'" label="审批人" prop="reviewerId">
                <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>
    <HandleDialog class="content" :show.sync="showEntbase" title="主体名单">
      <el-table
        :data="dataShow"
        tooltip-effect="dark"
        size="mini"
        style="width: 100%; min-height: 400px;"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column class="no" type="selection" min-width="20" align="center" />
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uniscid" label="统一社会信用代码" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="150" align="left" />
        <el-table-column prop="estdate" :show-overflow-tooltip="true" label="成立日期" min-width="90" align="left" />
        <el-table-column prop="dom" :show-overflow-tooltip="true" label="经营地址" min-width="150" align="left" />
        <el-table-column prop="name" label="法定代表人" align="left" />
        <!-- <el-table-column prop="sendtime" label="发送时间" align="left" /> -->
        <el-table-column prop="enttypeCn" :show-overflow-tooltip="true" label="企业类型" min-width="100" align="left" />
        <!--        <el-table-column prop="entStatus" :show-overflow-tooltip="true" label="企业状态" min-width="120" align="left" />-->
        <el-table-column prop="regstateCn" :show-overflow-tooltip="true" label="企业状态" min-width="120" align="left" :formatter="regStateformat" />
      </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 { getUsersWithPermission } from '@/api/user'
import { taskOpinion } from '@/api/task'
import { getPunishFromList, getEntInfoPageandPunishFrom, next, getLockTypeList, getRegStateNameList } from '@/api/punishment'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      measure: '',
      locktype: '',
      lockTypeOptions: [],
      infoList: [],
      lockReason: '',
      punishFromList: [],
      punishFrom: '',
      punishFromStr: '',
      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: 'reviewPunish'
      },
      formRules: {
        opinion: [
          { required: true, message: '请输入经办意见', trigger: ['blur', 'change'] }
        ],
        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: [],
      pageParam: {
        customParamMap: { bizseq: '' },
        curPage: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  computed: {

    showpunishFrom() {
      debugger
      let str = this.punishFromStr
      this.punishFromList.forEach(each => {
        if (each.value === this.punishFrom) {
          str = each.label
        }
      })
      this.punishFromStr = str
      return this.punishFromStr
    }
  },
  watch: {
    // 意见渲染
    opinion() {
      debugger
      let name = ''
      this.opinionOptions.forEach(each => {
        if (this.opinion === each.value) {
          name = each.label
        }
      })
      this.form.opinion = name
    }
    // punishFrom() {
    //   debugger
    //   let name = ''
    //   this.punishFromList.forEach(each => {
    //     if ( this.punishFrom === each.label) {
    //       name = each.value
    //     }
    //   })
    //   this.punishFromStr = name
    // }

    // punishFrom() {
    //   this.punishFromList.forEach(each => {
    //     if (each.value === this.punishFrom) {
    //       // this.punishFromStr = each.label
    //       this.$set(this, 'punishFromStr', each.label)
    //       this.$set(this, 'lockReason', '1、' + this.punishFromStr + '联合惩戒要求进行限制；' + this.commonLockReason)
    //     }
    //   })
    // }
  },
  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.lockTypeOptions = getLockTypeList()
    this.regStateList = getRegStateNameList()
    this.punishFromList = getPunishFromList()

    this.pageParam.customParamMap.bizseq = this.bizseq
    getEntInfoPageandPunishFrom(this.pageParam).then(res => {
      if (res.code === 0) {
        debugger
        this.punishFrom = res.data.punishFrom
        this.lockReason = res.data.lockReason
        this.measure = res.data.measure
        this.lockTypeOptions.forEach(each => {
          if (each.value === res.data.locktype) {
            this.locktype = each.label
          }
        })
        const list = []
        let i = 1
        const pageStart = (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.page.forEach(each => {
          each.index = pageStart + i++
          each.typeName = each.entTypeName
          if (each.estdate !== null) {
            each.estdate = each.estdate.substr(0, 10)
          }
          this.entbase.push(each)
        })
        this.total = this.entbase.length
        this.calcPageData()
      } else {
        this.$message.error(res.msg)
      }
    })

    // 加载惩戒来源
    // this.punishFromList = getPunishFromList()

    // 加载处办记录
    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()

    // 加载附件清单
    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'
      }
    },
    // 惩戒来源格式化
    punishFromFormat(list, value) {
      list.forEach(each => {
        console.log(each)
        if (each.value === value) {
          // this.punishFromStr = each.label
          this.$set(this, 'punishFromStr', each.label)
          console.log(this.punishFromStr)
        }
      })
    },
    regStateformat(row) {
      let name = ''
      this.regStateList.forEach(each => {
        if (each.value === row.regstate) {
          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
          this.form.nextPerformerids = 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
            }
          }
          if (this.form.nextNodeID === 'punishEnter') {
            this.form.nextPerformerids = ''
            this.form.nextPerformerNames = ''
          }
          this.submitLoading = true
          next(this.form).then(res => {
            this.submitLoading = false
            if (res.code === 0) {
              // if (this.form.nextNodeID === 'reviewPunish' && this.user.primaryKey === this.form.reviewerId) {
              //   this.$router.push({ path: '/punish/inclusion/reviewAgain', query: { tasklistid: res.data.taskListId, bizseq: res.data.bizseq, workflowId: res.data.workFlowId }})
              // } else {
              //   this.$message.success('提交成功')
              //   this.$router.back()
              // }
              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, 'url')
    },
    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('punishUnlockReview', this.user.orgId).then(res => {
      getUsersWithPermission('punishLockHandle', this.user.orgId).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.deregist{
  .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-left: 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>
