<!--
 * @Author: wanglj wanglijie@dashoo.cn
 * @Date: 2025-03-18 20:02:42
 * @LastEditors: wanglj wanglijie@dashoo.cn
 * @LastEditTime: 2025-03-21 09:46:32
 * @FilePath: \labsop_h5\src\view\training\enroll.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <van-form ref="formRef" @submit="onSubmit" class="mt10" required="auto">
      <h4 class="mb8 mt8">设备信息</h4>
      <van-cell-group>
        <van-field
          v-model="state.form.equipmentName"
          label="设备名称"
          placeholder="设备名称"
          @click="openSelectInst"
          :rules="[{ required: true, message: '请选择仪器' }]"
        />
        <van-field v-model="state.form.equipmentCode" label="设备编号" placeholder="设备编号" readonly />
        <van-field v-model="state.form.equipmentModel" label="设备型号" placeholder="设备型号" readonly />
        <van-field v-model="state.form.equipmentManager" label="设备负责人" placeholder="设备负责人" readonly />
        <van-field v-model="state.form.equipmentLocation" label="存放位置" placeholder="存放位置" readonly />
        <van-field v-model="state.form.recordName" label="预约记录" placeholder="预约记录" @click="openSelectUsedRecord" />
      </van-cell-group>
      <h4 class="mb8 mt8">报修信息</h4>
      <van-cell-group>
        <van-field v-model="state.form.repairApplicantName" label="报修人" placeholder="报修人" :rules="[{ required: true }]" />
        <van-field
          v-model="state.form.repairDate"
          label="报修时间"
          placeholder="报修时间"
          :rules="[{ required: true, message: '请选择报修时间' }]"
          @click="showAddDatePicker = true"
          readonly
        />
        <van-field
          v-model="state.form.faultDesc"
          rows="3"
          autosize
          type="textarea"
          maxlength="200"
          show-word-limit
          label="故障说明"
          placeholder="故障说明"
          :rules="[{ required: true, message: '请输入故障说明' }]"
        />
        <van-field name="uploader" label="文件上传" :rules="[{ required: true, message: '请上传故障照片' }]">
          <template #input>
            <van-uploader v-model="state.form.faultPhoto" :after-read="afterRead" preview-size="60" :preview-full-image="true" :max-count="6" />
          </template>
        </van-field>
      </van-cell-group>
      <van-action-bar placeholder>
        <van-action-bar-icon icon="wap-home-o" text="首页" @click="router.push('/home')" />
        <van-action-bar-icon icon="revoke" text="返回" @click="router.push('/inst/repairReport/home')" />
        <van-action-bar-button type="primary" text="立即提交" :loading="loading" native-type="submit" />
      </van-action-bar>
    </van-form>
  </div>

  <SelectInstPopup ref="SelectInstRef" @selectInst="getSelectInst"></SelectInstPopup>

  <SelectInstAppointRecordPopup ref="usedRecordRef" @selectUseRecord="getSelectUsedRecord"></SelectInstAppointRecordPopup>

  <!-- 所在时间 -->
  <van-popup v-model:show="showAddDatePicker" position="bottom">
    <van-date-picker v-model="date" title="选择日期" @confirm="onConfirmDate" :max-date="maxDate" @cancel="showAddDatePicker = false" />
  </van-popup>
</template>

<script name="repairReportConfirm" lang="ts" setup>
  import to from 'await-to-js'
  import { onMounted, reactive, ref, defineAsyncComponent } from 'vue'
  import { storeToRefs } from 'pinia'
  import { useUserInfo } from '/@/stores/userInfo'
  import { showNotify } from 'vant'
  import { formatDate } from '/@/utils/formatTime'
  import { useRouter } from 'vue-router'
  import { handleUpload } from '/@/utils/upload'
  import { useRepairReportApi } from '/@/api/instr/repairReport'

  const SelectInstPopup = defineAsyncComponent(() => import('/@/components/select-inst.vue'))
  const SelectInstAppointRecordPopup = defineAsyncComponent(() => import('/@/components/select-inst-appoint-record.vue'))

  const SelectInstRef = ref()
  const usedRecordRef = ref()

  const repairReportApi = useRepairReportApi()
  const storesUseUserInfo = useUserInfo()
  const router = useRouter()

  const { userInfos } = storeToRefs(storesUseUserInfo)

  const formRef = ref()
  const state = reactive({
    form: {
      id: 0,
      equipmentCode: '', //设备编码	string
      equipmentId: '', //关联设备	integer
      equipmentLocation: '', //设备存放位置	string
      equipmentManager: '', //设备负责人（带电话）	string
      equipmentModel: '', //设备型号(带品牌)	string
      equipmentName: '', //设备名称	string
      recordId: 0,
      recordName: '',
      repairApplicantName: '', //报修人
      repairDate: formatDate(new Date(), 'YYYY-mm-dd'), //报修时间 DATETIME	string
      faultDesc: '', //故障说明	string
      faultPhoto: <any>[], //故障照片	string
      remark: '' //备注	string
    }
  })
  const loading = ref(false) // 加载状态

  const initForm = async () => {
    state.form = {
      id: 0,
      equipmentCode: '', //设备编码	string
      equipmentId: '', //关联设备	integer
      equipmentLocation: '', //设备存放位置	string
      equipmentManager: '', //设备负责人（带电话）	string
      equipmentModel: '', //设备型号(带品牌)	string
      equipmentName: '', //设备名称	string
      recordId: 0,
      recordName: '',
      repairApplicantName: '', //报修人
      repairDate: formatDate(new Date(), 'YYYY-mm-dd'), //报修时间 DATETIME	string
      faultDesc: '', //故障说明	string
      faultPhoto: <any>[], //故障照片	string
      remark: '' //备注	string
    }
    date.value = [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]
    console.log(userInfos.value)
    state.form.repairApplicantName = userInfos.value.nickName // 报修人
  }

  const date = ref([]) // 选择的日期
  const maxDate = ref(new Date()) // 最大日期

  const showAddDatePicker = ref(false) // 是否显示选择日期的弹窗
  const onSubmit = async () => {
    console.log('提交表单')
    const [errValid] = await to(formRef.value.validate())
    if (errValid) return
    let params = JSON.parse(JSON.stringify(state.form))
    console.log(params)
    const files = params.faultPhoto.map((item: any) => {
      return {
        name: item.name,
        url: item.url
      }
    })
    params.faultPhoto = JSON.stringify(files) // 将图片数组转换为符合后端要求的格式
    loading.value = true
    const [err, res]: ToResponse = await to(repairReportApi.create(params))
    loading.value = false
    if (err) return
    showNotify({
      type: 'success',
      message: '报修申请已提交，请耐心等待处理'
    })
    setTimeout(() => {
      router.push('/inst/repairReport/home')
    }, 1000)
  }

  const openSelectInst = () => {
    SelectInstRef.value.openPopup()
  }

  const openSelectUsedRecord = () => {
    if (state.form.equipmentId === '') {
      showNotify({
        type: 'warning',
        message: '请先选择设备'
      })
      return
    }
    usedRecordRef.value.openPopup(state.form.equipmentId)
  }

  const getSelectInst = (data: any) => {
    console.log(data)
    state.form.equipmentCode = data.instCode //设备编码	string
    state.form.equipmentId = data.id //关联设备	integer
    state.form.equipmentLocation = data.placeAddress //设备存放位置	string
    state.form.equipmentManager = data.instHeadName + '-' + data.instHeadTel //设备负责人（带电话）	string
    state.form.equipmentModel = data.instNameEn //设备型号(带品牌)	string
    state.form.equipmentName = data.instName //设备名称	string};
    state.form.recordId = 0
    state.form.recordName = '' //预约记录
  }

  const getSelectUsedRecord = (data: any) => {
    console.log(data)
    state.form.recordId = data.id
    state.form.recordName = data.createdName
  }

  const onConfirmDate = () => {
    showAddDatePicker.value = false
    state.form.repairDate = `${date.value[0]}-${date.value[1]}-${date.value[2]}`
  }

  const afterRead = async (files: any) => {
    if (files.length) {
      for (const file of files) {
        file.status = 'uploading'
        const [err, res]: ToResponse = await to(handleUpload(file.file))
        if (err) {
          file.status = 'failed'
          return
        }
        file.status = 'success'
        file.url = res
        file.name = file.file.name
      }
    } else {
      const file = files
      file.status = 'uploading'
      const [err, res]: ToResponse = await to(handleUpload(file.file))
      if (err) {
        file.status = 'failed'
        return
      }
      file.status = 'success'
      file.url = res
      file.name = file.file.name
    }
  }

  onMounted(async () => {
    initForm()
  })
</script>

<style lang="scss" scoped>
  .app-container {
    header {
      padding: 14px;
      background-color: #f9ffff;
      border-radius: 4px;
      margin-top: 10px;
    }
    h4 {
      margin: 10px 0;
      height: 20px;
      line-height: 20px;
      &::before {
        display: inline-block;
        content: '';
        background-color: #3c78e3;
        width: 4px;
        height: 20px;
        margin-right: 4px;
        vertical-align: top;
      }
    }
    :deep(.flow-cell) {
      margin-left: 22px;
      display: flex;
      justify-content: space-between;
      color: #333;
    }
  }
  .ck-editor {
    height: calc(100vh - 100px);
    overflow-y: auto;
    padding: 0 10px;
  }
  .need-to-know {
    height: calc(100% - 20px);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding: 10px 20px;
    white-space: pre-wrap;
    p {
      flex: 1;
      overflow-y: auto;
    }
    footer {
      flex: 0 0 45px;
      margin-top: 4px;
      border-top: 1px solid #f7f8fa;
    }
  }
</style>
