<template>
  <div class="page cancel-revoke-handle-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: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) => {
              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>

      <template v-slot:steps>
        <div class="steps">
          <el-steps v-if="approveList.length > 0" :active="0" finish-status="success">
            <el-step v-for="(step, idx) in approveList" :key="step.approveId || idx">
              <template v-slot:description>
                <div class="step-description">
                  <div>
                    <span class="step-description-label">节点：</span>
                    <span class="step-description-value">{{ toNodeCn(step.node) }}</span>
                  </div>
                  <div>
                    <span class="step-description-label">办理人：</span>
                    <span class="step-description-value">{{ step.approverName || '-' }}</span>
                  </div>
                  <div>
                    <span class="step-description-label">意见：</span>
                    <span class="step-description-value">{{ step.approveOpinion || '-' }}</span>
                  </div>
                  <div>
                    <span class="step-description-label">日期：</span>
                    <span class="step-description-value">{{ step.approveTime || '-' }}</span>
                  </div>
                </div>
              </template>
            </el-step>
          </el-steps>
          <div v-else class="empty-tips">暂无历史信息</div>
        </div>
      </template>
    </easy-form>
  </div>
</template>

<script>
import {
  apiCancelRevokeBizId,
  apiCancelRevokeDetailBizSeq,
  apiCancelRevokeNext
} from '@/api/auto-baseapi'
import { getUsersWithPermission } from '@/api/user'

export default {
  data() {
    return {
      approveList: [],
      flowModel: [],
      nextPerformerMap: [],
      localSelection: '当前部门处理人',
      data: {
        approveOpinion: '',
        approveStatus: '1',
        bizId: '',
        bizSeq: '',
        cancelRevokeDate: '',
        currentNode: '',
        currentNodeName: '',
        entname: '',
        isAgree: '',
        nextNodeID: '',
        nextOrgID: '',
        nextPerformerIds: '',
        nextPerformerNames: '',
        nextPerformerids: '',
        opinionContent: '',
        regno: '',
        revokeListId: '',
        revokeReason: '',
        tasklistid: '',
        transferReason: '',
        uniscid: '',
        status: '',
        steps: []
      },
      formConfig: {
        labelPosition: 'right',
        buttonPosition: 'right',
        gutter: 0,
        isView: () => {
          return this.readonly
        }
      },
      buttons: [
        {
          label: '返回',
          type: 'primary',
          show: true,
          buttonProps: { plain: true },
          handler: () => {
            this.$router.back()
          }
        },
        {
          label: '提交',
          type: 'primary',
          show: () => !this.readonly,
          loading: false,
          handler: ({ formInstance, getOptionValue }) => {
            return formInstance.submitForm().then((formData) => {
              if (!this.data.bizId || !this.data.bizSeq) {
                this.$message.error('业务参数缺失，无法提交')
                return
              }
              this.$confirm('是否继续提交', '提示', {
                type: 'info',
                customClass: 'type-1',
                confirmHandlerPromise: () => {
                  const nextPerformer = getOptionValue('nextPerformerIds')
                  const payload = {
                    approveOpinion: formData.opinionContent,
                    approveStatus: this.resolveApproveStatus(formData),
                    bizId: this.data.bizId,
                    bizSeq: this.data.bizSeq,
                    cancelRevokeDate: this.data.cancelRevokeDate,
                    currentNode: this.data.currentNode,
                    nextNodeID: formData.isAgree,
                    nextPerformerNames: nextPerformer ? nextPerformer.label : '',
                    nextPerformerids: nextPerformer ? nextPerformer.value : '',
                    revokeListId: this.data.revokeListId,
                    tasklistid: this.data.tasklistid
                  }
                  if (formData.isAgree === 'transfer') {
                    payload.nextOrgID = formData.nextOrgID
                    payload.transferReason = formData.transferReason
                  }
                  return apiCancelRevokeNext(payload).then((res) => {
                    if (res.code !== 0) {
                      this.$message.error(res.msg || '提交失败')
                      return
                    }
                    this.$message.success('提交成功')
                    this.$router.push('/revoke/cancelRevoke/todo')
                  }).finally(() => {
                  })
                }
              })
            })
          }
        }
      ]
    }
  },
  computed: {
    readonly() {
      return this.$route.query.type === 'history'
    },
    fields() {
      return [
        { 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: 24, isView: true },
        { type: 'input', label: '吊销原因', prop: 'revokeReason', span: 24, isView: true },
        { type: 'input', label: '撤销吊销原因', prop: 'cancelRevokeReason', span: 24, isView: true },

        { type: 'divider', label: '历史处理信息' },
        {
          type: 'slot',
          slotName: 'steps',
          label: '历史处理信息',
          hiddenLabel: true,
          prop: 'steps',
          span: 24,
          defaultValue: () => []
        },

        {
          type: 'divider',
          label: ({ formData }) => {
            return ({
              '0': '经办意见',
              '1': '审核意见',
              '2': '审批意见',
              '7': '执法负责意见'
            })[formData.status] || '审批意见'
          },
          showInForm: () => !this.readonly
        },
        {
          type: 'radio',
          label: '选择操作',
          prop: 'isAgree',
          required: true,
          span: 24,
          options: () => this.flowModel,
          showInForm: () => !this.readonly,
          onChange: (scope, value, isFromUser) => {
            if (!isFromUser) return
            scope.formData.opinionContent = ''
            scope.formData.nextPerformerIds = ''
            scope.formData.nextPerformerids = ''
            scope.formData.nextPerformerNames = ''
            this.loadNextPerformers(value)
          }
        },
        {
          type: 'select',
          beforeSlotName: 'upperDept',
          label: '下一步处理人',
          prop: 'nextPerformerIds',
          required: true,
          span: 12,
          options: () => this.nextPerformerMap,
          showInForm: ({ formData }) => !this.readonly && this.$util.isNotEmpty(formData.isAgree) && formData.isAgree !== 'transfer'
        },
        {
          type: 'textarea',
          afterSlotName: 'opinion',
          label: '审批意见',
          prop: 'opinionContent',
          required: true,
          span: 24,
          opinion: '',
          options: [
            '同意',
            '不同意'
          ],
          showInForm: () => !this.readonly
        },
        {
          type: 'input',
          label: '转办机关',
          prop: 'nextOrgID',
          required: true,
          span: 24,
          showInForm: ({ formData }) => formData.isAgree === 'transfer' && !this.readonly
        },
        {
          type: 'input',
          label: '转办原因',
          prop: 'transferReason',
          required: true,
          span: 24,
          showInForm: ({ formData }) => formData.isAgree === 'transfer' && !this.readonly
        }
      ]
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    initPage() {
      const bizId = this.$route.query.bizId
      const bizSeq = this.$route.query.bizSeq
      const tasklistid = this.$route.query.tasklistid

      if (!bizId && !bizSeq) {
        this.$message.error('缺少业务参数')
        return
      }

      Promise.all([
        this.loadDetail(bizId, bizSeq, tasklistid)
      ]).catch(() => {
        this.$message.error('页面数据加载失败')
      })
    },
    loadDetail(bizId, bizSeq, tasklistid) {
      if (bizSeq) {
        return apiCancelRevokeDetailBizSeq({ bizSeq }, { tasklistid }).then((res) => {
          if (res.code !== 0) {
            this.$message.error(res.msg || '业务详情查询失败')
            return
          }
          this.fillDetail(res.data || {})
        })
      }
      return apiCancelRevokeBizId({ bizId }, { tasklistid }).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg || '业务详情查询失败')
          return
        }
        this.fillDetail(res.data || {})
      })
    },
    fillDetail(detail) {
      const flowModel = this.buildFlowModel(detail.nextSequenceFlowList || [])
      const detailApproveList = (detail.approveList || []).map(item => ({
        ...item,
        node: this.toNodeCn(item.node)
      }))
      this.flowModel = flowModel
      this.approveList = detailApproveList
      this.data = {
        ...this.data,
        ...detail,
        bizId: detail.bizId || this.$route.query.bizId || '',
        bizSeq: detail.bizSeq || this.$route.query.bizSeq || '',
        tasklistid: detail.tasklistid || this.$route.query.tasklistid || '',
        currentNode: detail.currentNode || '',
        currentNodeName: detail.currentNodeName || detail.currentNode || '',
        revokeListId: detail.revokeListId || '',
        cancelRevokeDate: detail.cancelRevokeDate || '',
        status: detail.status || detail.taskStatus || '',
        steps: detailApproveList
      }
      if (!this.data.isAgree && this.flowModel.length > 0) {
        this.data.isAgree = this.flowModel[0].value
      }
      if (this.$util.isNotEmpty(this.data.isAgree) && !this.readonly) {
        this.loadNextPerformers(this.data.isAgree)
      }
    },
    buildFlowModel(list) {
      return (list || []).map((item) => {
        const node = item.nextNode || item
        const value = node.id || item.nextNodeID || item.nextNodeId || item.nodeId || item.id || item.value || ''
        const label = node.name || item.nextNodeName || item.nextNodeDesc || item.nodeName || item.name || item.label || value
        return { label, value }
      }).filter(item => item.value)
    },
    buildUserOptions(users) {
      const list = Array.isArray(users) ? users : ((users && users.data) || [])
      return list.map((item) => {
        const value = item.value || item.primaryKey || item.userId || item.id || item.key || ''
        const label = item.label || item.name || item.userName || item.username || value
        return { label, value }
      }).filter(item => item.value)
    },
    loadNextPerformers(nextNodeID, isUpper) {
      if (!nextNodeID) {
        this.nextPerformerMap = []
        return Promise.resolve()
      }
      return getUsersWithPermission(nextNodeID, this.$store.getters.orgId, isUpper).then((res) => {
        this.nextPerformerMap = this.buildUserOptions(res)
      }).catch(() => {
        this.nextPerformerMap = []
      })
    },
    getUsersWithPermission(isUpper) {
      return this.loadNextPerformers(this.data.isAgree, isUpper)
    },
    toNodeCn(node) {
      const key = (node || '').toString()
      return ({
        0: '待受理',
        1: '经办',
        2: '审核',
        3: '审批',
        4: '办结',
        start: '发起',
        handle: '经办',
        examine: '审核',
        approve: '审批',
        law: '执法负责',
        transfer: '转办',
        end: '办结',
        revoke: '撤销'
      })[key] || node || '-'
    },
    resolveApproveStatus(formData) {
      const text = ((this.flowModel.find(item => item.value === formData.isAgree) || {}).label || '').toLowerCase()
      if (text.includes('不同意') || text.includes('拒绝') || text.includes('驳回') || text.includes('退回')) {
        return '2'
      }
      return '1'
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-handle";

.cancel-revoke-handle-page {
  .divider {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    .text {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      padding-left: 10px;
      border-left: 4px solid #2A8CE3;
      line-height: 20px;
    }
  }
  .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 {
      color: #999;
      font-size: 14px;
    }
  }
}
</style>
