<script lang="ts" setup name="EnvironmentalList">
import type { Ref } from 'vue'
import { getCurrentInstance, reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, ISupplier, IlistQuery, IlistType } from './plan_interface'
import QrDialog from '@/components/QrDialog/index.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportExcel } from '@/utils/exportXlsx'
import { exportPlanList, getDeptTree, getListDelete, getPlanList } from '@/api/system/plan'
import { printJSON } from '@/utils/printUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
import { exportFile } from '@/utils/exportUtils'
const listQuery = ref({
  createEndTime: '',
  createStartTime: '',
  deptId: '',
  director: '',
  effectiveCompany: '',
  ids: [],
  trainEndTime: '',
  formId: SCHEDULE.TRAIN_APPROVAL,
  trainStartTime: '',
  testCategory: '',
  offset: 1,
  limit: 20,
})
const checkoutList = ref<string[]>([])
const list = ref<ISupplier[]>([])
const total = ref(0)
const show = ref(true)

const loadingTable = ref(false)
// 初始化路由
// 培训时间数组
const trainTime = ref('')

const $router = useRouter()
const fetchData = (isNowPage: boolean) => {
  listQuery.value.trainStartTime = trainTime.value[0] || ''
  listQuery.value.trainEndTime = trainTime.value[1] || ''
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  list.value = [{ text: 'xxx' }]
  loadingTable.value = false
}
fetchData(true)
// 检测类别下拉框数组
const testCategoryList = [
  { name: '检定', id: '1' },
  { name: '检测', id: '2' },
  { name: '验收鉴定', id: '3' },
  { name: '校准', id: '4' },
  { name: '测试', id: '5' },
]
const { proxy } = getCurrentInstance() as any
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '原始记录编号',
    value: 'text',
    width: '120',
    align: 'center',
  },
  {
    text: '原始记录名称',
    value: 'text',
    width: '120',
    align: 'center',
  },
  {
    text: '样品编号',
    value: 'text',
    align: 'center',
  },
  {
    text: '样品名称',
    value: 'text',
    align: 'center',
  },
  {
    text: '出厂编号',
    value: 'text',
    align: 'center',
  },
  {
    text: '型号',
    value: 'text',
    align: 'center',
  },
  {
    text: '检校类别',
    value: 'text',
    align: 'center',
  },
  {
    text: '创建人',
    value: 'text',
    align: 'center',
  },
  {
    text: '创建时间',
    value: 'text',
    align: 'center',
  },
  {
    text: '备注',
    value: 'text',
    align: 'center',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    createEndTime: '',
    createStartTime: '',
    testCategory: '',
    deptId: '',
    director: '',
    effectiveCompany: '',
    formId: SCHEDULE.TRAIN_APPROVAL,
    ids: [],
    trainEndTime: '',
    trainStartTime: '',
    offset: 1,
    limit: 20,
  }
  trainTime.value = ''
  fetchData(true)
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  // if (list.value.length > 0) {
  // }
  // else {
  //   ElMessage.warning('无数据可导出数据')
  // }
  loading.close()
}
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(true)
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  text: string
}
// 点击编辑/详情
const handleEdit = (row: rowReturn, pageType: 'edit' | 'detail') => {
  $router.push(`/lab/primitiveLogList/${pageType}/${row.id}`)
}
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.text}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // getListDelete({ id: row.id as string }).then((res) => {
      //   if (res.code === 200) {
      //     ElMessage({
      //       type: 'success',
      //       message: '删除成功',
      //     })
      //     fetchData(true)
      //   }
      // })
    })
}

const handelClick = (text: string) => {}
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
const add = () => {
  $router.push('/lab/primitiveLogList/add')
}
const exportAll = () => {
  exportExcelBtn()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '环境记录单列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: ISupplier) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '环境记录单列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
</script>

<template>
  <div v-if="show">
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item>
          <el-input
            v-model.trim="listQuery.effectiveCompany"
            placeholder="原始记录编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="样品编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="样品名称"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="出厂编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="型号"
            clearable
          />
        </search-item>
        <search-item>
          <el-select
            v-model="listQuery.testCategory"
            placeholder="请选择检测类别"
            style="width: 195px;"
            clearable
          >
            <el-option
              v-for="item in testCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="创建人"
            clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/add')"
            icon="icon-add"
            title="新建"
            type="primary"
            @click="add"
          />
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/export')"
            icon="icon-export"
            title="导出"
            type="primary"
            @click="exportAll"
          />
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/print')"
            icon="icon-print"
            title="打印"
            type="primary"
            @click="printList"
          />
        </template>
        <normal-table
          :data="list"
          :total="total"
          :columns="columns"
          :query="listQuery"
          :list-loading="loadingTable"
          is-showmulti-select
          @change="changePage"
          @multiSelect="handleSelectionChange"
        >
          <template #columns>
            <el-table-column label="操作" align="center" width="190">
              <template #default="{ row }">
                <el-button
                  v-if="proxy.hasPerm('/measure/train/plan/edit')"
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row, 'edit')"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row, 'detail')"
                >
                  详情
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/measure/train/plan/delete')"
                  size="small"
                  link
                  type="danger"
                  @click="handleDelete(row.$index, row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
