<template>
  <div class="main-content abnormal m20">
    <DetailHead />
    <!-- <el-row class="content-header">
      <el-col :span="6" style="padding:15PX 10PX;">
        <span class="title">经营异常名录移出：经办</span>
      </el-col>
      <el-col :span="18">
        <el-button type="warning" icon="el-icon-caret-left" size="mini" class="back-btn" @click="$router.back()">返回上一层</el-button>
      </el-col>
    </el-row> -->
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="190px" 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="p10 lh0">
              <el-form-item label="移出异常主体信息">
                <el-button size="mini" type="primary" @click="showEntbaseList">{{ entname }}<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>

            <!-- <el-form-item label="事实理由" prop="remreasons">
              <el-input v-model="form.remreasons" type="textarea" placeholder="请输入事实理由" style="display:inline-block;width:600px" :autosize="{ minRows: 3, maxRows: 6 }" maxlength="500" show-word-limit />
            </el-form-item> -->
            <el-row>
              <el-form-item label="移出原因" prop="reason" class="bt0">
                <el-col :span="24">
                  <el-select v-model="reason" style="width:100%" placeholder="请选择移出原因" class="custom">
                    <el-option
                      v-for="item in reasonOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-col>
                <el-col :span="24">
                  <el-input v-model="form.reason" type="textarea" disabled style="width:100%" />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remRemark" class="bt0">
                <el-input v-model="remRemark" type="textarea" placeholder="备注" style="display:inline-block;width:100%" :autosize="{ minRows: 3, maxRows: 6 }" maxlength="500" show-word-limit />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="材料上传" class="upload bt0">
                <el-upload
                  :action="uploadPath"
                  :data="{bizseq:bizseq}"
                  :on-remove="removeFile"
                  :on-success="uploadCallback"
                  :on-preview="previewFile"
                  :before-upload="beforeFileUpload"
                  :before-remove="beforeRemove"
                  multiple
                  :file-list="fileList"
                  accept=".doc,.docx,.xlsx,.xls,.pdf,.jpg,.zip,.rar,.7z"
                  style="max-width:800px;display: inline-block"
                  class="uploadFileList"
                >
                  <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 class="form">
          <div class="tab">
            <div class="tab-title"><label>历史移出记录</label></div>
          </div>
          <div class="form-body history content-body">
            <div v-if="removeRecordList.length == 0" class="none">暂无移出记录</div>
            <el-table
              v-else
              :data="removeRecordList"
              border
              style="width: 100%"
              :row-class-name="tableRowClassName"
              :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
            >
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column prop="abntime" label="列入日期" min-width="100" />
              <el-table-column prop="specause" :formatter="intoReasonFormat" :show-overflow-tooltip="true" label="列入原因" min-width="200" />
              <el-table-column prop="intoSponsor" label="列入主办人" min-width="100" />
              <el-table-column prop="remdate" label="移出日期" min-width="100" />
              <el-table-column prop="remexcpres" :formatter="remReasonFormat" :show-overflow-tooltip="true" label="移出原因" min-width="200" />
              <el-table-column prop="remSponsor" label="移出主办人" min-width="100" />
            </el-table>
          </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">
                <el-col :span="24">
                  <el-input v-model="form.opinion" type="textarea" placeholder="请输入经办意见" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
                <el-col :span="12">
                  <label>常用语</label>
                  <el-select v-model="opinion" clearable placeholder="请选择" class="custom" style="width:100%">
                    <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 label="审核人" prop="reviewerId" class="bt0">
                <el-col :span="12">
                  <el-select v-model="form.reviewerId" style="width:100%" filterable clearable placeholder="请选择审核人" class="custom">
                    <el-option
                      v-for="item in reviewer"
                      :key="'reviewer'+item.primaryKey"
                      :label="item.name"
                      :value="item.primaryKey"
                    />
                  </el-select>
                </el-col>
              </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="异常主体名单" style="width:50vw">
      <el-table
        :data="dataShow"
        tooltip-effect="dark"
        style="width: 1200px"
        :fit="true"
        height="500px"
        :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column class="no" type="selection" min-width="20" />
        <el-table-column prop="index" label="序号" min-width="35" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="150" 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="成立时间" 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="enttypeCn" :show-overflow-tooltip="true" label="企业类型" min-width="150" align="left" />
      </el-table>
      <div>
        <el-row class="bl0">
          <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 class="dialog-box">
          <!-- <el-button type="danger" @click="removeEntbaseItem">剔除</el-button> -->
          <el-button type="primary" @click="showEntbaseList">确定</el-button>
        </div>
      </div>
    </HandleDialog>
  </div>
</template>

<script>
import DetailHead from '@/components/DetailHead'
import HandleDialog from '@/components/HandleDialog'
import { removeAttachementById, listAttachmentByBizseq } from '@/api/attachment'
import { bizRemoveNext, getBizRemInfo, removeBizRemListBySplistid, getBizRemoveRecordList } from '@/api/abnormal'
import { getUsersWithPermission } from '@/api/user'
import { getConstant, getCD72 } from '@/api/system'
import { validBeforeUpload } from '@/api/fileUpload'
import { taskOpinion } from '@/api/task'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      remRemark: '',
      submitLoading: false,
      entname: '',
      removeRecordList: [],
      uploadPath: `${process.env.VUE_APP_BASE_API}/attachment/uploadAdvance`,
      showEntbase: false,
      bizseq: '',
      workflowId: '',
      tasklistid: '',
      entbase: [], // 主体名单列表
      // 分页数据,这里用来保存每页切割后的数据
      // 看起来格式是这样的[[{},{},{}],[{},{},{}]]
      // 数组内套数组，每个数组就是一页数据
      totalPageData: [],
      // 共几页
      pageNum: '',
      // 每页显示数量
      pageSize: 10,
      // 当前显示页码
      currentPage: 1,
      // 总共多少条数据
      total: 1,
      // 当前要显示的数据
      dataShow: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }],
      // 选中数组
      multipleSelection: [],
      form: {
        enterType: 'company',
        remreasons: '',
        reason: '',
        remRemark: '',
        opinion: ''
      },
      formRules: {
        reason: [
          { required: true, message: '请输入移出原因', trigger: 'blur' }
        ],
        opinion: [
          { required: true, message: '请输入经办意见', trigger: ['blur', 'change'] }
        ],
        reviewerId: [
          { required: true, message: '请选择审核人' }
        ]
      },
      reason: '',
      opinion: '',
      reasonOptions: [],
      inclueReasonOptions: [],
      opinionOptions: [],
      historyLog: [],
      exmainerOptions: [],
      fileList: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      reviewer: []
    }
  },
  watch: {
    // 原因渲染
    reason() {
      this.form.remexcpres = 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 // 获取跳转携带的参数bizseq
    this.workflowId = this.$route.query.workflowId
    this.tasklistid = this.$route.query.tasklistid

    // 加载常用语
    this.opinionOptions = this.$util.getCommonWords(this.user.primaryKey)
    // 加载企业移出原因
    getCD72().then(res => {
      if (res.code === 0) {
        const list = []
        res.data.forEach(each => {
          list.push({
            value: each.code,
            label: each.name
          })
        })
        this.reasonOptions = list
      }
    })
    // 加载企业列入原因
    getConstant('CD71').then(res => {
      if (res.code === 0) {
        const list = []
        res.data.forEach(each => {
          list.push({
            value: each.code,
            label: each.name
          })
        })
        this.inclueReasonOptions = list
      }
    })
    // 加载待移出主体名单及 事实理由
    getBizRemInfo(this.bizseq).then(res => {
      if (res.code === 0) {
        // 添加分页index
        const list = []
        let i = 1
        const pageStart = (this.currentPage - 1) * this.pageSize
        res.data.bizList.forEach(each => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno // 有统一码显示统一码 没有用注册号
          list.push(each)
        })
        this.entbase = list
        const bizInfo = res.data.bizRemListMOdel
        this.entname = bizInfo.entname
        this.$set(this, 'reason', bizInfo.remexcpres)
        this.remRemark = bizInfo.remRemark
        // 分页处理
        this.total = this.entbase.length
        // 计算页数
        this.calcPageData()
      } else {
        this.$message.error('加载异常名录主体信息失败')
      }
    })

    // 获取主体移出记录
    getBizRemoveRecordList(this.bizseq).then(res => {
      if (res.code === 0) {
        this.removeRecordList = res.data
      } else {
        this.$message.error('加载移出记录失败')
      }
    })
    // 加载审核人
    this.loadReviewer()
    // 加载处办记录
    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('加载处办记录失败')
      }
    })
    // 加载附件清单
    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'
      }
    },
    // 列入原因格式化
    intoReasonFormat(row) {
      return this.$util.enumFormatter(this.inclueReasonOptions, row.specause)
    },
    // 移出原因格式化
    remReasonFormat(row) {
      return this.$util.enumFormatter(this.reasonOptions, row.remexcpres)
    },
    // 上传文件之前校验大小
    beforeFileUpload(file) {
      var that = this
      return validBeforeUpload(file, that)
    },
    // 移除文件前
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name} ？`)
      }
    },
    // 计算页数
    calcPageData() {
      // 计算页数(根据后台数据的条数和每页显示数量算出一共几页,得0时设为1)
      if (this.entbase.length >= 1) {
        this.pageNum = Math.ceil(this.entbase.length / this.pageSize) || 1
      }
      // 数据分组
      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]
    },
    // 每页条数发生变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize
      // 重新计算页数并分组
      this.calcPageData()
    },
    // 当前页码发生变化
    handleCurrentChange(newPageNum) {
      this.currentPage = newPageNum
      // 这里仍然不要忘记减去1
      this.dataShow = this.totalPageData[newPageNum - 1]
    },
    // 剔除主体名单
    removeEntbaseItem() {
      if (this.multipleSelection.length === 0) return this.$message.error('请至少选择一个企业从此列表中剔除')
      this.$confirm('是否确认剔除', '提示').then(() => {
        // 遍历获取pripid 拼接成字符串形式
        let ids = ''
        this.multipleSelection.forEach(each => {
          ids += (each.pripid + ';')
        })
        // 调接口
        removeBizRemListBySplistid(this.tasklistid, this.bizseq, 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
    },

    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    // 发送提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return this.$message.error('请先填完所有必填信息！')
        this.$confirm('是否确认提交？', '提示').then(() => {
          this.submitLoading = true
          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.entertype = 'company'
          if (this.$util.isNotEmpty(this.remRemark)) {
            this.form.remRemark = this.remRemark
          } else {
            this.form.remRemark = ''
          }
          this.form.tasklistid = this.tasklistid
          // this.form.nextPerformerids = this.user.primaryKey
          // this.form.nextPerformerNames = this.user.username
          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.form.nextNodeID = 'handleExptlist'
          bizRemoveNext(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 = !this.showEntbase
    },
    // 移除文件回调
    removeFile(file) {
      if (file && file.status === 'success') {
        removeAttachementById(file.id).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 加载审核人
    loadReviewer() {
      getUsersWithPermission('exptRemoveHandle', 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;
  .back-btn{
    margin-top: 6px;
    position:absolute;
    right:40pt;
  }
  .content-body{
    background: white;
    padding:15PX 10PX;
    border:1PX solid #eee;
  }
  .content-header{
    background: white;
    height:50PX;
    border:1PX solid #eee;
    display: flex;
    align-items: center;
    .title{
      font-weight: 600;
      font-size: 1rem;
    }
  }
  .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;
      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;
  }
  .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;
    }
  }
  .el-pagination{
    text-align: right;
  }
  .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>
