<script lang="ts" setup name="standardList">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, IlistType } from './standard_interface'
import StandardListAdd from './components/standardListAdd.vue'
import { getTypeSelect } from '@/api/system/price'
import { getStandardList, getStandardListDelete, getUsersDept } from '@/api/device/standard'
import { exportExcel } from '@/utils/exportXlsx'
// 逻辑代码

const listQuery = ref({
  standardNo: '',
  standardName: '',
  category: '',
  managerState: null,
  standardLaboratory: null,
  preparationDate: null,
  id: null,
  offset: 1,
  limit: 10,
})
const list = ref([]) // 存放数据
const isShow = ref(true) // 控制新增页面是否显示
// 获得权限
const { proxy } = getCurrentInstance() as any
// 表头
const columns = ref([
  {
    text: '标准代码',
    value: 'standardNo',
    width: '120',
  },
  {
    text: '标准名称',
    value: 'standardName',
    width: '90',
  },
  {
    text: '类别',
    value: 'categoryName',
    width: '80',
  },
  {
    text: '标准等级',
    value: 'standardLevelName',
    width: '100',
  },
  {
    text: '传递范围',
    value: 'transmitRange',
    width: '110',
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    width: '100',
  },
  {
    text: '标准所在部门',
    value: 'standardLaboratoryName',
    width: '120',
  },
  {
    text: '负责人',
    value: 'laboratoryOwner',
  },
  {
    text: '筹建日期',
    value: 'preparationDate',
    width: '110',
  },
  {
    text: '备注',
    value: 'remark',
    width: '80',
  },
])
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
  }
  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') // 获取管理状态下拉框

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

// 点击重置
const clearList = () => {
  listQuery.value = {
    standardNo: '', // 标准代码
    standardName: '', // 标准名称
    category: '', // 类别
    managerState: null,
    standardLaboratory: null,
    preparationDate: null,
    id: null,
    offset: 1,
    limit: 10,
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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, categoryName: item.categoryName, standardLevel: item.standardLevel, transmitRange: item.transmitRange, 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, categoryName: item.categoryName, standardLevel: item.standardLevel, transmitRange: item.transmitRange, 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 handleClick = (index: number, row: rowReturn, text: string) => {
  infoId.value = row.id
  buttonType.value = text
  isShow.value = false
}
</script>

<template>
  <app-container v-if="isShow">
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item style="width: 15%;">
        <el-input
          v-model.trim="listQuery.standardNo"
          placeholder="标准代码"
          clearable
        />
      </search-item>
      <search-item style="width: 15%;">
        <el-input
          v-model.trim="listQuery.standardName"
          placeholder="标准名称"
          clearable
        />
      </search-item>
      <search-item style="width: 15%;">
        <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: 15%;">
        <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: 15%;">
        <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 style="width: 15%;">
        <el-date-picker
          v-model="listQuery.preparationDate"
          type="datetime"
          clearable
          placeholder="筹建日期"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD h:m:s"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <el-button v-if="proxy.hasPerm('/standard/list/add')" type="primary" @click="addList">
          新建
        </el-button>
        <el-button v-if="proxy.hasPerm('/standard/list/export')" type="primary" @click="exportAll">
          导出
        </el-button>
        <el-button v-if="proxy.hasPerm('/standard/list/print')" v-print="printObj" type="primary">
          打印
        </el-button>
      </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
                v-if="proxy.hasPerm('/standard/list/edit')"
                size="small"
                type="primary"
                link
                @click="handleClick(row.$index, row, '编辑')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="handleClick(row.$index, row, '详情')"
              >
                详情
              </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>
  <standard-list-add
    v-else :info-id="infoId" :button-type="buttonType"
    @close="close"
  />
</template>

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