<!-- 设备运输过程详情 -->
<script lang="ts" setup name="EquipementResumeCourseDetail">
import { ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage } from 'element-plus'
import type { ICheckList, IForm } from './course-interface'
import { getUserList } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'
import { useCheckList } from '@/commonMethods/useCheckList'
import { UploadFile } from '@/api/file'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { addResumeCourseList, getInfo, updateResumeCourseList } from '@/api/equipment/resume/course'
// import type { IOptions } from '@/views/device/standardEquipment/standard_interface'
const user = useUserStore() // 用户信息
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const $router = useRouter() // 关闭页面使用
const $route = useRoute() // 路由参数
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
const ruleFormRef = ref() // 表单ref
const form = ref<IForm>({
  labCode: '', // 实验室代码
  groupCode: '',	// 组别代码(字典code)
  groupCodeName: '',	// 组别代码(字典value)
  formNo: '', // 检查单编号
  formName: '', // 检查单名称
  createUserId: '', // 创建人id
  createUserName: '', // 创建人
  createTime: '', // 创建时间
  quantity: 0, // 运输总数量
  directorId: '', // 运输负责人id
  director: '', // 运输负责人名字
  transportReason: '', // 运输原因
  transportFile: '', // 附件
})
// 校验规则
const formRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
})
const isMulti = ref(false) // 是否多选
// -------------------------------------------字典------------------------------------------
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const labCodeList = ref<dictType[]>([]) // 实验室代码
const groupCodeList = ref<dictType[]>([]) // 组别代码
// 获取字典值
async function getDict() {
  // 实验室代码
  getDictByCode('bizLabCode').then((response) => {
    labCodeList.value = response.data
  })
  // 组别代码
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })
  // 获取用户列表
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
}
// ----------------------------------路由参数--------------------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  console.log(pageType.value)

  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// ----------------------------------------检查内容-----------------------------------------------
const list = ref<ICheckList[]>([]) // 检查内容表格数据
const checkoutList = ref<ICheckList[]>([]) // 选中数据
const columns = [ // 表头
  { text: '检查时机', value: 'checkMoment', align: 'center', required: true },
  { text: '包装箱数量检查', value: 'checkQuantity', align: 'center', required: true },
  { text: '包装箱外观检查', value: 'checkAppearance', align: 'center', required: true },
  { text: '检查时间', value: 'checkTime', align: 'center', required: true },
  { text: '检查人', value: 'checkUserName', align: 'center', required: true },
]

// 点击增加行
const addRow = () => {
  if (useCheckList(list.value, columns, '检查内容')) {
    isMulti.value = false
    useSetAllRowReadable(list.value)
    list.value.push({
      id: '', // 更新/删除使用参数
      checkMoment: '', // 检查时机
      checkQuantity: '', // 包装箱数量检查
      checkAppearance: '', // 包装箱外观检查
      checkTime: '', // 检查时间
      checkUserId: '', // 检查人id
      checkUserName: '', // 检查人
      editable: true,
    })
  }
}
// 点击删除行
const deleteRow = () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请选中要删除的行')
    return false
  }
  list.value = list.value.filter((item: any) => {
    return !checkoutList.value.includes(item)
  })
}

// 选中
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}

// 双击行
const rowDblclick = (row: ICheckList) => {
  if (pageType.value !== 'detail') {
    useDoubleClickTableRow(row, list.value)
  }
}

const getName = (e: any, row: ICheckList) => {
  const obj = userList.value.find((item) => {
    return item.id === e
  })
  row.checkUserName = obj!.name
}
// -------------------------------------------文件上传--------------------------------------
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.transportFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// -------------------------------------------按钮----------------------------------------------
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 导出word
const exportWord = () => { ElMessage.info('敬请期待') }

// 导出pdf
const exportPdf = () => { ElMessage.info('敬请期待') }

// 打印
const print = () => { ElMessage.info('敬请期待') }

// 点击编辑按钮
const edit = () => {
  pageType.value = 'edit'
}

// 保存
const save = () => {
  if (!useCheckList(list.value, columns, '检查内容')) { return false }
  if (!list.value.length) {
    ElMessage.warning('检查内容不能为空')
    return false
  }
  ruleFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const params = {
        ...form.value,
        id: infoId.value,
        checkList: list.value.map((item: any) => {
          return {
            ...item,
            checkUserId: item.checkUserId,
          }
        }),
      }
      // 新建
      if (pageType.value === 'add') { // 新建
        addResumeCourseList(params).then((res) => {
          ElMessage.success('保存成功')
          form.value.formNo = res.data.formNo // 检查单单号
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
      // 保存
      else if (pageType.value === 'edit') { // 编辑
        updateResumeCourseList(params).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    }
    else {
      console.log('表单校验不通过')
    }
  })
}

// -------------------------------------------获取详情信息--------------------------------------------------
// 获取详情信息
const fetchInfo = () => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getInfo({ id: infoId.value }).then((res) => {
    form.value = res.data
    list.value = res.data.checkList.map((item: any, index: number) => {
      return {
        ...item,
        checkTime: item.checkTime ? dayjs(item.checkTime).format('YYYY-MM-DD HH:mm') : item.checkTime, // 检查时间
      }
    })
    loading.close()
  })
}

onMounted(async () => {
  getDict().then(() => {
    form.value.createUserId = user.id// 创建人
    form.value.createUserName = user.name // 创建人名字
    form.value.formName = '设备运输过程检查单' // 记录单名称
    form.value.createTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 创建时间
    if (pageType.value !== 'add') {
      fetchInfo()
    }
  })
})
</script>

<template>
  <app-container>
    <detail-page :title="`设备运输过程管理-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail'" type="primary" @click="exportWord">
          导出word
        </el-button>
        <el-button v-if="pageType === 'detail'" type="primary" @click="exportPdf">
          导出pdf
        </el-button>
        <el-button v-if="pageType === 'detail'" type="primary" @click="print">
          打印
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save">
          保存
        </el-button>
        <el-button v-if="pageType === 'detail'" type="primary" @click="edit">
          编辑
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-width="120"
        label-position="right"
        :rules="formRules"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="实验室代码" prop="labCode">
              <el-select v-model="form.labCode" :placeholder="pageType === 'detail' ? ' ' : '请选择实验室代码'" :disabled="pageType === 'detail'" class="full-width-input">
                <el-option v-for="item in labCodeList" :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="groupCode">
              <el-select v-model="form.groupCode" :placeholder="pageType === 'detail' ? ' ' : '请选择组别代码'" :disabled="pageType === 'detail'" class="full-width-input">
                <el-option v-for="item in groupCodeList" :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="formNo">
              <el-input v-model="form.formNo" class="full-width-input" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检查单名称:" prop="formName">
              <el-input v-model="form.formName" class="full-width-input" disabled placeholder="请输入记录单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人:" prop="createUserName">
              <el-input
                v-model="form.createUserName"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '创建人'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间:" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输总数量:" prop="quantity">
              <el-input-number
                v-model="form.quantity"
                :step="1"
                :min="0"
                :precision="0"
                :step-strictly="true"
                :placeholder="pageType === 'detail' ? '' : '请输入运输总数量'"
                class="full-width-input"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输负责人" prop="directorId">
              <el-select
                v-model.trim="form.directorId"
                placeholder="请选择运输负责人"
                filterable
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="运输原因:" prop="transportReason">
              <el-input
                v-model="form.transportReason"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? ' ' : '请输入运输原因'"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="附件:">
              <show-photo v-if="form.transportFile" :minio-file-name="form.transportFile" />
              <span v-else-if="pageType === 'detail'">无</span>
              <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.transportFile === '' ? '0px' : '20px' }" @click="upload">
                {{ form.transportFile === '' ? '上传' : '更换附件' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="检查内容">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="primary" @click="addRow">
          增加行
        </el-button>
        <el-button type="info" @click="deleteRow">
          删除行
        </el-button>
      </template>

      <el-table
        ref="table"
        :data="list"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        @row-dblclick="rowDblclick"
      >
        <el-table-column v-if="pageType !== 'detail'" type="selection" width="38" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <span v-if="pageType === 'detail'">{{ scope.row[item.value] }}</span>
            <el-select
              v-if="pageType !== 'detail' && item.value === 'checkUserName'"
              v-model.trim="scope.row[item.value]"
              placeholder="请选择检查人"
              filterable
              :disabled="pageType === 'detail'"
              class="full-width-input"
              @change="getName($event, scope.row)"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-date-picker
              v-if="pageType !== 'detail' && item.value === 'checkTime'"
              v-model="scope.row[item.value]"
              type="datetime"
              placeholder="请选择检查时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              class="full-width-input"
              :disabled="pageType === 'detail'"
            />
            <el-input v-if="pageType !== 'detail' && item.value !== 'checkUserName' && item.value !== 'checkTime'" v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
  </app-container>
</template>

<style lang="scss" scoped>
.step {
  line-height: 28px;
  font-size: 20px;
  color: #3d7eff;
  font-weight: bold;
  margin-bottom: 5px;
  width: fit-content;
}
</style>

<style lang="scss">
.fieldtest-record-detail {
  .el-table thead.is-group th.el-table__cell {
    background: #f2f6ff;
  }
}
</style>
