<!-- 延迟/提前送检-编辑 -->
<script lang="ts" setup name="ApplicationEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import planList from './table.vue'
import approvalDialog from './ApprovalDialog.vue'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import { SCHEDULE } from '@/utils/scheduleDict'
import { delTextBtn, editBtn, submitBtn } from '@/utils/applyBtns'
import { cancelApply, delApply, detailApply, editApply, submitApply } from '@/api/eqpt/measurementPlan/early'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
// 审批状态 (全部/审批等)
const statusName = $route.query.statusName as string
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// const params = $route.query.approvalType === '0' ? 'ealy' : 'delay'
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref({
  approvalNo: '', // 申请编号
  approvalName: '', // 申请名称
  createDeptId: '',
  createDeptName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  approvalType: $route.query.approvalType,
  reason: '',
  equipmentList: [],
}) // 表单
const rules = ref<FormRules>({
  reason: [{ required: true, message: '送检原因必填', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 弹窗初始化
const processId = ref()
const disabledProcess = ref(false)
const initDialog = () => {
  dialogStatus.value = $route.params.type as string
  ruleFormRef.value?.resetFields()
  if ($route.params.type === 'create') {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
    ruleForm.value.createDeptId = userStore.deptId
    ruleForm.value.createDeptName = userStore.deptName
    if ($route.query.approvalType === '0') {
      // 提前送检
      ruleForm.value.approvalName = '提前送检申请'
    }
    else {
      // 延迟送检
      ruleForm.value.approvalName = '延迟送检申请'
    }
  }
  else {
    const data = JSON.parse($route.query.row as string)
    if (data.approvalStatusName === '草稿箱') {
      disabledProcess.value = true
    }
    detailApply(data.id).then((res) => {
      ruleForm.value = res.data
      processId.value = res.data.processId
    })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  // $router.back()
  const params = $route.query.approvalType === '0' ? 'ealypage' : 'meteringdelay'
  $router.push({
    path: `/${params}`,
  })
}
const tableRef = ref()
// 保存
const submitId = ref('')
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid && tableRef.value.checkCertificateList()) {
      if (tableRef.value.list.length) {
        ElMessageBox.confirm(
          '确认保存吗？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          },
        ).then((res) => {
          ruleForm.value.equipmentList = tableRef.value.list
          editApply(ruleForm.value).then((res) => {
            submitId.value = res.data
            if (statusName === '已取消' || statusName === '未通过') {
              submitApply({ id: res.data, formId: $route.query.approvalType === '0' ? SCHEDULE.METERING_PLAN_EARLY : SCHEDULE.METERING_PLAN_DEALY }).then((res) => {
                ElMessage.success('已提交')
                close()
              })
            }
            else {
              ElMessage.success('保存成功')
            }
          })
        })
      }
      else {
        ElMessage.warning('请先添加设备')
      }
    }
  })
}
// 提交
const submitForm = () => {
  if (!submitId.value) {
    ElMessage.warning('请先保存')
    return false
  }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitApply({ id: submitId.value, formId: $route.query.approvalType === '0' ? SCHEDULE.METERING_PLAN_EARLY : SCHEDULE.METERING_PLAN_DEALY }).then((res) => {
      ElMessage.success('已提交')
      close()
    })
  })
}
// 关闭
const resetForm = (formEl: FormInstance | undefined) => {
  // formEl?.resetFields()
  close()
}
const cancelForm = () => {
  ElMessageBox.confirm(
    '确认取消此申请吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const row = JSON.parse($route.query.row as string)
    cancelApply({ id: row.id, processInstanceId: row.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
const delForm = () => {
  ElMessageBox.confirm(
    '确认删除该申请吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const row = JSON.parse($route.query.row as string)
    delApply({ id: row.id }).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
const activeName = ref('基本信息')
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page class="base-info-device" :title="`送检申请-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="submitBtn(statusName, dialogStatus) && statusName !== '已取消' && statusName !== '未通过'" type="primary" @click="submitForm()">
          提交
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus)" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button v-if="statusName === '审批中'" type="info" @click="cancelForm()">
          取消
        </el-button>
        <el-button v-if="delTextBtn(statusName)" type="info" @click="delForm()">
          删除
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com v-if="$route.path.includes('update')">
      <el-radio-group v-model="activeName">
        <el-radio-button label="基本信息">
          基本信息
        </el-radio-button>
        <el-radio-button label="审批详情" :disabled="disabledProcess">
          审批详情
        </el-radio-button>
      </el-radio-group>
    </detail-block-com>
    <div v-show="activeName === '基本信息'">
      <detail-block-com>
        <el-form
          ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form"
          :class="[$route.path.includes('detail') ? 'isDetail' : '']" :disabled="$route.path.includes('detail')"
        >
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="申请编号" prop="approvalNo">
                <el-input v-model.trim="ruleForm.approvalNo" placeholder="系统自动生成" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请名称" prop="approvalName">
                <el-input v-model.trim="ruleForm.approvalName" placeholder="申请名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建人" prop="createUserName">
                <el-input v-model.trim="ruleForm.createUserName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                  v-model="ruleForm.createTime" type="date" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" placeholder="请选择创建时间" class="normal-date" style="width: 100%;" disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item :label="`${$route.query.approvalType === '0' ? '提前' : '延迟'}送检原因`" prop="reason">
                <el-input v-model.trim="ruleForm.reason" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </detail-block-com>
      <detail-block-com>
        <plan-list ref="tableRef" :data="ruleForm.equipmentList" :status="$route.params.type as string" />
      </detail-block-com>
    </div>
    <approval-record-table v-if="activeName === '审批详情'" :process-id="processId" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
