<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">{{ step.createTime ? 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 { parseTime } from '@/utils'
import { xrSeriousIllegalPersonRemListProcessControl, xrSeriousIllegalPersonRemListGetApprovalFormByBizSeqNo, xrSeriousIllegalPersonRemListGetCurrentTaskInfo, xrSeriousIllegalPersonRemListGetNextStepList } from '@/api/auto-baseapi'
import { getUsersWithPermission } from '@/api/user'
export default {
  components: {
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    },
    readonly: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      parseTime,
      nextPerformerMap: [],
      currentNodeID: '',
      localSelection: '当前部门处理人', // 默认值
      orgs: [], // 登记机关树
      flowModel: [],
      type: this.$route.meta.type,
      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: 'textarea',
          label: '作出决定的事实、理由、依据及主要内容',
          prop: 'lostCreditExplainRem',
          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: 'radio',
          label: '选择操作',
          prop: 'isAgree',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            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: 'textarea',
          afterSlotName: 'opinion',
          label: ({ formData }) => {
            return ({
              '0': '经办人意见',
              '1': '审核人意见',
              '2': '审批人意见'
            })[formData.status] || '经办人意见'
          },
          prop: 'opinionContent',
          required: true,
          span: 24,
          opinion: '',
          options: () => [
            '同意',
            '不同意'
          ],
          showInForm: () => {
            return !this.readonly
          }
        },
        {
          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: () => {
                  // 构建流程控制接口参数，根据注释文档传参
                  const nextPerformer = getOptionValue('nextPerformerIds')
                  // 获取nextNodeID：优先使用nextNodeID字段，否则使用isAgreeRepair字段
                  const nextNodeID = formData.nextNodeID || formData.isAgree
                  const xrSeriousIllegalPersonRemList = {
                    ...formData
                  }
                  // 可选字段
                  if (formData.remWritId) xrSeriousIllegalPersonRemList.remWritId = formData.remWritId
                  if (formData.governmentOrg) xrSeriousIllegalPersonRemList.governmentOrg = formData.governmentOrg
                  const submitData = {
                    tasklistid: this.$route.query.tasklistid,
                    currentNodeID: this.currentNodeID,
                    nextNodeID: nextNodeID,
                    nextPerformerIds: nextPerformer ? [nextPerformer.value] : [],
                    nextPerformerNames: nextPerformer ? nextPerformer.label : '',
                    opinion: {
                      opinionContent: formData.opinionContent
                    },
                    bizSeqNo: this.$route.query.bizSeqNo,
                    xrSeriousIllegalPersonRemList: xrSeriousIllegalPersonRemList
                  }
                  // 调用流程控制接口提交
                  return xrSeriousIllegalPersonRemListProcessControl(submitData).then((response) => {
                    if (response.code !== 0) {
                      this.$message.error(response.msg || '提交审核失败')
                      return
                    }
                    this.$message.success(`已完成对"${formData.inv}"的业务办理!`)
                    this.$router.push({
                      path: `/illegal/naturalPerson/remove/${this.$route.meta.type}`
                    })
                  })
                }
              })
            })
          }
        }
      ]
    }
  },
  computed: {
    doctype() {
      return this.value.isAgreeRepair === '1'
    }
  },
  created() {
    const bizSeqNo = this.$route.query.bizSeqNo
    const cerNo = this.$route.query.cerNo

    if (!bizSeqNo) {
      this.$message.error('缺少必要的参数')
      return
    }

    // 如果父组件没有传递 steps 数据，则自己获取
    if (!this.value.steps || this.value.steps.length === 0) {
      this.fetchOpinionRecords(bizSeqNo, cerNo)
    }

    this.getUsersWithPermission(false)

    xrSeriousIllegalPersonRemListGetNextStepList({ bizSeqNo }).then((response) => {
      if (response.code !== 0) {
        this.$message.error(response.msg || '获取页面数据失败')
        this.flowModel = []
        return
      }
      // 接口返回的是 SequenceFlowModel 数组
      const sequenceFlowList = response.data || []
      // 确保是数组
      if (!Array.isArray(sequenceFlowList)) {
        console.warn('getNextStepList 返回的不是数组:', sequenceFlowList)
        this.flowModel = []
        return
      }
      // 映射下一步流程节点到 flowModel
      this.flowModel = sequenceFlowList.map((item) => ({
        label: item.name,
        value: item.nextNode?.id || item.id,
        nextNode: item.nextNode
      }))
      // 保存原始的 nextSequenceFlowList 用于后续处理
      this.nextSequenceFlowList = sequenceFlowList
    }).catch((error) => {
      console.error('获取下一步流程失败:', error)
      this.flowModel = []
    })
    if (this.type === 'todo') {
      return xrSeriousIllegalPersonRemListGetCurrentTaskInfo({
        bizSeqNo: this.$route.query.bizSeqNo
      }).then((response) => {
        if (response.code === 0 && response.data) {
          this.currentNodeID = response.data.currentNodeID
        }
      })
    }
  },
  methods: {
    getUsersWithPermission(isUpper) {
      const ps = []
      const status = this.value.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)
    },
    stepStatus2CN(opinionType) {
      return ({
        'handle': '经办',
        'examine': '审核',
        'approve': '审批'
      })[opinionType]
    },
    // 查询意见记录
    fetchOpinionRecords(bizSeqNo, cerNo) {
      return xrSeriousIllegalPersonRemListGetApprovalFormByBizSeqNo({ bizSeqNo, cerNo }).then((response) => {
        if (response.code !== 0) {
          console.error('获取意见记录失败:', response.msg)
          return
        }
        const data = response.data || {}
        const opinionList = data.opinion || []
        // 使用 $emit 更新父组件数据
        const steps = opinionList.map(item => ({
          ...item,
          opinionType: ({ '0': '待受理', '1': '经办', '2': '审核', '3': '审批', '4': '已通过', '5': '未通过', '6': '已作废', '7': '转办', '8': '待执法' })[item.opiniontype] || item.opiniontype,
          opinionContent: item.opinionContent || item.opinionContent,
          handler: item.handler,
          createTime: item.lauptime || item.handledate || item.createTime
        })).reverse()
        this.$emit('input', {
          ...this.value,
          steps: steps
        })
      })
    }
  }
}
</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>
