<!-- 选择原始记录 -->
<script setup lang="ts" name="SelectMeasureDevice">
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import type { fixedAssetsParams, fixedAssetsType } from '@/views/device/standingBook/standingBook-interface'
import { listPageApi } from '@/api/device/standingBook'
import type { IList, IListQuery, dictType } from '@/views/business/lab/primitiveLog/primitiveLogList'
import { getPrimitiveLogDetail, getPrimitiveLogList } from '@/api/business/lab/primitiveLogList'
import { getDictByCode } from '@/api/system/dict'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits(['changeVisible', 'confirmCheckout'])
const mesureCategoryList = ref<dictType[]>([]) // 校检类别
// 查询条件
const listQuery = ref<IListQuery>({
  measureCategory: '',	// 校验类别
  createUser: '',	// 创建人
  manufacturingNo: '',	// 出厂编号
  originalRecordCode: '',	// 原始记录单编号
  sampleModel: '',	// 样品型号
  sampleName: '',	// 样品名称
  sampleNo: '',	// 样品编号
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 表头
const columns = ref<TableColumn[]>([
  { text: '原始记录编号', value: 'originalRecordCode', width: '160', align: 'center', fixed: true },
  { text: '原始记录名称', value: 'originalRecordName', align: 'center', width: '110', fixed: true },
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '检校类别', value: 'measureCategory', align: 'center' },
  { text: '创建人', value: 'createUser', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
  // { text: '备注', value: 'remark', align: 'center' },
])
// 表格数据
const list = ref<IList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref([]) as any
// 获取字典值
async function getDict() {
  // 校检类别
  const response = await getDictByCode('measureCategory')
  mesureCategoryList.value = response.data
}
getDict()

// 列表数据查询
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getPrimitiveLogList(listQuery.value).then((res) => {
    list.value = res.data.rows.map((item: IList) => {
      return {
        ...item,
        sampleNo: item.customerSampleInfo.sampleNo, // 样品编号
        sampleName: item.customerSampleInfo.sampleName, // 样品名称
        manufacturingNo: item.customerSampleInfo.manufacturingNo, // 出厂编号
        sampleModel: item.customerSampleInfo.sampleModel, // 型号
        measureCategory: mesureCategoryList.value.find(i => i.value === item.measureCategory) ? mesureCategoryList.value.find(i => i.value === item.measureCategory)!.name : '', // 校检类别
      }
    })
    total.value = res.data.total
    loadingTable.value = false
  })
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: any) => {
    return {
      ...item,
      isEdit: false,
    }
  })
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    measureCategory: '',	// 校验类别
    createUser: '',	// 创建人
    manufacturingNo: '',	// 出厂编号
    originalRecordCode: '',	// 原始记录单编号
    sampleModel: '',	// 样品型号
    sampleName: '',	// 样品名称
    sampleNo: '',	// 样品编号
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}

// 点击取消
const cancle = () => {
  emits('changeVisible', false)
}

// 获取详情信息
const fetchDetail = (id: string) => {
  if (id) {
    getPrimitiveLogDetail({ id }).then((res) => {
      let responseData = {} as any
      responseData = res.data
      if (res.data.equipmentInfoList && res.data.equipmentInfoList.length) {
        responseData.equipmentInfoList = res.data.equipmentInfoList.map((item: fixedAssetsType) => {
          return {
            ...item,
            validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : '',
          }
        })
      }
      else {
        responseData.equipmentInfoList = []
      }
      responseData.fileList = res.data.fileList || []
      emits('confirmCheckout', responseData)
      cancle()
    })
  }
}

// 点击确定
const clickConfirmSample = async () => {
  if (!checkoutList.value.length) {
    ElMessage({
      message: '请选中',
      type: 'warning',
    })
  }
  await fetchDetail(checkoutList.value[0].id)
}

watch(() => props.visible, (newValue) => {
  if (newValue) {
    fetchData(true)
  }
})
defineExpose({ fetchDetail })
</script>

<template>
  <div class="select-kehu-dialog">
    <el-dialog :model-value="visible" title="选择原始记录" width="65%" @close="cancle">
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item>
          <el-input
            v-model.trim="listQuery.originalRecordCode"
            placeholder="原始记录编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.sampleName"
            placeholder="样品名称"
            clearable
          />
        </search-item>
        <search-item>
          <el-select
            v-model="listQuery.measureCategory"
            placeholder="请选择检校类别"
            style="width: 195px;"
            clearable
          >
            <el-option
              v-for="item in mesureCategoryList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <normal-table
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        :list-loading="loadingTable"
        is-showmulti-select
        :is-multi="false"
        :height="260"
        :page-sizes="[20]"
        @change="changePage"
        @multi-select="handleSelectionChange"
      >
        <!-- 序号 -->
        <template #preColumns>
          <el-table-column label="#" width="55" align="center" fixed>
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
      <template #footer>
        <el-button type="primary" @click="clickConfirmSample">
          确定
        </el-button>
        <el-button @click="cancle">
          取消
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
