<template>
  <div class="page">
    <easy-form
      ref="EasyForm"
      v-model="data"
      :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:uploader="scope">
        <div class="uploader">
          <el-upload
            :action="action"
            :data="{
              attachtype: '80',
              bizseq: scope.formData.bizSeqNo
            }"
            accept=".jpg,.png,.pdf,.doc,.docx,.xls,.xlsx,.rar,.zip,.7z"
            multiple
            :disabled="scope.isView"
            :file-list="scope.formData[scope.field.prop]"
            :before-remove="removeFile"
            :on-preview="previewFile"
          >
            <el-button v-if="!scope.isView" size="small" plain type="primary">
              <svg-icon icon-class="download" />
              点击上传
            </el-button>
            <div v-if="!scope.isView" slot="tip" class="el-upload__tip">只能上传jpg/png/pdf/doc/docx/xls/xlsx/rar/zip/7z文件，且单个文件不能超过20M</div>
          </el-upload>
        </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="请选择常用语"
            @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 {
  eOtIlldisdetailApprovalPage,
  eOtIlldisdetailApproval,
  userGetOrgunits,
  attachmentListByBizSepNo,
  eOtIlldisdetailQueryOpinionRecords,
  eOtIlldisdetailGetTaskDetail,
  eOtIlldisdetailModifyTemp
} 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: [],
      data: {},
      status: '',
      taskLikeId: '',
      showFakeProgress: false,
      type: this.$route.meta.type,
      flowModel: [],
      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: 'divider',
          label: '严重违法信息'
        },
        {
          type: 'select',
          label: '来源类型',
          prop: 'sourcetype',
          required: true,
          span: 24,
          options: [
            { label: '行政处罚', value: '2' },
            { label: '法院判决', value: '3' },
            { label: '其他', value: '9' }
          ]
        },
        {
          type: 'radio',
          label: '是否经过听证程序 ',
          prop: 'ishea',
          required: true,
          span: 24,
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '0' }
          ],
          showInForm: ({ formData }) => {
            return formData.sourcetype === '2'
          }
        },
        {
          type: 'input',
          label: '当事人听证中提出的主要意见 ',
          prop: 'heaop',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.sourcetype === '2' && formData.ishea === '1'
          }
        },
        {
          type: 'input',
          label: '听证意见 ',
          prop: 'heaopinionl',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.sourcetype === '2' && formData.ishea === '1'
          }
        },
        {
          type: 'input',
          label: '人民法院司法文书标题 ',
          prop: 'juddoctitle',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.sourcetype === '3'
          }
        },
        {
          type: 'input',
          label: '人民法院司法文书文号 ',
          prop: 'juddocno',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.sourcetype === '3'
          }
        },
        {
          type: 'date-picker',
          label: '列入日期',
          prop: 'abntime',
          required: true,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          },
          span: 24
        },
        {
          type: 'select',
          label: '列入原因',
          prop: 'serillrea',
          optionsBaseCode: 'CD73',
          required: true,
          span: 24
        },
        {
          type: 'textarea',
          label: '事实理由',
          prop: 'serreasons',
          required: true,
          span: 24,
          defaultValue: () => {
            return '经查，你（单位）        （事由）。依据《市场监督管理严重违法失信名单管理办法》        规定'
          }
        },
        {
          type: 'input',
          label: '行政复议机关',
          prop: 'reconsiderationorg',
          span: 24
        },
        {
          type: 'input',
          label: '诉讼机关',
          prop: 'litiorg',
          span: 24
        },
        {
          type: 'slot',
          slotName: 'uploader',
          label: '材料列表',
          prop: 'fileList',
          defaultValue: () => {
            return []
          },
          span: 24
        },
        {
          type: 'divider',
          label: '历史处理信息'
        },
        {
          type: 'slot',
          slotName: 'steps',
          label: '历史处理信息',
          hiddenLabel: true,
          prop: 'steps',
          defaultValue: () => {
            return []
          },
          span: 24
        },
        {
          type: 'divider',
          label: ({ formData }) => {
            return ({
              '0': '经办意见',
              '1': '审核意见',
              '2': '审批意见',
              '7': '执法负责意见'
            })[formData.status]
          },
          showInForm: () => {
            return !this.readonly
          }
        },
        {
          type: 'radio',
          label: '选择操作',
          prop: 'isAgree',
          required: true,
          span: 24,
          options: ({ formData }) => {
            return this.flowModel
          },
          showInForm: () => {
            return !this.readonly
          },
          onChange: (scope, value, isFromUser) => {
            if (isFromUser) {
              scope.formData.opinionContent = ''
            }
          }
        },
        {
          type: 'select',
          beforeSlotName: 'upperDept',
          label: '下一步处理人',
          prop: 'nextPerformerIds',
          span: 12,
          required: true,
          options: () => {
            return this.nextPerformerMap
          },
          showInForm: ({ formData }) => {
            return !this.readonly && ['0', '1', '7'].includes(formData.status) && !['nullify', 'transfer', 'examineFinish', 'approveFinish', 'lawFinish', 'handleReturn', 'examineReturn', 'end', 'upApproveFinish'].includes(formData.isAgree)
          }
        },
        {
          type: 'textarea',
          afterSlotName: 'opinion',
          label: ({ formData }) => {
            return ({
              '0': '经办意见',
              '1': '审核意见',
              '2': '审批意见',
              '7': '执法负责意见'
            })[formData.status]
          },
          prop: 'opinionContent',
          required: true,
          span: 24,
          opinion: '',
          options: [
            '同意',
            '不同意'
          ],
          showInForm: ({ formData }) => {
            return !this.readonly && formData.isAgree !== 'transfer'
          }
        },
        {
          type: 'cascader',
          label: '转办机关',
          prop: 'nextOrgID',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.isAgree === 'transfer' && formData.status === '0'
          },
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          },
          formProps: {
            props: { checkStrictly: true }
          },
          optionConfig: {
            labelKeyName: 'label',
            valueKeyName: 'orgUnitId'
          },
          options: () => {
            return this.authItemMap
          },
          onCreated: ({ setOptionLoading }) => {
            if (this.authItemMap.length === 0) {
              setOptionLoading('authItem', userGetOrgunits({}).then((response) => {
                if (response.code === 0) {
                  this.authItemMap = response.data || []
                }
              }))
            }
          }
        },
        {
          type: 'input',
          label: '转办原因',
          prop: 'transferReason',
          required: true,
          span: 24,
          showInForm: ({ formData }) => {
            return formData.isAgree === 'transfer' && formData.status === '0'
          },
          isView: ({ formData }) => {
            return ['1', '2'].includes(formData.status) || this.readonly
          }
        }
      ],
      buttons: [
        {
          label: '返回',
          type: 'primary',
          show: true,
          buttonProps: {
            plain: true
          },
          handler: (scope) => {
            this.$router.back()
          }
        },
        {
          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: '0', // 0：列入
                    abntime: formData.abntime,
                    serillrea: formData.serillrea,
                    serreasons: formData.serreasons
                  }
                  // 可选字段
                  if (formData.sourcetype) submitData.sourcetype = formData.sourcetype
                  if (formData.ishea) submitData.ishea = formData.ishea
                  if (formData.heaop) submitData.heaop = formData.heaop
                  if (formData.heaopinionl) submitData.heaopinionl = formData.heaopinionl
                  if (formData.juddoctitle) submitData.juddoctitle = formData.juddoctitle
                  if (formData.juddocno) submitData.juddocno = formData.juddocno
                  if (formData.reconsiderationorg) submitData.reconsiderationorg = formData.reconsiderationorg
                  if (formData.litiorg) submitData.litiorg = formData.litiorg
                  if (formData.infotype) submitData.infotype = formData.infotype
                  // 先保存严重违法列入信息
                  return eOtIlldisdetailModifyTemp(submitData).then((response) => {
                    if (response.code !== 0) {
                      this.$message.error(response.msg || '保存严重违法信息失败')
                      return
                    }
                    // 再提交审核信息
                    const nextPerformer = getOptionValue('nextPerformerIds')
                    return eOtIlldisdetailApproval({
                      tasklistid: this.$route.query.tasklistid,
                      nextNodeID: formData.isAgree,
                      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/inclusion/${this.$route.meta.type}`
                      })
                    })
                  })
                }
              })
            })
          }
        }
      ]
    }
  },
  computed: {
    readonly() {
      return this.type === 'history'
    }
  },
  created() {
    const workflowid = this.$route.query.workflowid
    const bizSeqNo = this.$route.query.bizSeqNo
    const tasklistid = this.$route.query.tasklistid

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

    createGlobalLoading(() => {
      // 公共查询：意见记录和附件列表
      const commonQueries = [
        this.fetchOpinionRecords(workflowid),
        this.fetchAttachmentList(bizSeqNo)
      ]

      if (this.readonly) {
        // 历史记录：公共查询 + workflowid查询业务信息
        return Promise.all([
          ...commonQueries,
          this.fetchTaskDetail(workflowid)
        ])
      } else {
        // 待办：公共查询 + tasklistid相关查询
        if (!tasklistid) {
          this.$message.error('缺少任务ID')
          return Promise.resolve()
        }
        return Promise.all([
          ...commonQueries,
          this.fetchApprovalPage(tasklistid),
          this.fetchTaskDetail(workflowid)
        ])
      }
    })
  },
  methods: {
    // 查询意见记录
    fetchOpinionRecords(workflowid) {
      return eOtIlldisdetailQueryOpinionRecords({ 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()
        }
      })
    },
    // 查询附件列表
    fetchAttachmentList(bizSeqNo) {
      return attachmentListByBizSepNo({
        bizseq: bizSeqNo,
        attachtype: '80'
      }).then((response) => {
        const data = response.data || []
        this.data.fileList = data.map((item) => ({
          ...item,
          name: item.filename
        }))
      })
    },
    // 查询审批页面信息（待办使用）- 仅获取审批相关信息
    fetchApprovalPage(tasklistid) {
      return eOtIlldisdetailApprovalPage({ tasklistid }).then((response) => {
        if (response.code !== 0) {
          this.$message.error(response.msg || '获取页面数据失败')
          return
        }
        const pageData = response.data || {}
        // 仅从approvalPage获取审批相关数据：状态、下一步节点、审批流程等
        this.data.status = pageData.taskStatus || this.data.status
        if (pageData.nextSequenceFlowList) {
          this.flowModel = pageData.nextSequenceFlowList.map((item) => ({
            label: item.nextNode.name,
            value: item.nextNode.id
          }))
        }
        const permission = ({
          '0': 'xrLaw',
          '7': 'xrExamine',
          '1': 'xrApprove'
        })[this.data.status]
        if (permission) {
          return getUsersWithPermission(permission, this.$store.getters.orgId).then((data) => {
            this.nextPerformerMap = data
          })
        }
      })
    },
    // 查询任务详情（待办和历史记录使用）- 获取外单位信息和严重违法信息
    fetchTaskDetail(workflowid) {
      return eOtIlldisdetailGetTaskDetail({ 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
            }
          })
        })
      })
    },
    // 加载登记机关树
    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, approve) {
      return `${approve === '1' ? '上级' : ''}` + ({
        'handle': '经办',
        'examine': '审核',
        'approve': '审批',
        'law': '执法负责'
      })[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': 'xrLaw',
        '7': 'xrExamine',
        '1': 'xrApprove'
      })[status]
      if (permission) {
        ps.push(getUsersWithPermission(
          permission,
          this.$store.getters.orgId,
          isUpper
        ).then((data) => {
          this.nextPerformerMap = data
        }))
      }
      return Promise.all(ps)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-handle";
.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>
