<template>
  <div class="main-content abnormal">
    <!-- <DetailHead :result="查询结果" /> -->
    <!-- <div class="content-header"> -->
    <!-- <img src="../../../../assets/images/icon-text.png" alt="" style="width:24px;margin-right:10px">
      <span class="title">查询结果</span> -->
    <!-- <el-button type="warning" icon="el-icon-caret-left" size="mini" class="back-btn" @click="$router.back()">返回上一层</el-button> -->
    <!-- </div> -->
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="180px" label-position="right" :rules="formRules">
        <div class="form">

          <div class="tab" v-if="bizList.length === 1">
            <div class="tab-title">
              <label>
                主体信息
              </label>
            </div>
          </div>
          <div class="form-body">
            <el-row v-if="bizList.length === 1">
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" class="bt0">
                  <span>{{ bizList[0].uniscid }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主体名称" class="bt0">
                  {{ bizList[0].entname }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="bizList.length === 1">
              <el-col :span="24">
                <el-form-item label="经营地址" class="bt0">
                  <span>{{ bizList[0].address }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="bizList.length === 1">
              <el-col :span="12">
                <el-form-item label="成立日期" class="bt0">
                  <span>{{ bizList[0].estDate }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法定代表人" class="bt0">
                  {{ bizList[0].lerepname }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="bizList.length === 1">
              <el-col :span="12">
                <el-form-item label="主体类型" class="bt0">
                  <span>{{ bizList[0].entTypeName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主体状态" class="bt0">
                  {{ bizList[0].regstateCn }}
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="tab">
            <div class="tab-title">
              <label>
                异常信息
              </label>
            </div>
          </div>
          <div class="form-body">
            <el-row v-if="bizList.length > 1">
              <el-form-item label="列入异常主体信息">
                <el-button size="medium" type="primary" @click="showEntbaseList">查看异常主体名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
                <el-button size="medium" type="primary" @click="exportEntListExcel">导出Excel<i class="el-icon" style="margin-left:5px" /></el-button>
                <el-button v-if="remList.length > 0" size="medium" type="primary" @click="showRemEntList">查看已剔除名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="列入原因" required class="bt0">
                <el-col :span="24">
                  <el-select v-model="reason" style="width:100%" placeholder="请选择列入原因" class="custom" :disabled="isBatchNB">
                    <el-option
                      v-for="item in reasonOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="案件来源" required prop="caseSource" class="bt0">
                <el-col :span="24">
                  <el-select v-model="caseSource" style="width:100%" placeholder="请选择案件来源" class="custom" >
                    <el-option
                      v-for="item in caseSourceOptions"
                      :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="decisionContent" class="bt0">
                <el-col :span="24">
                  <el-input v-model="decisionContent" style="width:100%" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>

            <!-- <el-form-item label="事实理由" prop="spereasons">
              <el-input v-model="spereasons" 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 v-if="dataFrom === '3'" label="现场核查人员" prop="remark" class="bt0">
                <el-col :span="24">
                  <div style="margin-top: 10px">{{regEntryUserName}}</div>
                  <!--                  <el-input v-model="regEntryUserName" placeholder="现场核查人员" style="width:100%" disabled maxlength="500" show-word-limit />-->
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remark" class="bt0">
                <el-col :span="24">
                  <el-input v-model="remark" type="textarea" placeholder="备注" style="width:100%" :autosize="{ minRows: 3, maxRows: 6 }" maxlength="500" show-word-limit />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="材料上传" class="upload bt0">
                <el-upload
                  :action="uploadPath"
                  :data="{bizseq:bizseq, attachtype: '2'}"
                  :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"
                >
                  <div style="display: inline-block;">
                    <el-button size="medium" style="display: inline-block;margin-right:10px" 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">
            <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="endApply">
                <el-radio v-model="form.endApply" label="1">列入</el-radio>
                <el-radio v-if="showRadio" v-model="form.endApply" label="3">线索回退</el-radio>
                <el-tooltip class="item" effect="dark" content="“列异模块”不生成列异线索，“市场所监管模块”保留现场核查记录。" placement="top">
                  <el-radio v-if="showRadio" v-model="form.endApply" label="4">线索作废</el-radio>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="结束当前经办人的流程。“列异模块”保留列异线索，其他经办人可继续办理线索" placement="top">
                  <el-radio v-model="form.endApply" label="5">结束流程</el-radio>
                </el-tooltip>
                <!--<el-radio v-if="historyLog.length > 1" v-model="form.endApply" label="2">结束</el-radio>--> <!-- 同样需要审核 -->
              </el-form-item>
            </el-row>
            <el-row v-if="form.endApply === '5'">
              <el-form-item label="结束原因" prop="endReason">
                <el-col :span="24">
                  <el-input v-model="form.endReason" type="textarea" placeholder="请输入结束原因" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row v-if="form.endApply === '4'">
              <el-form-item label="作废原因" prop="deleteReason">
                <el-col :span="24">
                  <el-input v-model="form.deleteReason" type="textarea" placeholder="请输入作废原因" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row v-if="form.endApply === '3'">
              <el-form-item label="回退原因" prop="returnReason">
                <el-col :span="24">
                  <el-input v-model="form.returnReason" type="textarea" placeholder="请输入回退原因" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>
            <!-- <el-row v-if="form.endApply === '2'">
              <el-form-item label="结束原因" prop="endReason">
                <el-col :span="24">
                  <el-input v-model="form.endReason" type="textarea" placeholder="请输入结束原因" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row> -->
            <template v-if="form.endApply === '1'">
              <el-row>
                <el-form-item label="经办意见" prop="opinion" class="bt0">
                  <el-col :span="24" class="mb10">
                    <el-input v-model="form.opinion" type="textarea" placeholder="请输入经办意见" :autosize="{ minRows: 2, maxRows: 6 }" />
                  </el-col>
                  <el-col :span="12">
                    <label style="line-height:32px">常用语</label>
                    <el-select v-model="opinion" placeholder="请选择" clearable 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>
            </template>

          </div>
        </div>
      </el-form>
      <div class="submit-box">
        <el-button v-if="form.endApply === '3'" type="primary" :loading="submitLoading" @click="returnAbnClue">线索回退</el-button>
        <el-button v-else-if="form.endApply === '4'" type="primary" :loading="submitLoading" @click="deleteAbnClue">线索作废</el-button>
        <el-button v-else-if="form.endApply === '5'" type="primary" :loading="submitLoading" @click="submitForm">结束流程</el-button>
        <el-button v-else type="primary" :loading="submitLoading" @click="submitForm">提交</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>
    <el-dialog
      title="异常主体名单"
      :visible.sync="showEntbase"
      width="90%"
    >
      <!--      <span style="color:red;">这批核查主体的同一地址为：{{bizList[0].checkAddress}}</span>-->
      <el-table
        v-loading="loading"
        :data="bizList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="bizList.length > 1" class="no" type="selection" min-width="20" align="center" />
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="210" align="left" />
        <el-table-column prop="address" :show-overflow-tooltip="true" label="经营地址" min-width="180" align="left" />
        <el-table-column prop="estDate" :show-overflow-tooltip="true" label="成立日期" min-width="80" align="left" />
        <el-table-column prop="lerepname" label="法定代表人" min-width="80" align="left" />
        <el-table-column prop="entTypeName" :show-overflow-tooltip="true" label="主体类型" min-width="120" align="left" />
        <el-table-column prop="regstateCn" :show-overflow-tooltip="true" label="主体状态" min-width="100" align="left" />
      </el-table>
      <template v-if="this.multipleSelection.length > 0">
        <el-row style="margin-bottom: 5px;margin-top:2px;border: unset">
          <label style="float: left;margin-left:10px;font-size:16px">剔除原因：</label>
          <el-input v-model="removeReason" style="width: 90%;" :autosize="{ minRows: 1 }" type="textarea" />
        </el-row>
      </template>
      <div>
        <el-row class="bl0">
          <el-col :span="12">
            <el-pagination
              :current-page="pageParam.curPage"
              small
              layout="prev, pager, next"
              :total="pageParam.total"
              @size-change="pageSizeChange"
              @current-change="pageIndexChange"
            />
          </el-col>
          <el-col :span="12">
            <div class="dialog-box">
              <el-button v-if="bizList.length > 1" type="danger" size="mini" @click="removeEntbaseItem">剔除</el-button>
              <el-button type="primary" size="mini" @click="showEntbaseList">确定</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog
      title="已剔除主体名单"
      :visible.sync="showRemEnt"
      width="90%"
    >
      <el-table
        v-loading="loading"
        :data="remList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="210" align="left" />
        <el-table-column prop="removeReason" :show-overflow-tooltip="true" label="剔除原因" min-width="180" align="left" />
        <el-table-column
          prop="removeTime"
          :show-overflow-tooltip="true"
          label="剔除时间"
          min-width="80"
          align="left"
        />
        <el-table-column prop="removeHandler" label="剔除处理人" min-width="80" align="left" />
      </el-table>
      <div>
        <el-row class="bl0">
          <el-col :span="12">
            <el-pagination
              :current-page="remPageParam.curPage"
              small
              layout="prev, pager, next"
              :total="remPageParam.total"
              @size-change="remPageSizeChange"
              @current-change="remPageIndexChange"
            />
          </el-col>
          <el-col :span="12">
            <div class="dialog-box">
              <el-button type="primary" size="mini" @click="showRemEntList">确定</el-button>
            </div>
          </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 { returnClue, deleteClue, nextAbnormaInclusionProcess,
  getBizSpeListPage, removeBySpelistid, searchBizSpeByBizSeqId, getDecContent, validateBiz, down, checkIsBatchNB } from '@/api/abnormal'
import { getUsersPermission } from '@/api/user'
import { validBeforeUpload } from '@/api/fileUpload'
import { getConstant } from '@/api/system'
import { parseTime } from '@/utils'
import { taskOpinion } from '@/api/task'
export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      remPageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'rem'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      remList: [],
      showRemEnt: false,
      removeReason: '',
      decisionContent: '',
      prepareContent: '',
      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: [],
      spereasons: '',
      remark: '',
      dataFrom: '',
      regEntryUserName: '',
      form: {
        enterType: 'company',
        spereasons: '',
        remark: '',
        reason: '',
        opinion: '',
        decisionContent: '',
        endApply: '1',
        endReason: ''
      },
      formRules: {
        caseSource: [
          { required: true, message: '请选择案件来源', trigger: 'change' }
        ],
        endReason: [
          { required: true, message: '请输入结束原因', trigger: 'blur' }
        ],
        decisionContent: [
          { required: true, message: '请输入决定书内容', trigger: 'blur' }
        ],
        specause: [
          { required: true, message: '请输入列入原因', trigger: 'blur' }
        ],
        opinion: [
          { required: true, message: '请输入经办意见', trigger: ['blur', 'change'] }
        ],
        reviewerId: [
          { required: true, message: '请选择审核人' }
        ],
        returnReason: [
          { required: true, message: '请输入回退原因', trigger: 'blur' }
        ],
        deleteReason: [
          { required: true, message: '请输入作废原因', trigger: 'blur' }
        ]
      },
      reason: '',
      opinion: '',
      reasonOptions: [],
      opinionOptions: [],
      historyLog: [],
      exmainerOptions: [],
      fileList: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      reviewer: [],
      pageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'biz'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      bizList: [], // 异常主体名单分页列表
      loading: false,
      bizType: '',
      showRadio: false,
      isBatchNB: false,
      // 其他已有的数据配置...
      caseSourceOptions: [
        { value: '1', label: '涉投诉实地查无' },
        { value: '2', label: '涉行政执法实地查无' },
        { value: '9', label: '其他' }
      ],
      caseSource: '' // 绑定下拉框的选中值，默认空
    }
  },
  watch: {
    // 原因渲染
    'reason': {
      handler(newValue, oldValue) {
        this.form.specause = newValue
        let name = ''
        this.reasonOptions.forEach(each => {
          if (this.reason === each.value) {
            name = each.label
          }
        })
        this.form.reason = name
        // 调用接口请求，选择不同原因时对应的模板
        if (this.$util.isNotEmpty(newValue) && oldValue !== '') {
          getDecContent({
            specause: this.reason,
            entertype: this.bizType
          }).then(res => {
            if (res.code === 0) {
              this.decisionContent = res.data
            }
          })
        }
      }

    },
    // 新增案件来源的监听器
    'caseSource': {
      handler(newValue) {
        // 同步选中值到表单的 caseSource 字段（与校验规则的 prop 对应）
        this.form.caseSource = newValue

        // 可选：如果需要显示中文名称，可在这里同步（类似 reason 的逻辑）
        let name = ''
        this.caseSourceOptions.forEach(item => {
          if (newValue === item.value) {
            name = item.label
          }
        })
        this.form.caseSourceName = name // 如需保存中文名称，可新增此字段
      },
      immediate: true // 初始化时立即执行一次，确保初始值同步
    },
    decisionContent() {
      this.$set(this.form, 'decisionContent', this.decisionContent)
    },
    // 意见渲染
    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

    // 加载企业列入原因
    const loading = this.$loading({
      lock: true,
      text: '正在加载..',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    Promise.all([
      // 加载异常名录主体
      this.loadBizSpeListPage().then(res => {
        // 判断类型，加载对应原因列表
        let baseCode = ''
        let permission = ''
        let commonWordsType = ''
        if (this.bizType === 'company') {
          baseCode = 'CD71'
          permission = 'exptInclueHandle'
          commonWordsType = '企业经营异常名录列入'
        } else if (this.bizType === 'individual') {
          baseCode = 'CD75'
          permission = 'individualMarkReview'
          commonWordsType = '个体户经营异常状态标记'
        } else if (this.bizType === 'farmer') {
          baseCode = 'CD77'
          permission = 'agricultureInclusionReview'
          commonWordsType = '农专社经营异常名录列入'
        }
        this.getReasonList(baseCode)
        // 加载审核人
        this.loadReviewer(permission)
        // 加载常用语
        this.opinionOptions = this.$util.getCommonWordsWithModule(this.user.primaryKey, commonWordsType)
        return
      }).then(res => {
        // 加载处办记录
        return taskOpinion(this.workflowId).then(res => {
          if (res.code === 0) {
            res.data.forEach(each => {
              if (this.bizType === 'company') {
                switch (each.opiniontype) {
                  case '9':
                  case '1': each.step = '经办'
                    break
                  case '2': each.step = '审核'
                    break
                  case '3': each.step = '审批'
                    break
                }
              } else {
                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('加载处办记录失败')
          }
        })
      }),
      checkIsBatchNB({ bizSeq: this.bizseq }).then(res => {
        this.isBatchNB = res.data
      }),
      this.loadRemListPage(),
      // listAbnormalByBizSeq(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.typeName = each.entTypeName
      //       // this.$set(this, 'reason', each.specause)
      //       this.entbase.push(each)
      //     })
      //     this.reason = this.entbase[0].specause
      //     this.remark = this.entbase[0].remark === 'null' ? '' : this.entbase[0].remark
      //     if (this.entbase[0].decisionContent !== null) {
      //       this.$nextTick(() => {
      //         this.decisionContent = this.entbase[0].decisionContent
      //       })
      //     }
      //     // 分页处理
      //     this.total = this.entbase.length
      //     // 计算页数
      //     this.calcPageData()
      //   } else {
      //     this.$message.error('加载异常名录主体信息失败')
      //   }
      // }),

      // 加载附件清单
      listAttachmentByBizseq(this.bizseq).then(data => {
        const list = []
        data.forEach(each => {
          if (each.attachtype !== '0') {
            each.id = each.attachmentid
            each.name = each.filename
            each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
            list.push(each)
          }
        })
        this.fileList = list
        // 加载线索过来的附件
        // if (this.$util.isNotEmpty(this.bizList[0].dataFromId)) {
        //   listAttachmentByBizseq(this.bizList[0].dataFromId).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.push(each)
        //     })
        //   })
        // }
      })
    ]).finally(() => {
      loading.close()
    })
  },
  methods: {
    // 加载列入原因
    getReasonList(code) {
      return getConstant(code).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.reason !== '') {
            let name = ''
            this.reasonOptions.forEach(each => {
              if (this.reason === each.value) {
                name = each.label
              }
            })
            this.form.reasonStr = name
          }
        }
      })
    },
    loadBizSpeListPage() {
      if (this.loading) return
      this.loading = true
      this.pageParam.customParamMap.bizseq = this.bizseq
      return getBizSpeListPage(this.pageParam).then((res) => {
        const list = []
        let i = 1
        const pageStart =
          (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.records.forEach((each) => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.bizList = list
        this.loading = false
        this.pageParam.total = res.data.total
        this.dataFrom = this.bizList[0].dataFrom
        this.regEntryUserName = this.bizList[0].regEntryUserName
        this.reason = this.bizList[0].specause
        this.caseSource = this.bizList[0].caseSource
        this.remark = this.bizList[0].remark === 'null' ? '' : this.bizList[0].remark
        this.bizType = this.bizList[0].type
        if (this.$util.isNotEmpty(this.bizList[0].toIncludeId)) { // 如果拟列异id不为空，则是线索列异流程，展示线索回退等选项
          this.$set(this, 'showRadio', true)
        }
        if (this.bizList[0].decisionContent !== null) {
          this.$nextTick(() => {
            this.decisionContent = this.bizList[0].decisionContent
          })
        }
        const selection = JSON.parse(JSON.stringify(this.multipleSelection))
        this.$nextTick(() => {
          for (const i in list) {
            const each = list[i]
            for (const j in selection) {
              if (each.pripid === selection[j].pripid) {
                this.$refs.bizList.toggleRowSelection(each, true)
              }
            }
          }
        })
      })
    },
    // 加载已剔除名单
    loadRemListPage() {
      this.loading = true
      this.remPageParam.customParamMap.bizseq = this.bizseq
      return getBizSpeListPage(this.remPageParam).then((res) => {
        const list = []
        let i = 1
        const pageStart =
          (this.remPageParam.curPage - 1) * this.remPageParam.pageSize
        res.data.records.forEach((each) => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.remList = list
        this.loading = false
        this.remPageParam.total = res.data.total
      })
    },
    // 剔除名单列表分页大小改变
    remPageSizeChange(pageSize) {
      this.remPageParam.pageSize = pageSize
      this.loadRemListPage()
    },
    // 剔除名单列表当前分页改变
    remPageIndexChange(curPage) {
      this.remPageParam.curPage = curPage
      this.loadRemListPage()
    },
    parseTime(...args) {
      return parseTime(...args)
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadBizSpeListPage()
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadBizSpeListPage()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 主体名单导出Excel
    exportEntListExcel() {
      this.$confirm('是否确认导出', '提示').then(() => {
        const url = location.origin + process.env.VUE_APP_BASE_API + '/bizSpeList/exportEntList?bizseq=' + this.bizseq
        window.open(url)
      })
    },
    // 上传文件之前校验大小
    beforeFileUpload(file) {
      var that = this
      return validBeforeUpload(file, that)
    },
    // 移除文件前
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name} ？`)
      }
    },
    // 剔除主体名单
    removeEntbaseItem() {
      if (this.multipleSelection.length === 0) return this.$message.warning('请至少选择一个主体从此列表中剔除')
      if (this.$util.isEmpty(this.removeReason)) return this.$message.warning('请输入剔除原因')
      this.$confirm('是否确认剔除', '提示').then(() => {
        // 遍历获取spelistid 拼接成字符串形式
        let ids = ''
        this.multipleSelection.forEach(each => {
          ids += (each.spelistid + ';')
        })
        // 调接口
        removeBySpelistid(ids.substring(0, ids.length - 1), this.removeReason, this.bizseq).then(res => {
          if (res.code === 0) {
            this.loadBizSpeListPage()
            this.loadRemListPage()
            this.$message.success('剔除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    download2(data, fileName) {
      if (!data) {
        return
      }
      console.log(data)
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }))
      // window.open(url)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      // document.body.appendChild(link)
      link.click()
    },
    // 上传文件预览
    previewFile(file) {
      if (file.createtype === '2') { // 双随机系统附件
        down(file.id).then(res => {
          this.download2(res, file.name)
        }).catch(req => {
          console.log('下载失败', req)
        })
      } else {
        if (['.jpg', '.png', '.jpeg', '.bmp'].includes(file.fileext)) {
          const fileList = this.fileList
          const imges = []
          let index = 0
          let indextemporary = 0
          for (let i = 0; i < fileList.length; i++) {
            if (['.jpg', '.png', '.jpeg', '.bmp'].includes(fileList[i].fileext) && fileList[i].createtype !== '2') {
              imges.push(fileList[i].url)
              if (file.id === fileList[i].id) {
                index = indextemporary
              }
              // 下一张图片的下标
              indextemporary++
            }
          }
          this.$hevueImgPreview({
            multiple: true, // 开启多图预览模式
            nowImgIndex: index, // 多图预览，默认展示第几张图片
            imgList: imges
          })
        } else {
          window.open(file.url, '_blank')
        }
      }
    },
    // 线索作废
    deleteAbnClue() {
      if (this.$util.isEmpty(this.form.deleteReason)) {
        return this.$message.warning('请先输入作废原因！')
      }
      this.submitLoading = true
      deleteClue({
        toIncludeId: this.bizList[0].toIncludeId,
        deleteReason: this.form.deleteReason,
        dataFromId: this.bizList[0].dataFromId
      }).then(res => {
        this.submitLoading = false
        if (res.code === 0) {
          this.$message.success('提交成功')
          this.$router.back()
        }
      })
    },
    // 线索回退
    returnAbnClue() {
      // if (this.bizList[0].dataFrom === '2') {
      //   this.$alert('双随机线索回退功能完善中，如需紧急办理业务，请联系监管人员到【市场所协同】-【现场核查】重新录入检查结果。', '提示', {
      //     confirmButtonText: '确定'
      //   })
      //   return
      // }
      if (this.$util.isEmpty(this.form.returnReason)) {
        return this.$message.warning('请先输入回退原因！')
      }
      this.submitLoading = true
      returnClue({
        tasklistid: this.tasklistid,
        bizseq: this.bizseq,
        toIncludeId: this.bizList[0].toIncludeId,
        returnReason: this.form.returnReason
      }).then(res => {
        this.submitLoading = false
        if (res.code === 0) {
          this.$message.success('提交成功')
          this.$router.back()
        }
      })
    },
    // 发送提交
    submitForm() {
      if (this.$util.isEmpty(this.form.specause)) {
        return this.$message.warning('请输入列入原因')
      }
      if (this.$util.isEmpty(this.form.caseSource)) {
        return this.$message.warning('请选择案件来源')
      }
      console.log(this.form.specause)
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.showRadio) { // 线索列异要再校验一次作提示
          validateBiz({ ids: this.bizList[0].toIncludeId, validType: 'CLUE', entertype: this.bizType, checkInBiz: 'false' }).then(res => {
            if (res.code === 0) {
              let str = ''
              let type = 'info'
              if (res.data.length > 0) {
                for (const item of res.data) {
                  str += item.entname + item.reason + '；'
                }
                if (this.form.endApply === '5') {
                  str += '是否结束流程？'
                }else{
                  str += '是否继续提交？'
                }
                type = 'warning'
              } else {
                if (this.form.endApply === '5') {
                  str = '是否结束流程？'
                }else{
                  str = '是否继续提交？'
                }
              }
              this.$confirm(str, '提示', { type: type }).then(() => {
                this.submitLoading = true
                this.form.bizseq = this.bizseq
                this.form.workflowid = this.workflowId
                this.form.opiniontype = this.bizType === 'company' ? '1' : '0'
                this.form.handler = this.user.username
                this.form.handlerid = this.user.primaryKey
                this.form.opinioncontent = this.form.opinion
                this.form.spereasons = this.spereasons
                this.form.remark = this.remark
                this.form.decisionContent = this.decisionContent
                this.form.nextPerformerids = this.form.reviewerId
                this.form.caseSource = this.caseSource // 关键：绑定选中值到表单
                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'
                if (this.form.endApply === '5') {
                  this.form.nextNodeID = 'overFinish'
                  this.form.opinioncontent = this.form.endReason
                }
                nextAbnormaInclusionProcess({
                  tasklistid: this.tasklistid,
                  bizseq: this.bizseq,
                  nextNodeID: this.form.nextNodeID,
                  opinion: {
                    opiniontype: this.form.opiniontype,
                    handler: this.user.username,
                    handlerid: this.user.primaryKey,
                    handledate: this.form.handledate,
                    opinioncontent: this.form.opinioncontent
                  },
                  nextPerformerIds: [this.form.nextPerformerids],
                  nextPerformerNames: [this.form.nextPerformerNames],
                  tsBizSpeListModel: this.form
                }).then(res => {
                  this.submitLoading = false
                  if (res.code === 0) {
                    this.$message.success('提交成功')
                    this.$router.back()
                  }
                })
              }).catch(() => {})
            }
          })
        } else {
          this.$confirm('是否确认提交', '提示').then(() => {
            this.submitLoading = true
            this.form.bizseq = this.bizseq
            this.form.workflowid = this.workflowId
            this.form.opiniontype = this.bizType === 'company' ? '1' : '0'
            this.form.handler = this.user.username
            this.form.handlerid = this.user.primaryKey
            this.form.opinioncontent = this.form.opinion
            this.form.spereasons = this.spereasons
            this.form.remark = this.remark
            this.form.decisionContent = this.decisionContent
            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'
            if (this.form.endApply === '5') {
              this.form.nextNodeID = 'overExptlist'
              this.form.opinioncontent = this.form.endReason
            }
            nextAbnormaInclusionProcess({
              tasklistid: this.tasklistid,
              bizseq: this.bizseq,
              nextNodeID: this.form.nextNodeID,
              opinion: {
                opiniontype: this.form.opiniontype,
                handler: this.user.username,
                handlerid: this.user.primaryKey,
                handledate: this.form.handledate,
                opinioncontent: this.form.opinioncontent
              },
              nextPerformerIds: [this.form.nextPerformerids],
              nextPerformerNames: [this.form.nextPerformerNames],
              tsBizSpeListModel: this.form
            }).then(res => {
              this.submitLoading = false
              if (res.code === 0) {
                this.$message.success('提交成功')
                // this.$router.back()
                this.$router.push('/todo/list')
              }
            })
          }).catch(() => {})
        }
      })
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        file.id = res.data.attachmentid
        file.filename = res.data.filename
        file.url = `${process.env.VUE_APP_DOWNLOAD_URL}` + res.data.temppath
        file.fileext = res.data.fileext
        file.createtype = res.data.createtype
        this.fileList.push(file)
        this.$message.success('上传成功')
      }
    },
    // 查看异常主体名单
    showEntbaseList() {
      this.showEntbase = !this.showEntbase
    },
    // 查看已剔除主体名单
    showRemEntList() {
      this.showRemEnt = !this.showRemEnt
    },
    // 移除文件回调
    removeFile(file) {
      if (file && file.status === 'success') {
        removeAttachementById(file.id).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            // 移除列表中元素
            const fileList = this.fileList
            let index = 0
            for (let i = 0; i < fileList.length; i++) {
              if (file.id === fileList[i].id) {
                index = i
              }
            }
            this.fileList.splice(index,1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 加载审核人
    loadReviewer(permission) {
      return getUsersPermission(permission, this.user.orgId, this.bizseq, this.bizType).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{
      background: #8cc3fb;
      height: 50px;
      line-height: 40px;
      text-align: center;
      .tab-title{
        label{
          color: #fff;
          font-size: 20px;
          display:inline-block;
          padding:5px;
        }
      }
    }
    .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;
  }
}
.content-body{
  background: #fff;
}
/deep/.el-table .warning-row {
  background: #eaf4fe!important;
}
</style>
<style lang="scss">
.main-content.abnormal{
  font-size: $table-content-font-size;
  .el-form-item{
    margin-bottom:0;
    background: $color-form-label;
    .el-form-item__label{
      padding: 25px 10px 10px 10px;
      font-size: $table-content-font-size;
      border-top: 1px solid $color-border;
      line-height: 0!important;
    }
    .el-form-item__content{
      background: white;
      padding: 5px;
      /*line-height: 0px!important;*/
      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;
    font-size: $table-content-font-size;
  }
  .form-body.history .none{
    font-size: $table-content-font-size;
  }
  .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;
    }
  }
  .dialog-box{
    text-align: right;
  }
  .upload .el-form-item__label::after{
    display: inline-block;
    // content: '()';
    color: #F56C6C;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    color: #1c1e23;
  }
  .el-input__inner{
    margin-bottom: 5px;
  }
  .handle-dialog.mid>.main-dialog{
    min-height: 300px;
    width: 75vw;
  }
  .uploadFileList{
    .el-upload-list__item{
      display: inline-block;
      width: auto;
    }
  }
  .el-step__description{
    font-size: 18px;
  }
}

</style>
