<template>
  <div>
    <easy-form
      ref="EasyForm"
      v-model="value"
      :fields="fields"
      :form-config="formConfig"
      :buttons="buttons"
    >
      <template v-slot:divider="scope">
        <div class="divider">
          <span class="text">{{ scope.getPropValue(scope.field.label) }}</span>
        </div>
      </template>
      <template v-slot:steps="scope">
        <div class="steps">
          <el-steps v-if="scope.formData[scope.field.prop].length > 0" :active="0" finish-status="success">
            <el-step v-for="step in scope.formData[scope.field.prop]" :key="step.key">
              <template v-slot:description>
                <div class="step-description">
                  <div>
                    <span class="step-description-label">{{ step.opinionType }}内容：</span>
                    <span class="step-description-value">{{ step.opinionContent }}</span>
                  </div>
                  <div>
                    <span class="step-description-label">{{ step.opinionType }}人：</span>
                    <span class="step-description-value">{{ step.handler }}</span>
                  </div>
                  <div>
                    <span class="step-description-label">{{ step.opinionType }}日期：</span>
                    <span class="step-description-value">{{ parseTime(step.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                  </div>
                </div>
              </template>
            </el-step>
          </el-steps>
          <div v-else class="empty-tips">暂无历史信息</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="请选择常用语"
            clearable
            @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 { createGlobalLoading, parseTime } from '@/utils'
import { getUsersWithPermission } from '@/api/user'
import { findCurrentNode } from '@/api'
import { eOtIlldisdetailApproval, eOtIlldisdetailQueryOpinionRecords, eOtIlldisdetailGetTaskDetail, eOtIlldisdetailModifyTemp, userGetOrgunits } from '@/api/auto-baseapi'
export default {
  components: {
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    },
    readonly: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      parseTime,
      nextPerformerMap: [],
      currentNodeID: '',
      localSelection: '当前部门处理人', // 默认值
      orgs: [], // 登记机关树
      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: 'textarea',
          label: '作出决定的事实、理由、依据及主要内容',
          prop: 'remreasons',
          span: 24,
          defaultValue: () => {
            return '根据《市场监督管理信用修复管理办法》第七条要求，当事人被列入严重违法失信名单满一年，且符合下列情形的，可以依照本办法规定申请信用修复：（一）已经自觉履行行政处罚决定中规定的义务；（二）已经主动消除危害后果和不良影响；（三）未再受到市场监督管理部门较重行政处罚。依照法律、行政法规规定，实施相应管理措施期限尚未届满的，不得申请提前移出。'
          }
        },
        {
          type: 'divider',
          label: '历史处理信息'
        },
        {
          type: 'slot',
          slotName: 'steps',
          label: '历史处理信息',
          hiddenLabel: true,
          prop: 'steps',
          defaultValue: () => {
            return []
          },
          span: 24
        },
        {
          type: 'divider',
          label: ({ formData }) => {
            return ({
              '0': '经办意见',
              '1': '审核意见',
              '2': '审批意见'
            })[formData.status] || '经办意见'
          },
          showInForm: () => {
            return !this.readonly
          }
        },
        {
          type: 'textarea',
          afterSlotName: 'opinion',
          label: ({ formData }) => {
            return ({
              '0': '经办人意见',
              '1': '审核人意见',
              '2': '审批人意见'
            })[formData.status] || '经办人意见'
          },
          prop: 'opinionContent',
          required: true,
          span: 24,
          opinion: '',
          options: [
            '同意',
            '不同意'
          ],
          showInForm: () => {
            return !this.readonly
          }
        },
        {
          type: 'radio',
          label: '是否通过',
          prop: 'nextNodeID',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return ['1', '2'].includes(formData.status)
          },
          options: ({ formData }) => {
            return [
              { label: '通过', value: formData.status === '1' ? 'approve' : 'end' },
              { label: '不通过', value: formData.status === '1' ? 'examineFinish' : 'approveFinish' },
              { label: '回退', value: formData.status === '1' ? 'handleReturn' : 'examineReturn' }
              // { label: '删除业务', value: 'nullify' }
            ]
          }
        },
        {
          type: 'select',
          beforeSlotName: 'upperDept',
          label: ({ formData }) => {
            return ({
              '0': '下一步审核人',
              '1': '下一步审批人'
            })[formData.status] || '下一步处理人'
          },
          prop: 'nextPerformerIds',
          required: true,
          span: 12,
          showInForm: ({ formData }) => {
            return !this.readonly && ['0', '1'].includes(formData.status) && !['examineFinish', 'approveFinish', 'handleReturn', 'examineReturn', 'nullify'].includes(formData.nextNodeID)
          },
          options: () => {
            return this.nextPerformerMap
          }
        }
      ],
      buttons: [
        {
          label: '返回',
          type: 'primary',
          show: true,
          buttonProps: {
            plain: true
          },
          handler: (scope) => {
            this.$emit('prev-tab')
          }
        },
        {
          label: '确定',
          type: 'primary',
          show: () => {
            return !this.readonly
          },
          handler: ({ formInstance, getOptionValue }) => {
            return formInstance.submitForm().then((formData) => {
              this.$confirm('是否继续提交', '提示', {
                type: 'info',
                customClass: 'type-1',
                confirmHandlerPromise: () => {
                  // 构建 modifyTemp 接口参数
                  const submitData = {
                    bizseq: this.$route.query.bizSeqNo,
                    bizType: '1', // 1：移出
                    remdate: formData.remdate,
                    remexcpres: formData.remexcpres,
                    remreasons: formData.remreasons
                  }
                  // 可选字段
                  if (formData.recorg) submitData.recorg = formData.recorg
                  if (formData.recorgCn) submitData.recorgCn = formData.recorgCn
                  if (formData.redocnum) submitData.redocnum = formData.redocnum
                  if (formData.governmentorg) submitData.governmentorg = formData.governmentorg
                  // 先保存严重违法移出信息
                  return eOtIlldisdetailModifyTemp(submitData).then((response) => {
                    if (response.code !== 0) {
                      this.$message.error(response.msg || '保存移出信息失败')
                      return
                    }
                    // 再提交审核信息
                    const nextPerformer = getOptionValue('nextPerformerIds')
                    // 获取nextNodeID：优先使用nextNodeID字段，否则使用isAgree字段
                    const nextNodeID = formData.nextNodeID || formData.isAgree
                    return eOtIlldisdetailApproval({
                      tasklistid: this.$route.query.tasklistid,
                      nextNodeID: nextNodeID,
                      nextPerformerids: nextPerformer ? nextPerformer.value : '',
                      nextPerformerNames: nextPerformer ? nextPerformer.label : '',
                      opinionModel: {
                        opinioncontent: formData.opinionContent
                      }
                    }).then((approvalRes) => {
                      if (approvalRes.code !== 0) {
                        this.$message.error(approvalRes.msg || '提交审核失败')
                        return
                      }
                      this.$message.success(`已完成对"${formData.entname}"的业务办理!`)
                      this.$router.push({
                        path: `/illegal/externalUnit/remove/${this.$route.meta.type}`
                      })
                    })
                  })
                }
              })
            })
          }
        }
      ]
    }
  },
  computed: {
    doctype() {
      return this.value.isAgreeRepair === '1'
    }
  },
  created() {
    createGlobalLoading(() => {
      const ps = []
      const permission = ({
        '0': 'xrExamine',
        '1': 'xrApprove'
      })[this.value.status]
      if (permission) {
        ps.push(getUsersWithPermission(
          permission,
          this.$store.getters.orgId
        ).then((data) => {
          this.nextPerformerMap = data
        }))
      }
      return Promise.all([
        ...ps,
        eOtIlldisdetailQueryOpinionRecords({
          workflowid: this.$route.query.workflowid
        }).then((response) => {
          const data = response.data || []
          this.value.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()
        }),
        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
          // 合并数据：bizInfo包含外单位信息和移出信息
          this.value = {
            ...this.value,
            ...bizInfo,
            ...taskList
          }
          // 加载登记机关树并转换regorg为中文
          return this.loadOrgunits().then(() => {
            // 转换regorg为中文名称
            if (this.value.regorg) {
              const orgName = this.findOrgName(this.orgs, this.value.regorg)
              this.value.regorgCn = orgName || this.value.regorg
            }
            return findCurrentNode({
              taskId: taskId
            }).then((activity) => {
              if (activity) {
                this.currentNodeID = activity.linkType
              }
            })
          })
        })
      ])
    })
  },
  methods: {
    stepStatus2CN(opinionType) {
      return ({
        'handle': '经办',
        'examine': '审核',
        'approve': '审批'
      })[opinionType]
    },
    getUsersWithPermission(isUpper) {
      const ps = []
      const permission = ({
        '0': 'xrExamine',
        '1': 'xrApprove'
      })[this.value.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.scss";
.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;
        &>div{
          margin-bottom: 8px;
        }
        .step-description-label{
          color: #666666;
        }
        .step-description-value{
          color: #333333;
        }
      }
    }
  }
  .empty-tips{
    text-align: center;
    color: #999999;
  }
}
.doc-name{
  text-decoration: underline;
  color: #2A8CE3;
  cursor: pointer;
}
/deep/ .easy-form-col-decisionContent{
  .el-form-item__content{
    padding: 0!important;
  }
}
</style>
