<script setup lang="ts">
import { IotDeviceApi } from '@/api/pms/device'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, realValue } from '@/utils/dict'
import { WarningFilled } from '@element-plus/icons-vue'
import { DeviceList, DeviceQuery } from './types'

const { t } = useI18n()

const emits = defineEmits<{
  choose: [value: DeviceList[]]
  close: []
}>()

const visible = ref(false)

const open = () => {
  visible.value = true
  query.value = initQuery()
  selectedRows.value = []
  tableRef.value?.elTableRef.clearSelection()
  getList()
}

defineExpose({ open })

const initQuery = (): DeviceQuery => ({
  pageNo: 1,
  pageSize: 10
})

const loading = ref(false)
const query = ref(initQuery())
const total = ref(0)

const list = ref<DeviceList[]>([])
const selectedRows = ref<DeviceList[]>([])
const tableRef = ref()

const getList = async () => {
  loading.value = true
  try {
    const res = await IotDeviceApi.getIotDevicePage(query.value)
    total.value = res.total
    list.value = res.list
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val: number) => {
  query.value.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  query.value.pageNo = val
  getList()
}

const handleQuery = () => {
  query.value.pageNo = 1
  getList()
}

const reset = () => {
  query.value = initQuery()
  handleQuery()
}

const handleClose = () => {
  tableRef.value?.elTableRef.clearSelection()
  selectedRows.value = []
  emits('close')
}

const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个设备')
    return
  }

  emits('choose', selectedRows.value)
  visible.value = false
}

const handleSelectionChange = (val: DeviceList[]) => {
  selectedRows.value = val
}

const handleRowClick = (row: DeviceList) => {
  if (!row.hasSetMaintenanceBom) {
    ElMessage.warning({
      message: '请选择有保养项的设备',
      grouping: true
    })
    return
  }

  tableRef.value?.elTableRef.toggleRowSelection(row)
}

const { ZmTable, ZmTableColumn } = useTableComponents<DeviceList>()
</script>

<template>
  <Dialog
    v-model="visible"
    :title="t('deviceList.selectDevice')"
    :style="{ width: '1200px' }"
    :body-style="{ height: '100%' }"
    :close-on-click-modal="false"
    @close="handleClose">
    <el-form
      :model="query"
      class="flex border-1 border-solid border-gray-300 p-4 rounded"
      size="default"
      label-width="86px">
      <el-form-item class="mb-0!" :label="t('deviceList.deviceName')" prop="deviceName">
        <el-input
          v-model="query.deviceName"
          @keyup.enter="handleQuery"
          :placeholder="t('deviceList.nameHolder')"
          clearable
          class="!w-200px" />
      </el-form-item>
      <el-form-item class="mb-0!" :label="t('deviceList.deviceCode')" prop="deviceCode">
        <el-input
          v-model="query.deviceCode"
          @keyup.enter="handleQuery"
          :placeholder="t('deviceList.codeHolder')"
          clearable
          class="!w-200px" />
      </el-form-item>
      <el-form-item class="mb-0!">
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('deviceList.search') }}
        </el-button>
        <el-button @click="reset">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('deviceList.reset') }}
        </el-button>
        <el-button @click="handleConfirm" type="success">
          <Icon icon="ep:check" class="mr-5px" /> {{ t('workOrderMaterial.confirm') }}
        </el-button>
      </el-form-item>
    </el-form>
    <section class="mt-4 p-4 pb-1 border-1 border-solid border-gray-300 rounded">
      <ZmTable
        ref="tableRef"
        :data="list"
        :loading="loading"
        :height="420"
        row-key="id"
        :column-max-width="420"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange">
        <ZmTableColumn
          column-key="selection"
          type="selection"
          width="55"
          reserve-selection
          :selectable="(row) => row.hasSetMaintenanceBom" />
        <ZmTableColumn :label="t('chooseMaintain.deviceCode')" prop="deviceCode" />
        <ZmTableColumn :label="t('deviceList.deviceName')" prop="deviceName" />
        <ZmTableColumn :label="t('iotDevice.dept')" prop="deptName" />
        <ZmTableColumn
          :label="t('iotDevice.status')"
          prop="deviceStatus"
          :real-value="(row) => realValue(DICT_TYPE.PMS_DEVICE_STATUS, row.deviceStatus ?? '')">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="row.deviceStatus ?? ''" />
          </template>
        </ZmTableColumn>
        <ZmTableColumn
          :label="t('deviceInfo.deviceBOM')"
          prop="hasSetMaintenanceBom"
          :real-value="
            (row) =>
              row.hasSetMaintenanceBom ? t('mainPlan.haveMaintItems') : t('mainPlan.noMaintItems')
          ">
          <template #header>
            {{ t('deviceInfo.deviceBOM') }}
            <el-tooltip effect="dark" content="请选择有保养项的设备" placement="top">
              <el-icon :size="12" color="#e6a23c" style="margin-left: 3px; cursor: pointer">
                <WarningFilled />
              </el-icon>
            </el-tooltip>
          </template>
          <template #default="{ row }">
            <el-tag :type="row.hasSetMaintenanceBom ? 'success' : 'danger'">
              {{
                row.hasSetMaintenanceBom ? t('mainPlan.haveMaintItems') : t('mainPlan.noMaintItems')
              }}
            </el-tag>
          </template>
        </ZmTableColumn>
      </ZmTable>
      <div class="h-8 mt-2 flex items-center justify-end">
        <el-pagination
          v-show="total > 0"
          :current-page="query.pageNo"
          :page-size="query.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </section>
  </Dialog>
</template>

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