<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 { IEnvironmental, selectionListItem } from './environmentalList_interface'
import QrDialog from '@/components/QrDialog/index.vue'
import { getenvironmentRecordDelete, getenvironmentRecordList } from '@/api/business/environmentRecord/environmentRecord'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
import { exportFile } from '@/utils/exportUtils'
const listQuery = ref({
  environmentCode: '', // 记录单编号
  roomNumber: '', // 房间号
  beginTime: '', // 记录开始时间
  endTime: '', // 记录结束时间
  offset: 1, // 当前页
  limit: 20, // 多少条
})
const checkoutList = ref<string[]>([])
const list = ref<IEnvironmental[]>([])
const total = ref(0)
const show = ref(true)

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

const $router = useRouter()
const fetchData = (isNowPage: boolean) => {
  listQuery.value.beginTime = trainTime.value[0] || ''
  listQuery.value.endTime = trainTime.value[1] || ''
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // getenvironmentRecordList(listQuery.value).then((res) => {

  // })
  list.value = [{
    environmentCode: 'A001',
    roomNumber: '1',
    recorder: '张三',
    temperature: '25',
    humidity: '3',
    outputVoltage: '220',
    zeroGroundVoltage: '2',
    remark: '备注',
    recordTime: '2022-12-12 10:10:10',
    createUser: '100000',
    id: '1',
  },
  {
    environmentCode: 'A001',
    roomNumber: '1',
    recorder: '张三',
    temperature: '25',
    humidity: '3',
    outputVoltage: '220',
    zeroGroundVoltage: '2',
    remark: '备注',
    recordTime: '2022-12-12 10:10:10',
    createUser: '100000',
    id: '2',
  },
  ]
  loadingTable.value = false
}
fetchData(true)
const { proxy } = getCurrentInstance() as any
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '记录单号',
    value: 'environmentCode',
    align: 'center',
  },
  {
    text: '房间号',
    value: 'roomNumber',
    align: 'center',
  },
  {
    text: '记录人',
    value: 'recorder',
    align: 'center',
  },
  {
    text: '记录时间',
    value: 'recordTime',
    width: '180',
    align: 'center',
  },
  {
    text: '温度(℃)',
    value: 'temperature',
    align: 'center',
  },
  {
    text: '湿度(%)',
    value: 'humidity',
    align: 'center',
  },
  {
    text: '输出电压(V)',
    value: 'outputVoltage',
    align: 'center',
  },
  {
    text: '零地电压(V)',
    value: 'zeroGroundVoltage',
    align: 'center',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    environmentCode: '', // 记录单编号
    roomNumber: '', // 房间号
    beginTime: '', // 记录开始时间
    endTime: '', // 记录结束时间
    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
  roomNumber: string
}
// 点击编辑/详情
const handleEdit = (row: rowReturn, pageType: 'edit' | 'detail') => {
  $router.push(`/lab/environmentalList/${pageType}/${row.id}`)
}
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.roomNumber}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // getenvironmentRecordDelete({ 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/environmentalList/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)
}
// 房间号模拟下拉框数据
const selectionList = ref<selectionListItem[]>([
  { label: '101', value: '101' },
  { label: '102', value: '102' },
  { label: '103', value: '103' },
  { label: '104', value: '104' },
])
// 打印列表
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: IEnvironmental) => 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.environmentCode"
            placeholder="记录编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-select
            v-model="listQuery.roomNumber"
            clearable
            filterable
            placeholder="请选择房间号"
            size="default"
          >
            <el-option
              v-for="item in selectionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-date-picker
            v-model="trainTime"
            type="datetimerange"
            range-separator="到"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            start-placeholder="记录时间开始时间"
            end-placeholder="记录时间结束时间"
          />
        </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="160">
              <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>
