<script setup name="approvalDialog">
import { ref, watch, reactive } from 'vue'
import OrgTree from '@/components/orgTree/index.vue'
import { procdefUnit } from '@/http/apis/systemManage/flowConfiguration'
const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    data: Object
  }),
  emits = defineEmits(['close', 'update:data']),
  formRef = ref(),
  form = ref({
    name: undefined,
    orgType: undefined,
    assignedOrg: [],
    subProcess: undefined,
    procDefId: undefined,
    threeDaysAutoPass: false
  }),
  rules = {
    name: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
    orgType: [{ required: true, message: '请选择节点负责单位' }],
    assignedOrg: [{ required: true, message: '请至少指定一个单位' }],
    subProcess: [{ required: true, message: '请选择单位内部流程' }],
    type: [{ required: true, message: '请选择单位内部流程' }],
    threeDaysAutoPass: [{ type: Boolean, required: true, message: '请选择' }],
    constructionSuggestions: [{ type: Boolean, required: true, message: '请选择' }]
  },
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        const data = {
          name: form.value.name || '',
          id: form.value.id || '',
          parentId: form.value.parentId || '',
          type: 'SUB',
          props: {
            mode: 'AND',
            sign: false,
            assignedType: 'ASSIGN_ORG',
            refuse: {
              type: 'TO_END',
              target: ''
            },
            assignedOrg: form.value.orgType === 'TARGET_LABEL' ? form.value.assignedOrg && form.value.assignedOrg.map(i => {
              return {
                ...i,
                type: unitFlows.value.find(r => r.processDefId === form.value.subProcess).type || 'DEFAULT',
                processDefId: form.value.subProcess,
                orgType: form.value.orgType
              }
            }) : [{
              orgType: form.value.orgType,
              type: form.value.type
            }],
            threeDaysAutoPass: form.value.type === 'SEAL' ? false : form.value.threeDaysAutoPass || false,
            constructionSuggestions: form.value.constructionSuggestions || false
          }
        }
        emits('update:data', data)
        emits('close', true)
      }
    })
  },
  // 修改节点负责单位
  changeUnitType = () => {
    form.value.assignedOrg = []
    form.value.subProcess = undefined
    form.value.type = undefined
  },
  // 选择单位弹窗
  orgProps = reactive({
    unitVisible: false,
    showCheckbox: false,
    data: undefined
  }),
  showOrgTree = () => {
    orgProps.unitVisible = true
    orgProps.showCheckbox = false
    orgProps.data = form.value.assignedOrg.map(i => {
      return {
        key: i.orgCode,
        title: i.orgName
      }
    })
  },
  getOrgData = (data, expandedKeys) => {
    form.value.assignedOrg = data.map(i => {
      return {
        orgCode: i.key,
        orgName: i.title
      }
    })
    getProcdefUnit(data[0].key)
  },
  closeOrg = () => {
    orgProps.unitVisible = false
  },
  // 删除单位
  delTag = (index) => {
    form.value.assignedOrg.splice(index, 1)
  },
  // 获取单位内部流程
  unitFlows = ref([]),
  getProcdefUnit = async (orgCode) => {
    const res = await procdefUnit({ pageNum: 1, pageSize: 1000, orgCode })
    unitFlows.value = res.data.records.filter(i => !i.isStop)
    if (res.data.records && !res.data.records.length) {
      unitFlows.value = []
    }
  },
  // 评审字段
  fieldVisible = ref(false),
  column = [
    {
      label: '字段名称',
      prop: 'fieldName',
      key: 'fieldName'
    },
    {
      label: '是否必填',
      prop: 'isRequired',
      key: 'isRequired'
    },
    {
      label: '填写类型',
      prop: 'writeType',
      key: 'writeType'
    }
  ],
  fieldData = ref([
    {
      fieldName: '评审意见附件',
      isRequired: '是',
      writeType: '文件上传'
    },
    {
      fieldName: '建议总投资',
      isRequired: '是',
      writeType: '文本'
    },
    {
      fieldName: '建议年度预算',
      isRequired: '是',
      writeType: '文本'
    }
  ])
watch(
  () => props.visible,
  async val => {
    if (val) {
      if (props.data && props.data.props) {
        props.data.props.assignedOrg?.length && props.data.props.assignedOrg[0].orgType === 'TARGET_LABEL' && getProcdefUnit(props.data.props.assignedOrg[0].orgCode)
      }
      form.value = {
        ...props.data,
        props: undefined,
        orgType: props.data.props && props.data.props.assignedOrg?.length ? props.data.props.assignedOrg[0].orgType : null,
        subProcess: props.data.props && props.data.props.assignedOrg[0].orgType === 'TARGET_LABEL' ? props.data.props.assignedOrg[0].processDefId : undefined,
        assignedOrg: props.data.props && props.data.props.assignedOrg && props.data.props.assignedOrg.length && props.data.props.assignedOrg[0].orgType === 'TARGET_LABEL' && props.data.props.assignedOrg.map(i => i) || [],
        type: props.data.props && props.data.props.assignedOrg?.length && props.data.props.assignedOrg[0].orgType !== 'TARGET_LABEL' ? props.data.props.assignedOrg[0].type : undefined,
        threeDaysAutoPass: props.data.props?.threeDaysAutoPass || false,
        constructionSuggestions: props.data.props?.constructionSuggestions || false
      }
    } else {
      formRef.value.resetFields()
    }
  }
)
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="审批节点设置"
    width="840px"
    destroy-on-close
    @close="emits('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="200"
      label-suffix=":"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="节点名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="节点负责单位" prop="orgType">
            <el-radio-group v-model="form.orgType" @change="changeUnitType">
              <el-radio label="TARGET_LABEL">指定单位</el-radio>
              <el-radio label="TARGET_MANAGEMENT">主管单位</el-radio>
              <el-radio label="TARGET_OWNER">发起单位</el-radio>
              <el-radio label="TARGET_LINE_MANAGEMENT">上级条线主管单位</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.orgType==='TARGET_LABEL'">
        <el-col :span="24">
          <el-form-item prop="assignedOrg">
            <div class="flex flex-col items-start">
              <el-button type="primary" @click="showOrgTree"><el-icon><Plus /></el-icon>添加单位</el-button>
              <p>
                <el-tag
                  v-for="(item,index) in form.assignedOrg"
                  :key="index"
                  class="mr-8"
                  closable
                  @close="delTag(index)"
                >
                  {{ item.orgName }}
                </el-tag>
              </p>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="(form.orgType==='TARGET_LABEL'&&form.assignedOrg.length)||(form.orgType&&form.orgType!=='TARGET_LABEL')">
        <el-col :span="24">
          <el-form-item v-if="form.orgType==='TARGET_LABEL'" label="单位内部流程" prop="subProcess">
            <el-radio-group v-model="form.subProcess">
              <el-radio v-for="(item,index) in unitFlows" :key="index" :label="item.processDefId||0">{{ item.processDefName }}{{ item.type==="SEAL"?'（盖章流程）':item.type==="DEFAULT"?'（默认流程）':'' }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-else prop="type" label="单位内部流程">
            <el-radio-group v-model="form.type">
              <el-radio label="DEFAULT">默认流程</el-radio>
              <el-radio label="SEAL">盖章流程</el-radio>
              <el-radio label="JOINT_REVIEW">重大项目联审流程</el-radio>
              <el-radio label="JOINT_REVIEW_CONFIRM">联审确认流程</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.type!=='SEAL'">
        <el-col :span="24">
          <el-form-item label="3天不处理自动通过" prop="threeDaysAutoPass">
            <el-switch v-model="form.threeDaysAutoPass" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="$route.query.formName==='建设方案审批流程'">
        <el-col :span="24">
          <el-form-item label="是否添加评审建议信息字段" prop="constructionSuggestions">
            <el-switch v-model="form.constructionSuggestions" />
            <a class="ml-8 cursor-pointer" @click="fieldVisible=true">查看字段</a>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit(formRef)">
        提交
      </el-button>
      <el-button @click="emits('close')">
        关闭
      </el-button>
    </template>
  </el-dialog>
  <el-dialog
    :model-value="fieldVisible"
    title="查看字段"
    width="600px"
    destroy-on-close
    @close="fieldVisible=false"
  >
    <table-list :column="column" :data="fieldData" :pagination="false" />
  </el-dialog>
  <org-tree
    :visible="orgProps.unitVisible"
    :show-checkbox="orgProps.showCheckbox"
    :default-data="orgProps.data"
    :params="{onlyUnit: true}"
    @close="closeOrg"
    @get-select-unit="getOrgData"
  />
</template>
