<script lang="ts" setup name="standardList">
import { ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, IlistType } from './standard_interface'
import { getTypeSelect } from '@/api/system/price'
import { getRemindListPage, getStandardListDelete, getUsersDept, setRemind } from '@/api/device/standard'
import { exportExcel } from '@/utils/exportXlsx'
// 逻辑代码
const listQuery = ref({
  category: null,
  id: null,
  managerState: null,
  preparationEndDate: '',
  preparationStartDate: '',
  standardLaboratory: null,
  standardName: '',
  standardNo: '',
  validEndTime: '',
  validStartTime: '',
  offset: 1,
  limit: 20,
})
const list = ref([]) // 存放数据
const isShow = ref(true) // 控制新增页面是否显示
// 表头
const columns = ref([
  {
    text: '标准代码',
    value: 'standardNo',
    width: '160',
    align: 'center',
  },
  {
    text: '标准名称',
    value: 'standardName',
    width: '90',
    align: 'center',
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    width: '100',
    align: 'center',
  },
  {
    text: '标准所在部门',
    value: 'standardLaboratory',
    width: '120',
    align: 'center',
  },
  {
    text: '负责人',
    value: 'standardOwnerName',
    align: 'center',
  },
  {
    text: '建标项目',
    value: 'constructionStandardUnitName',
    align: 'center',
  },
  {
    text: '筹建日期',
    value: 'preparationDate',
    width: '160',
    align: 'center',
  },
  {
    text: '有效日期',
    value: 'preparationDate',
    width: '160',
    align: 'center',
  },
])
const total = ref(0)
// 表格loding
const loadingTable = ref(false)
// 选中的数据
const checkoutList = ref([])
// 编辑或者详情id
const infoId = ref('')
// 点击的类型
const buttonType = ref('')
// 类别下拉框
const checkTypeOptions = ref<IOptions[]>([])
// 管理状态下拉框
const standardManagerStateList = ref<IOptions[]>([])
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 获取数据
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getRemindListPage(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
fetchData(true)
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
  })
}
getSelectList('standardCategory') // 获取类别下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框

// 初始化路由
const $router = useRouter()
// 获取部门信息
getUsersDept({
  createTime: null,
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
}).then((res) => {
  standardUsersDeptList.value = res.data.rows
})

// 筹建日期数组
const preparationArr = ref([
  listQuery.value.preparationStartDate,
  listQuery.value.preparationEndDate,
])
// 到期开始以及结束数组
const validTimeArr = ref([
  listQuery.value.validStartTime,
  listQuery.value.validStartTime,
])

// 点击重置
const clearList = () => {
  listQuery.value = {
    category: null,
    id: null,
    managerState: null,
    preparationEndDate: '',
    preparationStartDate: '',
    standardLaboratory: null,
    standardName: '',
    standardNo: '',
    validEndTime: '',
    validStartTime: '',
    offset: 1,
    limit: 20,
  }
  preparationArr.value = []
  validTimeArr.value = []
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '到期提醒模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})

// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    exportExcel({
      json: list.value.map((item: IlistType, index: number) => ({ index: index + 1, standardNo: item.standardNo, standardName: item.standardName, managerStateName: item.managerStateName, standardLaboratoryName: item.standardLaboratoryName, standardOwnerName: item.standardOwnerName, preparationDate: item.preparationDate, remark: item.remark })),
      name: '到期提醒列表',
      titleArr: ['序号', '标准代码', '标准名称', '管理状态', '标准所在部门', '负责人', '筹建日期', '备注'],
      sheetName: 'sheet1',
    })
  }
  else if (checkoutList.value.length > 0) {
    exportExcel({
      json: checkoutList.value.map((item: IlistType, index: number) => ({ index: index + 1, standardNo: item.standardNo, standardName: item.standardName, managerStateName: item.managerStateName, standardLaboratoryName: item.standardLaboratoryName, standardOwnerName: item.standardOwnerName, preparationDate: item.preparationDate, remark: item.remark })),
      name: '到期提醒列表',
      titleArr: ['序号', '标准代码', '标准名称', '管理状态', '标准所在部门', '负责人', '筹建日期', '备注'],
      sheetName: 'sheet1',
    })
  }
  else {
    ElMessage.warning('暂无数据')
  }
  loading.close()
}
// 新增
const addList = () => {
  buttonType.value = ''
  isShow.value = false
}
// 关闭
const close = () => {
  isShow.value = true
  fetchData(true)
}
// 点击导出
const exportAll = () => {
  exportExcelBtn()
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  standardName: string
}
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.standardName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getStandardListDelete({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
// 点击编辑/详情
const handleEdit = (row: rowReturn) => {
  $router.push(`/standard/detail/${row.id}`)
}
// 提醒函数
const warnClick = (row: rowReturn) => {
  ElMessageBox.confirm(
    `确认提醒${row.standardName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      setRemind({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '提醒成功',
          })
          fetchData(true)
        }
      })
    })
}
</script>

<template>
  <app-container v-if="isShow">
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item style="width: 12%;">
        <el-input
          v-model.trim="listQuery.standardNo"
          placeholder="标准代码"
          clearable
        />
      </search-item>
      <search-item style="width: 12%;">
        <el-input
          v-model.trim="listQuery.standardName"
          placeholder="标准名称"
          clearable
        />
      </search-item>
      <search-item style="width: 10%;">
        <el-select
          v-model.trim="listQuery.category"
          clearable
          placeholder="类别"
          size="default"
        >
          <el-option
            v-for="item in checkTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item style="width: 11%;">
        <el-select
          v-model.trim="listQuery.managerState"
          clearable
          placeholder="管理状态"
          size="default"
        >
          <el-option
            v-for="item in standardManagerStateList"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item style="width: 12%;">
        <el-select
          v-model.trim="listQuery.standardLaboratory"
          clearable
          placeholder="标准所在部门"
          size="default"
        >
          <el-option
            v-for="item in standardUsersDeptList"
            :key="item.id"
            :label="item.organizeName"
            :value="item.id"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="preparationArr"
          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-item>
        <el-date-picker
          v-model="validTimeArr"
          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 icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-print="printObj" icon="icon-print" title="打印" type="primary" />
      </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="250">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="warnClick(row)"
              >
                提醒
              </el-button>
              <el-button
                size="small"
                link
                type="danger"
                @click="handleDelete(row.$index, row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
