<!-- 设备分组信息-编辑 -->
<script lang="ts" setup name="TaskEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import tableList from './tableList.vue'
import { addTask, detailTask, updateTask } from '@/api/eqpt/measurementPlan/task'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string
const tableRef = ref()
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref({
  createTime: '',
  createUserId: '',
  createUserName: '',
  customerAddress: '',
  customerId: '',
  customerName: '',
  customerPhone: '',
  customerSampleInfoList: [],
  deliverer: '',
  delivererId: '',
  delivererTel: '',
  id: '',
  isUrgent: '',
  maintainMajor: '',
  measureCompany: '',
  orderNo: '',
  planDeliverTime: '',
  receiveIllustrate: '',
  receiveStatus: '',
  requireOverTime: '',
  undertakeTime: '',
  undertakerId: '',
  undertakerName: '',
  updateTime: '',

}) // 表单
const checkPhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('手机号不能为空'))
  }
  else if (!(/^1[3456789]\d{9}$/.test(value))) {
    callback(new Error('请输入正确手机号'))
  }
  else {
    callback()
  }
}
const rules = ref<FormRules>({
  deliverer: [{ required: true, message: '送检人必填', trigger: ['blur', 'change'] }],
  customerAddress: [{ required: true, message: '委托方地址必填', trigger: ['blur', 'change'] }],
  customerPhone: [{ required: true, message: '电话必填', trigger: ['blur', 'change'] }],
  maintainMajor: [{ required: true, message: '检修专业必填', trigger: ['blur', 'change'] }],
  planDeliverTime: [{ required: true, message: '预计送达时间必选', trigger: ['blur', 'change'] }],
  requireOverTime: [{ required: true, message: '要求检完时间必选', trigger: ['blur', 'change'] }],
  isUrgent: [{ required: true, message: '是否加急必选', trigger: ['blur', 'change'] }],
  measureCompany: [{ required: true, message: '检定(校准)单位必填', trigger: ['blur', 'change'] }],
  undertakerName: [{ required: true, message: '承接人必填', trigger: ['blur', 'change'] }],
  undertakeTime: [{ required: true, message: '承接时间必选', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 弹窗初始化
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.measureCompany = '西昌卫星发射中心计量测试站'
    // ruleForm.value.createDeptId = userStore.deptId
    // ruleForm.value.createDeptName = userStore.deptName
    // 获取当前用户所在单位
    getUserDept().then((res) => {
      console.log(res.data, '用户所在单位')
      // fullName
      ruleForm.value.customerId = res.data.id
      ruleForm.value.customerName = res.data.fullName
    })
  }
  else {
    ruleForm.value = JSON.parse($route.query.row as string)
    detailTask({ id: ruleForm.value.id }).then((res) => {
      ruleForm.value = res.data.data
      console.log(ruleForm.value, 'rule')
      ruleForm.value.isUrgent = String(res.data.data.isUrgent)
    })
  }
}
onMounted(() => {
  initDialog()
})
// 获取是否加急下拉列表
const isUrgentList = ref<{ id: string; value: string; name: string }[]>()
const fetchListData = () => {
  getDictByCode('eqptisUrgent').then((res) => {
    isUrgentList.value = res.data
  })
}
fetchListData()
// 关闭弹窗
const close = () => {
  $router.back()
}
// 新增
const add = () => {
  ruleForm.value.customerSampleInfoList = tableRef.value.list
  addTask(ruleForm.value).then((res) => {
    ElMessage.success('新增成功')
    close()
  })
}
// 编辑
const update = () => {
  ruleForm.value.customerSampleInfoList = tableRef.value.list
  updateTask(ruleForm.value).then((res) => {
    ElMessage.success('修改成功')
    close()
  })
}
// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid && tableRef.value.checkCertificateList()) {
      if (!tableRef.value.list.length) {
        ElMessage.warning('请先选择设备')
        return
      }
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        if (dialogStatus.value === 'create') {
          add()
        }
        else {
          update()
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page :title="`任务单管理-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="!$route.path.includes('detail')" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :class="$route.path.includes('detail') ? 'isDetail' : ''" label-position="right" label-width="120px" class="form" :disabled="$route.path.includes('detail')">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="任务单编号">
              <el-input v-model.trim="ruleForm.orderNo" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model.trim="ruleForm.createUserName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-input v-model.trim="ruleForm.createTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="送检人" prop="deliverer">
              <el-input v-model.trim="ruleForm.deliverer" placeholder="送检人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="委托方" prop="customerName">
              <el-input v-model.trim="ruleForm.customerName" placeholder="委托方" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="委托方地址" prop="customerAddress">
              <el-input v-model.trim="ruleForm.customerAddress" placeholder="委托方地址" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电话" prop="customerPhone">
              <el-input v-model.trim="ruleForm.customerPhone" placeholder="委托方电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="预计送达时间" prop="planDeliverTime">
              <!-- <el-input v-model.trim="ruleForm.planDeliverTime" /> -->
              <el-date-picker
                v-model="ruleForm.planDeliverTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="预计送达时间" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="要求检完时间" prop="requireOverTime">
              <el-date-picker
                v-model="ruleForm.requireOverTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="要求检完时间" class="normal-date" style="width: 100%;"
              />
              <!-- <el-input v-model.trim="ruleForm.requireOverTime" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否加急" prop="isUrgent">
              <!-- <el-input v-model.trim="ruleForm.isUrgent" placeholder="是否加急" /> -->
              <el-select v-model="ruleForm.isUrgent" placeholder="是否加急" style="width: 100%;">
                <el-option v-for="item in isUrgentList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修专业" prop="maintainMajor">
              <el-input v-model.trim="ruleForm.maintainMajor" placeholder="检修专业" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="检定(校准)单位" prop="measureCompany">
              <el-input v-model.trim="ruleForm.measureCompany" placeholder="检定(校准)单位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="承接人" prop="undertakerName">
              <el-input v-model.trim="ruleForm.undertakerName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="承接时间" prop="undertakeTime">
              <!-- <el-input v-model.trim="ruleForm.undertakeTime" /> -->
              <el-date-picker
                v-model="ruleForm.undertakeTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="承接时间" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <table-list ref="tableRef" :data="ruleForm.customerSampleInfoList" :status="dialogStatus" />
    </detail-block-com>
  </app-container>
</template>

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