<template>
  <div class="page">
    <easy-form
      ref="EasyForm"
      v-model="data"
      :fields="fields"
      :form-config="formConfig"
      :buttons="buttons"
    >
      <template v-slot:fixuploader="{options,formData,field,isView}">
        <div class="fixuploader">
          <div v-for="(item,index) in options" :key="item.value" class="fixuploader-item">
            <span class="index">{{ Number(index)+1 }}</span>
            <span class="label" :class="{canDownload: !!formData[field.prop][item.value]}" @click="previewFile(formData[field.prop][item.value],formData.bizSeqNo,index)">{{ item.label }}</span>
            <svg-icon :class="{ hidden: !formData[field.prop][item.value] }" icon-class="success" />
            <el-button size="small" type="primary" class="upload" @click="previewFile(formData[field.prop][item.value],formData.bizSeqNo,index)">
              查看
            </el-button>
            <el-upload
              v-if="!isView"
              class="upload"
              :action="action"
              :data="{
                attachtype: item.value,
                bizseq: formData.bizSeqNo
              }"
              :show-file-list="false"
              :on-success="(response, file)=>{
                $set(formData[field.prop], item.value, file)
              }"
            >
              <el-button size="small" type="primary">
                点击上传
              </el-button>
            </el-upload>
            <el-button
              size="small"
              :class="{
                hidden: !item.template
              }"
              class="download-tmp"
              type="primary"
              plain
              @click="downloadTemplate(item)"
            >下载模板</el-button>
          </div>
        </div>
      </template>
      <template v-slot:opinion="scope">
        <div class="opinion-selector">
          <span class="opinion-selector-text">常用语</span>
          <el-select
            v-model="scope.field.opinion"
            size="medium"
            placeholder="请选择常用语"
            @change="(val)=>{
              scope.formData[scope.field.prop] = val
              scope.easyFormItemBindData.componentScope.formInstance.clearValidate(scope.field.prop)
            }"
          >
            <el-option
              v-for="item in scope.field.options"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </template>
    </easy-form>
  </div>
</template>

<script>
import { getUsersWithPermission } from '@/api/user'
import {
  xrAttachmentDelLawFile
} from '@/api/abnormal'
import { attachmentListByBizSepNo, tswrittemplateGetContentsWithBizseq, userGetOrgunits, xrSeriousIllegalPersonRemListListByBizSeqNo } from '@/api/auto-baseapi'
import { createGlobalLoading, parseTime } from '@/utils'
export default {
  data() {
    return {
      authItemMap: [],
      parseTime,
      action: process.env.VUE_APP_BASE_API + '/attachment/uploadFileByBizseq',
      nextPerformerMap: [],
      nextSequenceFlowList: [],
      data: {},
      status: '',
      taskLikeId: '',
      showFakeProgress: false,
      orgs: [], // 登记机关树
      uploadPath: process.env.VUE_APP_BASE_API + '/xrBizSpeList/fileParamExplainLr',
      type: this.$route.meta.type,
      localSelection: '当前部门处理人', // 默认值
      flowModel: [],
      selectedNextNodeEnd: false,
      selectedIsReturn: false,
      formConfig: {
        labelPosition: 'right',
        buttonPosition: 'right',
        gutter: 0,
        isView: () => {
          return this.readonly
        }
      },
      fields: [
        {
          type: 'divider',
          label: '自然人移出严重违法失信名单申请信息'
        },
        {
          type: 'input',
          label: '身份证号',
          prop: 'cerNo',
          span: 12,
          isView: true
        },
        {
          type: 'input',
          label: '姓名',
          prop: 'inv',
          span: 12,
          isView: true
        },
        {
          type: 'select',
          label: '证件类型',
          prop: 'cerType',
          span: 12,
          isView: true,
          optionsBaseCode: 'CB16'
        },
        {
          type: 'date-picker',
          label: '列入时间',
          prop: 'abnTime',
          formProps: {
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd'
          },
          span: 12,
          isView: true
        },
        {
          type: 'date-picker',
          label: '申请时间',
          prop: 'applyTime',
          formProps: {
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            format: 'yyyy-MM-dd'
          },
          span: 12
        },
        {
          type: 'input',
          label: '申请人',
          prop: 'applicant',
          span: 12
        },
        {
          type: 'select',
          label: '列入原因',
          prop: 'serIllRea',
          required: true,
          span: 24,
          optionsBaseCode: 'CD73',
          isView: true
        },
        {
          type: 'slot',
          slotName: 'fixuploader',
          label: '证据材料',
          prop: 'fixuploader',
          defaultValue: () => {
            return {}
          },
          span: 24,
          options: [
            {
              label: '信用修复申请书',
              value: '10',
              template: '10'
            },
            {
              label: '已公示年度报告信息截图',
              value: '5'
            },
            {
              label: '守信承诺书',
              value: '8',
              template: '8'
            },
            {
              label: '履行法定义务，纠正违法行为的相关材料',
              value: '12'
            },
            {
              label: '身份证照片',
              value: '13'
            },
            {
              label: '其他材料',
              value: '14'
            }
          ]
        },
        {
          type: 'divider',
          label: ({ formData }) => {
            return ({
              '0': '经办意见',
              '1': '审核意见',
              '2': '审批意见'
            })[formData.status]
          },
          showInForm: () => {
            return !this.readonly
          }
        },
        {
          type: 'radio',
          label: '选择操作',
          prop: 'isAgreeRepair',
          required: true,
          span: 24,
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          },
          showInForm: () => {
            return !this.readonly
          },
          options: ({ formData }) => {
            return [
              {
                label: '准予修复',
                value: '1'
              },
              {
                label: '不予修复',
                value: '2'
              }
            ]
          }
        },
        {
          type: 'select',
          label: '移出原因',
          prop: 'remExcpRes',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            // 只有选择了操作且nextNode.end === false时才显示移出原因
            return !!formData.isAgreeRepair && !this.selectedNextNodeEnd
          },
          optionsBaseCode: 'CD74',
          onChange: ({ formData }, value, fromUser) => {
            if (fromUser) {
              // 根据是否是退回操作决定使用哪个模板
              // 退回/补正使用p2，正常流程使用p3
              const writsType = this.selectedIsReturn ? 'p2' : 'p3'
              tswrittemplateGetContentsWithBizseq({
                bizseq: this.$route.query.bizSeqNo,
                type: 'naturalPerson',
                needTemplate: '1',
                writsType: writsType
              }).then((response) => {
                if (response.code === 0) {
                  const data = response.data || {}
                  formData.decisionContent = data.content
                }
              })
            }
          },
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          }
        },
        {
          type: 'textarea',
          label: '决定书内容 ',
          prop: 'decisionContent',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            // 只有选择了操作且nextNode.end === false时才显示决定书内容
            return !!formData.isAgreeRepair && !this.selectedNextNodeEnd
          },
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          }
        },
        {
          type: 'input',
          label: '退回原因',
          prop: 'backProposal',
          required: true,
          span: 24,
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          },
          showInForm: ({ formData }) => {
            // 只有选择了操作且是退回/补正操作时显示退回原因
            return !!formData.isAgreeRepair && this.selectedIsReturn
          }
        },
        {
          type: 'input',
          label: '结束原因',
          prop: 'notRepaired',
          required: true,
          span: 24,
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          },
          showInForm: ({ formData }) => {
            // 只有选择了操作且nextNode.end === true时显示结束原因
            return !!formData.isAgreeRepair && this.selectedNextNodeEnd
          }
        }
      ],
      buttons: [
        {
          label: '返回',
          type: 'primary',
          show: true,
          buttonProps: {
            plain: true
          },
          handler: (scope) => {
            this.$router.back()
          }
        },
        {
          label: '下一步',
          type: 'primary',
          show: ({ formData }) => {
            return !this.readonly && !!formData.isAgreeRepair && !this.selectedNextNodeEnd && !this.selectedIsReturn
          },
          handler: ({ formInstance }) => {
            return formInstance.submitForm().then(() => {
              console.log(this.data)

              this.$emit('next-tab', this.data)
            })
          }
        }
      ]
    }
  },
  computed: {
    readonly() {
      return this.type === 'history'
    }
  },
  async created() {
    const bizSeqNo = this.$route.query.bizSeqNo
    await createGlobalLoading(() => {
      // 公共查询：意见记录和附件列表
      const commonQueries = [
        this.fetchAttachmentList(bizSeqNo)
      ]

      if (this.readonly) {
        // 历史记录：公共查询 + bizSeqNo查询业务信息
        return Promise.all([
          ...commonQueries,
          this.fetchTaskDetail(bizSeqNo)
        ])
      } else {
        return Promise.all([
          ...commonQueries,
          this.fetchTaskDetail(bizSeqNo)
        ])
      }
    }).finally(() => {
      this.inited = true
    })
  },
  methods: {
    // 查询附件列表
    fetchAttachmentList(bizSeqNo) {
      return Promise.all(['9', '10', '11', '12', '13', '14'].map((attachType) => {
        return attachmentListByBizSepNo({
          bizseq: bizSeqNo,
          attachtype: attachType
        }).then((response) => {
          const data = response.data || []
          this.data = {
            ...this.data,
            fixuploader: {
              ...(this.data.fixuploader || {}),
              [attachType]: data[data.length - 1]
            }
          }
        })
      }))
    },
    // 通过 bizSeqNo 查询任务详情（历史记录和待办使用）
    fetchTaskDetail(bizSeqNo) {
      return xrSeriousIllegalPersonRemListListByBizSeqNo({ bizSeqNo }).then((response) => {
        if (response.code !== 0) {
          this.$message.error(response.msg || '获取任务详情失败')
          return
        }
        // 接口返回的是 XrSeriousIllegalPersonSpeList对象，扁平结构
        const detailData = response.data || {}
        const taskId = detailData.taskListId
        this.taskLikeId = taskId
        // 直接使用返回的数据
        this.data = {
          ...this.data,
          ...detailData,
          taskId: taskId,
          bizSeqNo: this.$route.query.bizSeqNo
        }
        // 加载登记机关树并转换decOrg为中文
        return this.loadOrgunits().then(() => {
          // 转换decOrg为中文名称（登记机关）
          if (this.data.decOrg) {
            const orgName = this.findOrgName(this.orgs, this.data.decOrg)
            this.data.regOrgCn = orgName || this.data.decOrg
          }
        })
      })
    },
    // 加载登记机关树
    loadOrgunits() {
      if (this.orgs.length > 0) {
        return Promise.resolve()
      }
      return userGetOrgunits({}).then((response) => {
        if (response.code === 0) {
          this.orgs = response.data || []
        }
      })
    },
    // 在机关树中查找指定orgUnitId的名称
    findOrgName(orgs, orgUnitId) {
      if (!orgs || orgs.length === 0) return null
      // 将查询值转为字符串，避免类型不匹配
      const targetId = String(orgUnitId)
      for (const org of orgs) {
        if (String(org.orgUnitId) === targetId) {
          return org.label
        }
        // 递归查找子节点
        if (org.children && org.children.length > 0) {
          const name = this.findOrgName(org.children, targetId)
          if (name) {
            return name
          }
        }
      }
      return null
    },
    stepStatus2CN(opinionType) {
      return ({
        'handle': '经办',
        'examine': '审核',
        'approve': '审批'
      })[opinionType]
    },
    removeFile(file) {
      return xrAttachmentDelLawFile({
        id: file.attachmentId
      })
    },
    previewFile(file) {
      window.open(`${process.env.VUE_APP_BASE_API}/xrAttachment/getMaterial?id=${file.attachmentId || file?.response?.data?.attachmentId}&bizSeqNo=${file.bizSeqNo}&attachType=${file.attachType}`, '_blank')
    },
    getUsersWithPermission(isUpper) {
      const ps = []
      const status = this.data.status || '0'
      const permission = ({
        '0': 'xrExamine',
        '1': 'xrApprove'
      })[status]
      if (permission) {
        ps.push(getUsersWithPermission(
          permission,
          this.$store.getters.orgId,
          isUpper
        ).then((response) => {
          if (response.code === 0) {
            const userList = response.data || []
            this.nextPerformerMap = userList.map(item => ({
              label: item.name,
              value: item.primaryKey
            }))
          }
        }))
      }
      return Promise.all(ps)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-handle";
/deep/ .easy-form-col-fixuploader{
  .el-form-item__content{
    padding: 0!important;
  }
  .fixuploader{
    .fixuploader-item{
      display: flex;
      padding: 12px 12px 12px 24px;
      border-bottom: 1px solid #F4F4F4;
      align-items: center;
      font-size: 14px;
      .index{
        width: 32px;
        display: inline-block;
        color: #999999;
        flex-shrink: 0;
      }
      .label{
        color: #333333;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
        &.canDownload{
          cursor: pointer;
        }
      }
      .svg-icon{
        margin: 0 55px 0 auto;
        flex-shrink: 0;
      }
      .upload{
        margin-right: 12px;
        flex-shrink: 0;
      }
      .hidden{
        opacity: 0;
        pointer-events: none;
      }
    }
  }
}
.opinion-selector{
  margin-top: 18px;
  display: flex;
  .opinion-selector-text{
    margin-right: 16px;
  }
}
.steps{
  padding: 20px 24px;
  overflow: auto;
  .el-steps{
    position: relative;
    width: max-content;
    min-width: 100%;
    &::before{
      content: "";
      position: absolute;
      border: 2px solid #F5F5F5;
      width: 100%;
      top: 18px;
    }
    .el-step{
      flex-basis: unset!important;
      margin-right: 56px!important;
      flex-shrink: 0;
      /deep/ .el-step__head{
        margin-bottom: 16px;
        .el-step__line{
          display: none;
        }
        .el-step__icon{
          width: 36px;
          height: 36px;
          border-color: #2A8CE3;
          color: #2A8CE3;
        }
      }
      /deep/ .el-step__description{
        padding-right: 0;
      }
      .step-description{
        font-size: 14px;
        max-width: 235px;
        &>div{
          margin-bottom: 8px;
        }
        .step-description-label{
          color: #666666;
        }
        .step-description-value{
          color: #333333;
        }
      }
    }
  }
  .empty-tips{
    text-align: center;
    color: #999999;
  }
}
</style>
