<!-- 产品管理 列表 -->
<script name="ProductList" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type { IDictType } from '../common-interface'
import type { IListQuery, IProductInfo } from './product-info'
import AddProductDialog from './addProductDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { delProduct, getProductListPage } from '@/api/basic/product'
import { getDictByCode } from '@/api/system/dict'

const { proxy } = getCurrentInstance() as any

const refAddProductDialog = ref()

// 查询条件
const searchQuery = ref<IListQuery>({
  productName: '', // 产品名
  model: '',
  encipherType: '',
  accessType: '',
  deviceType: '',
  beginTime: '', // 创建时间-起始
  endTime: '', // 创建时间-结束
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '产品编号', value: 'productNo', align: 'center' },
  { text: '产品名称', value: 'name', align: 'center' },
  { text: '设备类型', value: 'deviceTypeName', align: 'center' },
  { text: '设备型号', value: 'model', align: 'center', width: '200' },
  { text: '数据加密方式', value: 'encipherTypeName', align: 'center', width: '180' },
  { text: '通信方式', value: 'communicationProtocolName', align: 'center', width: '180' },
  { text: '接入方式', value: 'accessTypeName', align: 'center', width: '180' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
const dataList = ref<Array<IProductInfo>>([]) // 表格数据

const deviceTypeDict = ref<Array<IDictType>>([])
const accessTypeDict = ref<Array<IDictType>>([])
const powerTypeDict = ref<Array<IDictType>>([])
const encipherTypeDict = ref<Array<IDictType>>([])
const communicationDict = ref<Array<IDictType>>([])

// 逻辑

// 跳转到新建的页面
const addProduct = () => {
  refAddProductDialog.value.initDialog({ type: 'create' })
}

// 详情
const detail = (row: IProductInfo) => {
  sessionStorage.setItem('productInfo', JSON.stringify(row))
  refAddProductDialog.value.initDialog({ type: 'detail' })
}

// 编辑
const updateById = (row: IProductInfo) => {
  sessionStorage.setItem('productInfo', JSON.stringify(row))
  refAddProductDialog.value.initDialog({ type: 'update', id: row.id })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getProductListPage(searchQuery.value).then((response) => {
    if (response.code === 200) {
      dataList.value = response.data.rows
      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
    calcTableHeight()
  }).catch(() => {
    loadingTable.value = false
  })
}

const searchList = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 重置
const reset = () => {
  searchQuery.value = {
    productName: '', // 产品名
    model: '',
    beginTime: '', // 创建时间-起始
    endTime: '', // 创建时间-结束
    encipherType: '',
    accessType: '',
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 删除
const deleteById = (row: IProductInfo) => {
  ElMessageBox.confirm(`是否删除产品 ${row.name}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delProduct(row.id!).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`产品 ${row.name} 删除成功`)
        fetchData(true)
      }
      else {
        ElMessage.error(`产品 ${row.name} 删除失败: ${res.message}`)
      }
    })
  })
}

const productSavedHandler = () => {
  fetchData(true)
}

// 获取在用状态字典值
const getDeviceTypeDict = () => {
  getDictByCode('deviceType').then((res: any) => {
    if (res.code === 200) {
      deviceTypeDict.value = res.data
      sessionStorage.setItem('deviceType', JSON.stringify(res.data))
    }
  })
}
const getAccessTypeDict = () => {
  getDictByCode('accessType').then((res: any) => {
    if (res.code === 200) {
      accessTypeDict.value = res.data
      sessionStorage.setItem('accessType', JSON.stringify(res.data))
    }
  })
}
const getPowerTypeDict = () => {
  getDictByCode('powerType').then((res: any) => {
    if (res.code === 200) {
      powerTypeDict.value = res.data
      sessionStorage.setItem('powerType', JSON.stringify(res.data))
    }
  })
}
const getEncipherTypeDict = () => {
  getDictByCode('encipherType').then((res: any) => {
    if (res.code === 200) {
      encipherTypeDict.value = res.data
      sessionStorage.setItem('encipherType', JSON.stringify(res.data))
    }
  })
}
const getCommunicationDict = () => {
  getDictByCode('communicationProtocol').then((res: any) => {
    if (res.code === 200) {
      communicationDict.value = res.data
      sessionStorage.setItem('communicationProtocol', JSON.stringify(res.data))
    }
  })
}
const getDict = async () => {
  getDeviceTypeDict()
  getAccessTypeDict()
  getPowerTypeDict()
  getEncipherTypeDict()
  getCommunicationDict()
}

// watch(dateRange, (val) => {
//   if (val) {
//     searchQuery.value.beginTime = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
//     searchQuery.value.endTime = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
//   }
//   else {
//     searchQuery.value.beginTime = ''
//     searchQuery.value.endTime = ''
//   }
// })

onMounted(async () => {
  await getDict()
  searchList()
  window.addEventListener('resize', calcTableHeight)
})
const tableHeight = ref(400)
const calcTableHeight = () => {
  // 顶部高度
  const topHeight = 110
  // app-container的 padding距离
  const appPadding = 20
  // 查询组件的高度
  const searchDiv = document.getElementById('search-div-id')
  const searchHeight = searchDiv ? searchDiv.clientHeight : 0
  // 表格顶部的文字提示高度
  const tableTopHeight = 32 + 10
  // 表格表头
  const tableHeaderHeight = 40
  // 分页器的高度
  const tablePaginationHeight = 40
  // 判断数据长度
  const height = window.innerHeight - topHeight - appPadding - searchHeight - tableTopHeight - tableHeaderHeight - tablePaginationHeight
  if (dataList.value.length * 40 >= height) {
    tableHeight.value = height
  }
  else {
    tableHeight.value = dataList.value.length ? (dataList.value.length + 1) * 40 : 200
  }
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', calcTableHeight)
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.productName" placeholder="产品名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.deviceType" placeholder="请选择设备类型" clearable style="width: 192px;">
          <el-option v-for="dict in deviceTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.model" placeholder="设备型号" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.encipherType" placeholder="请选择加密方式" clearable style="width: 192px;">
          <el-option v-for="dict in encipherTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.accessType" placeholder="请选择接入方式" clearable style="width: 192px;">
          <el-option v-for="dict in accessTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>
      <!-- <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="创建时间（开始）" end-placeholder="创建时间（结束）" />
      </search-item> -->
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="产品管理">
      <!-- 表头区域 -->
      <template #btns-right>
        <!-- <icon-button v-if="proxy.hasPerm(`/basic/product/add`)" icon="icon-add" title="新建" @click="addProduct" /> -->
        <el-button v-if="proxy.hasPerm(`/basic/product/add`)" type="primary" @click="addProduct">新建</el-button>
      </template>

      <!-- 表格区域 -->
      <normal-table :data="dataList" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }" :list-loading="loadingTable"
        @change="changePage" :height="tableHeight">
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm(`/basic/product/edit`)" size="small" type="primary" link
                @click="updateById(row)">
                编辑
              </el-button>

              <el-button v-if="proxy.hasPerm(`/basic/product/del`)" size="small" type="danger" link
                @click="deleteById(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>

    <add-product-dialog ref="refAddProductDialog" @record-saved="productSavedHandler" />
  </app-container>
</template>
