<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>
      <template v-slot:upperDept="scope">
        <div class="opinion-selector">
          <el-radio-group
            v-model="localSelection"
            @change="(val) => {
              // 调用方法并传入 isUpper 参数
              getUsersWithPermission(val === '上级部门处理人' ? 1 : 0);
              scope.easyFormItemBindData.componentScope.formInstance.clearValidate(scope.field.prop);
            }"
          >
            <el-radio label="当前部门处理人">当前部门处理人</el-radio>
            <el-radio label="上级部门处理人">上级部门处理人</el-radio>
          </el-radio-group>
        </div>
      </template>
    </easy-form>
  </div>
</template>

<script>
import {
  xrAttachmentDelLawFile
} from '@/api/abnormal'
import { tswrittemplateGetContentsWithBizseq, attachmentListByBizSepNo, eOtIlldisdetailApprovalPage, eOtIlldisdetailQueryOpinionRecords, eOtIlldisdetailGetTaskDetail, userGetOrgunits } from '@/api/auto-baseapi'
import { getUsersWithPermission } from '@/api/user'
import { createGlobalLoading, parseTime } from '@/utils'
import { findCurrentNode } from '@/api'
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,
      currentNodeID: '',
      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: 'uniscid',
          span: 12,
          isView: true
        },
        {
          type: 'input',
          label: '注册号',
          prop: 'regno',
          span: 12,
          isView: true
        },
        {
          type: 'input',
          label: '主体名称',
          prop: 'entname',
          span: 12,
          isView: true
        },
        {
          type: 'input',
          label: '登记机关',
          prop: 'regorgCn',
          span: 12,
          isView: true
        },
        {
          type: 'input',
          label: '法人',
          prop: 'name',
          span: 12,
          isView: true
        },
        {
          type: 'date-picker',
          label: '列入时间',
          prop: 'abntime',
          formProps: {
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            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: 'select',
          label: '移出原因',
          prop: 'remexcpres',
          span: 24,
          optionsBaseCode: 'CD74',
          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: 'isAgree',
          required: true,
          span: 24,
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          },
          showInForm: () => {
            return !this.readonly
          },
          options: ({ formData }) => {
            return this.flowModel
          },
          onChange: (scope, value, isFromUser) => {
            if (isFromUser) {
              scope.formData.opinionContent = ''
              // 根据选中的值更新selectedNextNodeEnd
              const selectedFlow = this.nextSequenceFlowList.find(item => item.nextNode.id === value)
              this.selectedNextNodeEnd = selectedFlow ? selectedFlow.nextNode.end : false
              // 判断是否是退回操作（nextNodeID包含return或replenish）
              this.selectedIsReturn = selectedFlow ?
                (selectedFlow.nextNode.id?.includes('return') || selectedFlow.nextNode.id?.includes('replenish')) : false
            }
          }
        },
        {
          type: 'select',
          label: '移出原因',
          prop: 'remexcpres',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            // 只有选择了操作且nextNode.end === false时才显示移出原因
            return !!formData.isAgree && !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: 'externalUnit',
                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.isAgree && !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.isAgree && 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.isAgree && 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.isAgree && !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'
    }
  },
  created() {
    createGlobalLoading(() => {
      return Promise.all([
        eOtIlldisdetailQueryOpinionRecords({
          workflowid: this.$route.query.workflowid
        }).then((response) => {
          const data = response.data || []
          this.data = {
            ...this.data,
            steps: data.map(item => ({
              ...item,
              opinionType: ({ '0': '待受理', '1': '经办', '2': '审核', '3': '审批', '4': '已通过', '5': '未通过', '6': '已作废', '7': '转办', '8': '待执法' })[item.opiniontype] || item.opiniontype,
              opinionContent: item.opinioncontent,
              handler: item.handler,
              createTime: item.lauptime || item.handledate
            })).reverse()
          }
        }),
        attachmentListByBizSepNo({
          bizseq: this.$route.query.bizSeqNo,
          attachtype: '81'
        }).then((response) => {
          const data = response.data || []
          this.data.fileList = data.map((item) => {
            return {
              ...item,
              name: item.filename
            }
          })
        }),
        // 只有待办模式才需要调用approvalPage获取流程选项
        ...(this.readonly ? [] : [eOtIlldisdetailApprovalPage({
          tasklistid: this.$route.query.tasklistid
        }).then((response) => {
          if (response.code !== 0) {
            this.$message.error(response.msg || '获取页面数据失败')
            return
          }
          const pageData = response.data || {}
          // 仅从approvalPage获取审批相关数据：状态、下一步节点等
          this.status = pageData.taskStatus || this.data.status
          // 保存原始的nextSequenceFlowList用于查找nextNode.end
          this.nextSequenceFlowList = pageData.nextSequenceFlowList || []
          // 映射flowModel选项
          if (pageData.nextSequenceFlowList) {
            this.flowModel = pageData.nextSequenceFlowList.map((item) => ({
              label: item.nextNode.name,
              value: item.nextNode.id,
              nextNode: item.nextNode
            }))
          }
          const permission = ({
            '0': 'xrExamine',
            '1': 'xrApprove'
          })[this.status]
          const ps = []
          if (permission) {
            ps.push(getUsersWithPermission(
              permission,
              this.$store.getters.orgId
            ).then((data) => {
              this.nextPerformerMap = data
            }))
          }
          return Promise.all(ps)
        })]),
        eOtIlldisdetailGetTaskDetail({
          workflowid: this.$route.query.workflowid
        }).then((response) => {
          if (response.code !== 0) {
            this.$message.error(response.msg || '获取任务详情失败')
            return
          }
          const detailData = response.data || {}
          const taskList = detailData.taskList || {}
          const bizInfo = detailData.bizInfo || {}
          const taskId = taskList.tasklistid
          this.taskLikeId = taskId
          // 合并数据：bizInfo包含外单位信息和移出信息，taskList包含待办信息
          this.data = {
            ...this.data,
            ...bizInfo,
            ...taskList,
            taskId: taskId,
            bizSeqNo: this.$route.query.bizSeqNo
          }
          // 加载登记机关树并转换regorg为中文
          return this.loadOrgunits().then(() => {
            // 转换regorg为中文名称
            if (this.data.regorg) {
              const orgName = this.findOrgName(this.orgs, this.data.regorg)
              this.data.regorgCn = orgName || this.data.regorg
            }
            return findCurrentNode({
              taskId: taskId
            }).then((activity) => {
              if (activity) {
                this.currentNodeID = activity.linkType
              }
            })
          })
        })
      ])
    })
  },
  methods: {
    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((data) => {
          this.nextPerformerMap = data
        }))
      }
      return Promise.all(ps)
    },
    // 加载登记机关树
    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
    }
  }
}
</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>
