<!-- 计量计划-编辑 -->
<script lang="ts" setup name="PlanEdit">
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 { cancelPlan, delPlan, detailPlan, editPlan, getInfoList, submitPlan } from '@/api/eqpt/measurementPlan/paln'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import { SCHEDULE } from '@/utils/scheduleDict'
import { delTextBtn, editBtn, submitBtn } from '@/utils/applyBtns'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string
const typeFlag = ref('')
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
const typeMap: { [key: string]: string } = {
  year: '0',
  season: '1',
  month: '2',
}
// 当前年份
const currentYear = ref<number>()
currentYear.value = new Date().getFullYear()
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref({
  approvalStatus: '', // 审批状态
  createDeptId: '', // 创建单位id
  createDeptName: '', // 创建单位名称
  createTime: '', // 	创建时间
  createUserId: '', // 创建人id
  createUserName: '', // 创建人姓名
  decisionItem: '', // 可选决策项
  equipmentIds: [], // 关联设备id
  id: '',
  month: 0, // month
  planCategory: '0', // 计划分类（字典值，原始/追加）
  planName: '', // 计划名称
  planNo: '', // 计划编号
  planType: '', // 计划类型（字典值，年/季/月）
  processId: '', // 流程实例id
  remark: '', // 备注
  season: 0, // 季度
  taskId: '', // 任务id
  updateTime: '', // 更新时间
  year: '', // 年份
}) // 表单
const rules = ref<FormRules>({
  // planCategory: [{ required: true, message: '计划分类必选', trigger: ['blur', 'change'] }],
  season: [{ required: true, message: '季度必填', trigger: ['blur', 'change'] }],
  month: [{ 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
    ruleForm.value.planType = typeMap[$route.query.category as string]
    typeFlag.value = typeMap[$route.query.category as string]
    ruleForm.value.year = String(currentYear.value)
    if ($route.query.category as string === 'year') {
      ruleForm.value.planName = '2023年年度计量计划'
      ruleForm.value.planType = '0'
    }
  }
  else {
    const data = JSON.parse($route.query.row as string)
    ruleForm.value.year = String(currentYear.value)
    typeFlag.value = data.planType
    ruleForm.value.planType = data.planType
    processId.value = data.processId
    if (data.approvalStatusName === '草稿箱') {
      disabledProcess.value = true
    }
    // 判断是否追加计划
    if ($route.query.append) {
      disabledProcess.value = true
      // 修改计量计划为追加
      ruleForm.value.planCategory = '1'
      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 (typeFlag.value === '0') {
        ruleForm.value.planName = '2023年年度计量计划'
      }
      return
    }
    // 基本信息
    ruleForm.value = {
      ...data,
      equipmentIds: [],
    }
    // 获取计划列表
    getInfoList(data.id, '').then((res) => {
      ruleForm.value.equipmentIds = res.data
    })
  }
}
// 获取计划分类列表
const planTypeList = ref()
const fetchTypeList = () => {
  getDictByCode('eqptPlanType').then((res) => {
    planTypeList.value = res.data
  })
}
fetchTypeList()
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  // $router.back()
  $router.push({ path: '/plan' })
}
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) => {
          if ($route.query.category as string === 'season' || typeFlag.value === '1') {
            ruleForm.value.planName = `${currentYear.value}年第${ruleForm.value.season}季度计量计划`
            ruleForm.value.planType = '1'
          }
          else if ($route.query.category as string === 'month' || typeFlag.value === '2') {
            ruleForm.value.planName = `${currentYear.value}年${ruleForm.value.month}月月度计量计划`
            ruleForm.value.planType = '2'
          }
          ruleForm.value.equipmentIds = tableRef.value.list.map((item: any) => item.equipmentId)
          // console.log(tableRef.value.list, 'tableRef.value.list')
          editPlan(ruleForm.value).then((res) => {
            submitId.value = res.data
            // close()
            if (statusName === '已取消' || statusName === '未通过') {
              submitPlan({ id: submitId.value, formId: SCHEDULE.METERING_PLAN_APPROVAL }).then((res) => {
                ElMessage.success('已提交')
                close()
              })
            }
            else {
              ElMessage.success('保存成功')
            }
          })
          ruleForm.value.equipmentIds = tableRef.value.list
        })
      }
      else {
        ElMessage.warning('请先添加设备')
      }
    }
  })
}
// 提交
const submitForm = () => {
  if (!submitId.value) {
    ElMessage.warning('请先保存')
    return false
  }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((_res) => {
    submitPlan({ id: submitId.value, formId: SCHEDULE.METERING_PLAN_APPROVAL }).then((_res) => {
      ElMessage.success('已提交')
      close()
    }).catch((_err) => {
      ruleForm.value.equipmentIds = tableRef.value.list
    })
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
// 打印
const print = () => {

}
// 审批
const approvalDialogRef = ref()
const apply = (type: string) => {
  const data = JSON.parse($route.query.row as string)
  approvalDialogRef.value.initDialog(type, data.taskId, data.processId, ruleForm.value.id)
}
// 编辑
const editForm = () => {
  $router.push({
    params: { ...$route.params, type: 'update' },
    query: { ...$route.query },
  })
}
const delForm = () => {
  ElMessageBox.confirm(
    '确认删除此记录吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const row = JSON.parse($route.query.row as string)
    delPlan(row.id).then((res) => {
      ElMessage.success('操作成功')
      close()
      // search()
    })
  })
}
const cancelForm = () => {
  ElMessageBox.confirm(
    '确认取消此申请吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const row = JSON.parse($route.query.row as string)
    cancelPlan({ id: row.id, processInstanceId: row.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      close()
      // search()
    })
  })
}
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="statusName === '待审批'" type="primary" @click="apply('agree')">
          同意
        </el-button>
        <el-button v-if="statusName === '待审批'" type="primary" @click="apply('refuse')">
          拒绝
        </el-button>
        <el-button v-if="editBtn(statusName, dialogStatus)" type="primary" @click="editForm()">
          编辑
        </el-button>
        <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="planNo">
                <el-input v-model.trim="ruleForm.planNo" placeholder="系统自动生成" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item v-if="typeFlag === '0'" label="计划名称" prop="year">
                <el-input v-model.trim="ruleForm.planName" placeholder="计划名称" disabled />
              </el-form-item>
              <el-form-item v-if="typeFlag === '1'" label="计划名称" prop="season">
                {{ currentYear }}年第<el-input-number v-model="ruleForm.season" :min="1" :max="4" controls-position="right" style="width: 100px;" /> 季度计量计划
              </el-form-item>
              <el-form-item v-if="typeFlag === '2'" label="计划名称" prop="month">
                {{ currentYear }}年<el-input-number v-model="ruleForm.month" :min="1" :max="12" controls-position="right" style="width: 100px;" /> 月月度计量计划
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计划分类" prop="planCategory">
                <el-select v-model="ruleForm.planCategory" placeholder="选择计划分类" style="width: 100%;" disabled>
                  <el-option v-for="item in planTypeList" :key="item.id" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="创建单位" prop="createDeptName">
                <el-input v-model.trim="ruleForm.createDeptName" 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="备注" prop="remark">
                <el-input v-model.trim="ruleForm.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </detail-block-com>
      <detail-block-com>
        <plan-list ref="tableRef" :data="ruleForm.equipmentIds" :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>
