<script lang="ts" setup name="standardList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, ISupplier, IlistQuerys } from './standard_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getTypeSelect } from '@/api/system/price'
import { getExportExcel, getStandardList, getStandardListDelete, getUsersDept } from '@/api/device/standard'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
// 列表查询条件
const listQuery: Ref<IlistQuerys> = ref({
  category: '', // 类别
  id: '',
  managerState: '', // 管理状态
  preparationEndDate: '', // 筹建日期结束
  preparationStartDate: '', // 筹建日期开始
  standardLaboratory: '', // 标准所在实验室
  standardName: '', // 标准名称
  standardNo: '', // 标准代码
  validEndTime: '', // 到期结束时间
  validStartTime: '', // 到期开始时间
  offset: 1, // 多少页
  limit: 20, // 一页多少条
})
// 筹建日期
const preparationDate = ref('')
const list = ref<ISupplier[]>([]) // 存放数据
// 获得权限
const { proxy } = getCurrentInstance() as any
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '标准代码',
    value: 'standardNo',
    align: 'center',
  },
  {
    text: '标准名称',
    value: 'standardName',
    align: 'center',
  },
  {
    text: '类别',
    value: 'categoryName',
    align: 'center',
  },
  {
    text: '标准等级',
    value: 'standardLevelName',
    align: 'center',
  },
  {
    text: '传递范围',
    value: 'transmitRangeName',
    align: 'center',
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    align: 'center',
  },
  {
    text: '标准所在部门',
    value: 'standardLaboratoryName',
    align: 'center',
    width: '180',
  },
  {
    text: '负责人',
    value: 'laboratoryOwner',
    align: 'center',
  },
  {
    text: '筹建日期',
    value: 'preparationDate',
    width: '180',
    align: 'center',
  },
  {
    text: '备注',
    value: 'remark',
    align: 'center',
  },
])
const total = ref(0)
// 初始化路由
const $router = useRouter()
// 表格loding
const loadingTable = ref(false)
// 选中的数据
const checkoutList = 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
  }
  // 筹建日期
  listQuery.value.preparationStartDate = preparationDate.value[0] || ''
  listQuery.value.preparationEndDate = preparationDate.value[1] || ''
  getStandardList(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 DeptParams = ref({
  createEndTime: '',
  createstartTime: '',
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '3',
  pdeptId: null,
  offset: 1,
  limit: 999999,
})
// 获取部门信息
getUsersDept(DeptParams.value).then((res) => {
  standardUsersDeptList.value = res.data.rows
})

// 点击重置
const clearList = () => {
  listQuery.value = {
    category: '', // 类别
    id: '',
    managerState: '', // 管理状态
    preparationEndDate: '', // 筹建日期结束
    preparationStartDate: '', // 筹建日期开始
    standardLaboratory: '', // 标准所在实验室
    standardName: '', // 标准名称
    standardNo: '', // 标准代码
    validEndTime: '', // 到期结束时间
    validStartTime: '', // 到期开始时间
    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 handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item: TableColumn) => {
    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)) // checkoutList类型
    printJSON(printList, properties, '标准装置列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      category: listQuery.value.category, // 类别
      id: listQuery.value.id, // 	主键
      managerState: listQuery.value.managerState, // 管理状态
      preparationEndDate: listQuery.value.preparationEndDate, // 筹建结束日期
      preparationStartDate: listQuery.value.preparationStartDate, // 筹建结束日期
      standardLaboratory: listQuery.value.standardLaboratory, // 标准所在实验室
      standardName: listQuery.value.standardName, // 标准名称
      standardNo: listQuery.value.standardNo, // 标准代码
      validEndTime: listQuery.value.validEndTime, // 到期结束日期
      validStartTime: listQuery.value.validStartTime, // 到期开始日期
      ids: checkoutList.value,
    }
    // 导出接口
    getExportExcel(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '标准装置列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  // 关闭loading
  loading.close()
}
// 新增
const addList = () => {
  $router.push('/standard/add')
}
// 关闭
const close = () => {
  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, pageType: 'edit' | 'detail') => {
  $router.push(`/standard/${pageType}/${row.id}`)
}
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.standardNo"
          placeholder="标准代码"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.standardName"
          placeholder="标准名称"
          clearable
        />
      </search-item>
      <search-item>
        <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>
        <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>
        <el-select
          v-model="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="preparationDate"
          type="daterange"
          range-separator="到"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="筹建日期开始日期"
          end-placeholder="筹建日期结束日期"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/standard/list/add')" icon="icon-add" title="新建" type="primary" @click="addList" />
        <icon-button v-if="proxy.hasPerm('/standard/list/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/standard/list/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="180">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/standard/list/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('/standard/list/delete')"
                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>
