<!-- 授权代理委托书详情 -->
<script name="ReviewNoticeDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type{ ICustomerNoticeInfo } from './customer-notice'
import useUserStore from '@/store/modules/user'
import { exportFile, saveReviewNotice, updateReviewNotice } from '@/api/resource/reviewNotice'
import type { IDictType } from '@/commonInterface/resource-interface'
import { getDictByCode } from '@/api/system/dict'
import FilterSysUser from '@/views/resource/common/filterSysUser.vue'
import FilterCustomer from '@/views/resource/common/filterCustomer.vue'

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const userInfo = useUserStore()
const route = useRoute()
const router = useRouter()
const title = ref('')

// 关键字段是否可以编辑
const keyFieldsDisable = ref<boolean>(true)

const noticeFormRef = ref()
const noticeRef = ref()
const refFilterSysUser = ref()
const refFilterCustomer = ref()

const noticeInfo = ref<ICustomerNoticeInfo>({
  id: '',
  customerId: '',
  customerName: '',
  deptId: '',
  labCode: '',
  labCodeName: '',
  noticeUserId: '',
  noticeUserName: '',
  noticeNo: '',
  noticeName: '检测结果复查通知单',
  submitDate: '',
  deviceName: '',
  deviceModel: '',
  deviceNo: '',
  returnDate: '',
  noticeDate: '',
  createUserId: '',
  createUserName: '',
  createTime: '',
})

const noticeFormRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空，请选择', trigger: ['change', 'blur'] }],
}) // 表单验证规则

const noticeRules = ref({
  deptId: [{ required: true, message: '委托单位不能为空，请选择', trigger: ['change', 'blur'] }],
  submitDate: [{ required: true, message: '送检日期不能为空，请选择', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  deviceNo: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  deviceModel: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }],
  returnDate: [{ required: true, message: '寄回日期不能为空', trigger: 'blur' }],
  noticeDate: [{ required: true, message: '通知日期不能为空，请选择', trigger: 'blur' }],
}) // 表单验证规则

// 字典值
const labCodeDict = ref<IDictType[]>([])

// 逻辑

// 保存至草稿箱
const saveNoticeInfo = () => {
  noticeInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 创建时间改为提交时间
  saveReviewNotice(noticeInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的委托方id和委托方编号
      noticeInfo.value.noticeNo = res.data.noticeNo
      noticeInfo.value.id = res.data.id
      id.value = res.data.id

      type.value = 'detail'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 编辑
const updateNoticeInfo = () => {
  updateReviewNotice(noticeInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 新建时保存后的处理 获取返回的id
const saveButtonHandler = async () => {
  if (!noticeRef) { return }

  let formValid

  // 先对表单一进行校验
  await noticeFormRef.value.validate((valid: boolean) => {
    if (valid === false) {
      formValid = false
    }
    else {
      formValid = true
    }
  })

  if (formValid === false) { return }

  // 表单一通过校验后 对表单二进行校验
  await noticeRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveNoticeInfo()
        }
        else if (type.value === 'update') {
          updateNoticeInfo()
        }
      })
    }
  })
}

// 打印Word
const printToWord = () => {
  // exportFile({ id: noticeInfo.value.id, pdf: false })
}

// 打印PDF
const printToPDF = () => {

}

// 打印通知
const printNotice = () => {

}

// 点击 发送 按钮
const sendToCustomer = () => {
  refFilterSysUser.value.showOrHideFilterDialog(true)
}

const sysUserSelectedHandler = (row: any) => {
  refFilterSysUser.value.showOrHideFilterDialog(false)

  if (row.id !== '') {
    noticeInfo.value.noticeUserId = row.id
    noticeInfo.value.noticeUserName = row.name

    updateReviewNotice(noticeInfo.value).then((res) => {
      if (res.code === 200) {
        // 提示保存成功
        ElMessage.success(`发送到 ${noticeInfo.value.customerName} 的 ${noticeInfo.value.noticeUserName} 成功`)
      }
      else {
        // 提示失败信息
        ElMessage.error(`通知单发送至受检单位失败：${res.message}`)
      }
    })
  }
  else {
    ElMessage.error('发送至人员不能为空，请重新选择')
  }
}

const showCustomerFilter = () => {
  refFilterCustomer.value.showOrHideFilterDialog(true)
}

const customerSelectedHandler = (row: any) => {
  refFilterCustomer.value.showOrHideFilterDialog(false)

  if (row.id !== '') {
    noticeInfo.value.customerId = row.id
    noticeInfo.value.deptId = row.deptId
    noticeInfo.value.customerName = row.customerName
  }
  else {
    ElMessage.error('委托单位不能为空，请重新选择')
  }
}

const getLabCodeDict = async () => {
  // 先从缓存中获取
  if (sessionStorage.getItem('bizLabCode') === null || sessionStorage.getItem('bizLabCode') === undefined) {
    // 缓存中没有则调用接口查询
    await getDictByCode('bizLabCode').then((res) => {
      if (res.code === 200) {
        labCodeDict.value = res.data
        sessionStorage.setItem('bizLabCode', JSON.stringify(labCodeDict.value)) // 放到缓存中
      }
    })
  }
  else {
    labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)
  }
}

// 关闭
const resetForm = () => {
  sessionStorage.removeItem('reviewNoticeInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  switch (params.type) {
    case 'create' :
      title.value = '检测结果复查通知单（新增）'

      sessionStorage.removeItem('reviewNoticeInfo')

      noticeInfo.value.createUserId = userInfo.id
      noticeInfo.value.createUserName = userInfo.name
      noticeInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      noticeInfo.value.noticeDate = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

      // 新建时组别代码和实验室代码可以编辑
      keyFieldsDisable.value = false
      break
    case 'update':
      title.value = '检测结果复查通知单（编辑）'

      noticeInfo.value = JSON.parse(sessionStorage.getItem('reviewNoticeInfo')!)
      break
    case 'detail':
      title.value = '检测结果复查通知单（详情）'
      id.value = params.id

      noticeInfo.value = JSON.parse(sessionStorage.getItem('reviewNoticeInfo')!)
      keyFieldsDisable.value = true
      break
    default:
      title.value = ''
      keyFieldsDisable.value = true
      break
  }
}

const initDict = () => {
  getLabCodeDict()
}

// 监听 显示中文
watch(() => noticeInfo.value.labCode, (newVal) => {
  labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)

  if (labCodeDict.value.length > 0) {
    const targetList = labCodeDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      noticeInfo.value.labCodeName = targetList[0].name
    }
    else {
      noticeInfo.value.labCodeName = ''
    }
  }
})

onMounted(() => {
  initDict()
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <el-form ref="noticeFormRef" :model="noticeInfo" :rules="noticeFormRules" label-position="right" label-width="110px" border stripe>
      <detail-page :title="`${title}`">
        <template #btns>
          <template v-if="type === 'detail'">
            <el-button type="primary" @click="sendToCustomer">
              发送给受检单位
            </el-button>
            <el-button type="primary" @click="printToWord">
              导出Word
            </el-button>
            <el-button type="primary" @click="printToPDF">
              导出PDF
            </el-button>
            <el-button type="primary" @click="printNotice">
              打印
            </el-button>
          </template>

          <el-button v-else type="primary" @click="saveButtonHandler">
            保存
          </el-button>
          <el-button type="info" @click="resetForm()">
            关闭
          </el-button>
        </template>

        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="实验室代码" prop="labCode">
              <el-select v-model="noticeInfo.labCode" placeholder="请选择实验室代码" tabindex="1" :disabled="keyFieldsDisable" style="width: 100%;">
                <el-option v-for="dict in labCodeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
              <el-input v-model="noticeInfo.labCodeName" type="hidden" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="通知单编号">
              <el-input v-model="noticeInfo.noticeNo" placeholder="通知单编号，保存后自动生成" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model="noticeInfo.noticeName" type="hidden" />
              <el-input v-model="noticeInfo.createUserId" type="hidden" />
              <el-input v-model="noticeInfo.createUserName" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-input v-model="noticeInfo.createTime" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </detail-page>
    </el-form>

    <el-form ref="noticeRef" :model="noticeInfo" :rules="noticeRules" style="display: flex; white-space: nowrap; flex-wrap: wrap;">
      <el-input v-model="noticeInfo.labCode" type="hidden" />
      <el-input v-model="noticeInfo.labCodeName" type="hidden" />
      <el-input v-model="noticeInfo.noticeNo" type="hidden" />
      <el-input v-model="noticeInfo.noticeName" type="hidden" />
      <el-input v-model="noticeInfo.createUserId" type="hidden" />
      <el-input v-model="noticeInfo.createUserName" type="hidden" />
      <el-input v-model="noticeInfo.createTime" type="hidden" />
      <detail-block style="margin-top: 20px; width: 100%; font-size: 1.5rem;" title="">
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="notice-title">
              检测结果复查通知单
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="padding: 0 6rem;">
          <el-form-item label="" prop="deptId">
            <el-input v-model="noticeInfo.customerId" type="hidden" />
            <el-input v-model="noticeInfo.deptId" type="hidden" />
            <el-input v-model="noticeInfo.customerName" placeholder="请选择委托单位" size="large" :disabled="true" style="width: 300px;">
              <template #append>
                <el-button size="small" :disabled="type === 'detail'" @click="showCustomerFilter">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-row>

        <el-row :gutter="24" style="margin-top: 30px; padding: 0 8rem;">
          <span class="notice-text">由于我站工作失误，贵单位于</span>

          <el-form-item label="" prop="submitDate">
            <el-date-picker
              v-model="noticeInfo.submitDate" type="date"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择送检时间" :clearable="true" :disabled="type === 'detail'"
              size="large"
              style="width: 300px; margin: 0 10px;"
            />
          </el-form-item>

          <span class="notice-text">送来的</span>

          <el-form-item label="" prop="deviceName">
            <el-input
              v-model="noticeInfo.deviceName" placeholder="设备名称"
              :clearable="true" :disabled="type === 'detail'"
              size="large" style="width: 300px; margin: 0 10px;"
            />
          </el-form-item>
        </el-row>

        <el-row :gutter="24" style="margin-top: 20px;padding: 0 6rem;">
          <el-form-item label="" prop="deviceModel">
            <el-input
              v-model="noticeInfo.deviceModel" placeholder="设备型号"
              :clearable="true" :disabled="type === 'detail'"
              size="large" style="width: 300px;"
            />
          </el-form-item>

          <el-form-item label="" prop="deviceNo">
            <el-input
              v-model="noticeInfo.deviceNo" placeholder="设备编号"
              :clearable="true" :disabled="type === 'detail'"
              size="large" style="width: 300px; margin: 0 10px;"
            />
          </el-form-item>

          <span class="notice-text">测量结果可能有误，需重新进行测试、校准或检定。</span>
        </el-row>

        <el-row :gutter="24" style="margin-top: 20px;padding: 0 6rem;">
          <span class="notice-text">请贵单位于</span>

          <el-form-item label="" prop="returnDate">
            <el-date-picker
              v-model="noticeInfo.returnDate" type="date"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择寄回时间" :clearable="true" :disabled="type === 'detail'"
              style="width: 300px; margin: 0 10px;" size="large"
            />
          </el-form-item>

          <span class="notice-text">前将此设备以及证书或报告一同送（寄）回本站，谢谢合作。</span>
        </el-row>

        <el-row :gutter="24" style="margin-top: 50px;">
          <el-col :span="6" :offset="10">
            <span class="notice-text"> 特此通知 </span>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="margin-top: 50px;">
          <el-col :span="6" :offset="12">
            <span class="notice-text">中国西昌卫星发射中心计量测试站</span>

            <el-form-item label="" prop="noticeDate">
              <el-date-picker
                v-model="noticeInfo.noticeDate" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择通知日期" :clearable="true" :disabled="type === 'detail'"
                style="width: 300px; margin-top: 20px;" size="large"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </detail-block>
    </el-form>

    <filter-sys-user ref="refFilterSysUser" @record-selected="sysUserSelectedHandler" />

    <filter-customer ref="refFilterCustomer" @record-selected="customerSelectedHandler" />
  </app-container>
</template>

<style scoped>
.notice-title {
  text-align: center;
  font-weight: bold;
  font-size: 2rem;
  font-family: SimSun, STSong;
  margin-bottom: 50px;
}

.notice-text {
  font-family: SimSun, STSong;
  line-height: 40px;
}
</style>
