<template>
  <ArtTableFullScreen>
    <div class="enterprise-devices-page" id="table-full-screen">
      <!-- 企业信息卡片 -->
      <ElCard shadow="never" style="margin-bottom: 16px">
        <template #header>
          <div class="card-header">
            <span>企业设备列表</span>
            <ElButton @click="goBack">{{ $t('common.cancel') }}</ElButton>
          </div>
        </template>
        <ElDescriptions :column="3" border v-if="enterpriseInfo">
          <ElDescriptionsItem label="企业名称">{{
            enterpriseInfo.enterprise_name
          }}</ElDescriptionsItem>
          <ElDescriptionsItem label="企业编号">{{
            enterpriseInfo.enterprise_code
          }}</ElDescriptionsItem>
          <ElDescriptionsItem label="联系人">{{ enterpriseInfo.contact_name }}</ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton
              type="primary"
              @click="showAllocateDialog"
              v-permission="'enterprise_device:allocate'"
            >
              授权设备
            </ElButton>
            <ElButton
              type="warning"
              :disabled="selectedDevices.length === 0"
              @click="showRecallDialog"
              v-permission="'enterprise_device:recall'"
            >
              撤销授权
            </ElButton>
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="device_id"
          :loading="loading"
          :data="deviceList"
          :currentPage="pagination.page"
          :pageSize="pagination.pageSize"
          :total="pagination.total"
          :marginTop="10"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
        >
          <template #default>
            <ElTableColumn type="selection" width="55" />
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>

        <!-- 授权设备对话框 -->
        <ElDialog
          v-model="allocateDialogVisible"
          title="授权设备给企业"
          width="75%"
          @close="handleAllocateDialogClose"
        >
          <!-- 搜索过滤条件 -->
          <ArtSearchBar
            v-model:filter="deviceSearchForm"
            :items="deviceSearchFormItems"
            label-width="85"
            :show-expand="false"
            @reset="handleDeviceSearchReset"
            @search="handleDeviceSearch"
          ></ArtSearchBar>

          <!-- 设备列表 -->
          <div class="device-selection-info">
            已选择 {{ selectedAvailableDevices.length }} 台设备
          </div>
          <ArtTable
            ref="availableDevicesTableRef"
            row-key="id"
            :loading="availableDevicesLoading"
            :data="availableDevicesList"
            :currentPage="devicePagination.page"
            :pageSize="devicePagination.pageSize"
            :total="devicePagination.total"
            :marginTop="10"
            @size-change="handleDevicePageSizeChange"
            @current-change="handleDevicePageChange"
            @selection-change="handleAvailableDevicesSelectionChange"
          >
            <template #default>
              <ElTableColumn type="selection" width="55" :selectable="checkDeviceSelectable" />
              <ElTableColumn
                v-for="col in availableDeviceColumns"
                :key="col.prop || col.type"
                v-bind="col"
              />
            </template>
          </ArtTable>

          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="allocateDialogVisible = false">{{ $t('common.cancel') }}</ElButton>
              <ElButton
                type="primary"
                @click="handleAllocate"
                :loading="allocateLoading"
                :disabled="selectedAvailableDevices.length === 0"
              >
                {{ $t('common.confirm') }}
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 撤销授权对话框 -->
        <ElDialog
          v-model="recallDialogVisible"
          title="撤销设备授权"
          width="600px"
          @close="handleRecallDialogClose"
        >
          <ElForm ref="recallFormRef" :model="recallForm" :rules="recallRules">
            <ElFormItem label="已选择设备">
              <div>已选择 {{ selectedDevices.length }} 个设备</div>
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="recallDialogVisible = false">{{ $t('common.cancel') }}</ElButton>
              <ElButton type="primary" @click="handleRecall" :loading="recallLoading">
                {{ $t('common.confirm') }}
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 结果对话框 -->
        <ElDialog v-model="resultDialogVisible" title="操作结果" width="700px">
          <ElDescriptions :column="2" border>
            <ElDescriptionsItem label="成功数量">
              <ElTag type="success">{{ operationResult.success_count }}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="失败数量">
              <ElTag type="danger">{{ operationResult.fail_count }}</ElTag>
            </ElDescriptionsItem>
          </ElDescriptions>

          <!-- 失败项详情 -->
          <div
            v-if="operationResult.failed_items && operationResult.failed_items.length > 0"
            style="margin-top: 20px"
          >
            <ElDivider content-position="left">失败项</ElDivider>
            <ElTable :data="operationResult.failed_items" border max-height="300">
              <ElTableColumn prop="virtual_no" label="设备号" width="180" />
              <ElTableColumn prop="reason" label="失败原因" />
            </ElTable>
          </div>

          <!-- 显示已授权设备 -->
          <div
            v-if="
              operationResult.authorized_devices && operationResult.authorized_devices.length > 0
            "
            style="margin-top: 20px"
          >
            <ElDivider content-position="left">已授权设备</ElDivider>
            <ElTable :data="operationResult.authorized_devices" border max-height="200">
              <ElTableColumn prop="virtual_no" label="设备号" width="180" />
              <ElTableColumn prop="device_id" label="设备ID" width="100" />
              <ElTableColumn label="绑定卡数">
                <template #default="{ row }">
                  {{ row.card_count || 0 }}
                </template>
              </ElTableColumn>
            </ElTable>
          </div>

          <template #footer>
            <div class="dialog-footer">
              <ElButton type="primary" @click="resultDialogVisible = false">{{
                $t('common.confirm')
              }}</ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import { EnterpriseService, DeviceService } from '@/api/modules'
  import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { formatDateTime } from '@/utils/business/format'
  import type {
    EnterpriseDeviceItem,
    AllocateDevicesResponse,
    RecallDevicesResponse,
    AuthorizedDeviceItem,
    FailedDeviceItem
  } from '@/types/api/enterpriseDevice'
  import type { EnterpriseItem } from '@/types/api'
  import type { Device, DeviceStatus } from '@/types/api/device'

  defineOptions({ name: 'EnterpriseDevices' })

  const { t } = useI18n() // 仅保留用于 common.confirm, common.cancel
  const route = useRoute()
  const router = useRouter()
  const loading = ref(false)
  const allocateDialogVisible = ref(false)
  const allocateLoading = ref(false)
  const recallDialogVisible = ref(false)
  const recallLoading = ref(false)
  const resultDialogVisible = ref(false)
  const tableRef = ref()
  const recallFormRef = ref<FormInstance>()
  const selectedDevices = ref<EnterpriseDeviceItem[]>([])
  const enterpriseId = ref<number>(0)
  const enterpriseInfo = ref<EnterpriseItem | null>(null)
  const operationResult = ref<AllocateDevicesResponse | RecallDevicesResponse>({
    success_count: 0,
    fail_count: 0,
    failed_items: null,
    authorized_devices: null
  })

  // 可用设备列表相关
  const availableDevicesTableRef = ref()
  const availableDevicesLoading = ref(false)
  const availableDevicesList = ref<Device[]>([])
  const selectedAvailableDevices = ref<Device[]>([])
  const allocatedDeviceVirtualNos = ref<Set<string>>(new Set())

  // 设备搜索表单初始值
  const initialDeviceSearchState = {
    status: undefined,
    virtual_no: '',
    device_name: '',
    shop_id: undefined
  }

  const deviceSearchForm = reactive({ ...initialDeviceSearchState })
  const devicePagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索表单初始值
  const initialSearchState = {
    virtual_no: ''
  }

  // 搜索表单
  const searchForm = reactive({ ...initialSearchState })

  // 撤销表单
  const recallForm = reactive({})

  // 撤销表单验证规则
  const recallRules = reactive<FormRules>({})

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: '设备号',
      prop: 'virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入设备号'
      }
    }
  ]

  // 设备列表搜索表单配置
  const deviceSearchFormItems: SearchFormItem[] = [
    {
      label: '设备状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '在库', value: 1 },
        { label: '已分销', value: 2 },
        { label: '已激活', value: 3 },
        { label: '已停用', value: 4 }
      ]
    },
    {
      label: '设备号',
      prop: 'virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入设备号'
      }
    },
    {
      label: '设备名称',
      prop: 'device_name',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入设备名称'
      }
    }
  ]

  // 列配置
  const columnOptions = [
    { label: '设备ID', prop: 'device_id' },
    { label: '设备号', prop: 'virtual_no' },
    { label: '设备名称', prop: 'device_name' },
    { label: '设备型号', prop: 'device_model' },
    { label: '绑定卡数量', prop: 'card_count' },
    { label: '授权时间', prop: 'authorized_at' }
  ]

  const deviceList = ref<EnterpriseDeviceItem[]>([])

  // 获取设备状态标签类型
  const getDeviceStatusTag = (status: DeviceStatus) => {
    switch (status) {
      case 1:
        return 'info'
      case 2:
        return 'warning'
      case 3:
        return 'success'
      case 4:
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取设备状态文本
  const getDeviceStatusText = (status: DeviceStatus) => {
    switch (status) {
      case 1:
        return '在库'
      case 2:
        return '已分销'
      case 3:
        return '已激活'
      case 4:
        return '已停用'
      default:
        return '未知'
    }
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'device_id',
      label: '设备ID',
      width: 100
    },
    {
      prop: 'virtual_no',
      label: '设备号',
      minWidth: 150
    },
    {
      prop: 'device_name',
      label: '设备名称',
      minWidth: 150
    },
    {
      prop: 'device_model',
      label: '设备型号',
      width: 120
    },
    {
      prop: 'card_count',
      label: '绑定卡数量',
      width: 100
    },
    {
      prop: 'authorized_at',
      label: '授权时间',
      width: 180,
      formatter: (row: EnterpriseDeviceItem) =>
        row.authorized_at ? formatDateTime(row.authorized_at) : '-'
    }
  ])

  // 可用设备列表列配置
  const availableDeviceColumns = computed(() => [
    {
      prop: 'virtual_no',
      label: '设备号',
      minWidth: 150
    },
    {
      prop: 'device_name',
      label: '设备名称',
      minWidth: 150
    },
    {
      prop: 'device_model',
      label: '设备型号',
      width: 120
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: Device) => {
        return h(ElTag, { type: getDeviceStatusTag(row.status) }, () =>
          getDeviceStatusText(row.status)
        )
      }
    },
    {
      prop: 'shop_name',
      label: '所属店铺',
      width: 150
    },
    {
      prop: 'bound_card_count',
      label: '绑定卡数',
      width: 100
    }
  ])

  onMounted(() => {
    const id = route.query.id
    if (id) {
      enterpriseId.value = Number(id)
      getEnterpriseInfo()
      getTableData()
    } else {
      ElMessage.error('加载设备列表失败')
      goBack()
    }
  })

  // 获取企业信息
  const getEnterpriseInfo = async () => {
    try {
      const res = await EnterpriseService.getEnterprises({
        page: 1,
        page_size: 1,
        id: enterpriseId.value
      })
      if (res.code === 0 && res.data.items && res.data.items.length > 0) {
        enterpriseInfo.value = res.data.items[0]
      }
    } catch (error) {
      console.error('获取企业信息失败:', error)
    }
  }

  // 获取企业设备列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        page_size: pagination.pageSize,
        virtual_no: searchForm.virtual_no || undefined
      }

      // 清理空值
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })

      const res = await EnterpriseService.getEnterpriseDevices(enterpriseId.value, params)
      if (res.code === 0) {
        deviceList.value = res.data.list || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    getTableData()
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  // 刷新表格
  const handleRefresh = () => {
    getTableData()
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getTableData()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.page = newCurrentPage
    getTableData()
  }

  // 表格选择变化
  const handleSelectionChange = (selection: EnterpriseDeviceItem[]) => {
    selectedDevices.value = selection
  }

  // 返回
  const goBack = () => {
    router.back()
  }

  // 获取可用设备列表
  const getAvailableDevicesList = async () => {
    availableDevicesLoading.value = true
    try {
      const params: any = {
        page: devicePagination.page,
        page_size: devicePagination.pageSize,
        ...deviceSearchForm
      }
      // 清理空值
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })

      const res = await DeviceService.getDevices(params)
      if (res.code === 0) {
        availableDevicesList.value = res.data.items || []
        devicePagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
    } finally {
      availableDevicesLoading.value = false
    }
  }

  // 处理设备列表选择变化
  const handleAvailableDevicesSelectionChange = (selection: Device[]) => {
    selectedAvailableDevices.value = selection
  }

  // 设备列表搜索
  const handleDeviceSearch = () => {
    devicePagination.page = 1
    getAvailableDevicesList()
  }

  // 设备列表重置
  const handleDeviceSearchReset = () => {
    Object.assign(deviceSearchForm, { ...initialDeviceSearchState })
    devicePagination.page = 1
    getAvailableDevicesList()
  }

  // 设备列表分页大小变化
  const handleDevicePageSizeChange = (newPageSize: number) => {
    devicePagination.pageSize = newPageSize
    getAvailableDevicesList()
  }

  // 设备列表页码变化
  const handleDevicePageChange = (newPage: number) => {
    devicePagination.page = newPage
    getAvailableDevicesList()
  }

  // 检查设备是否可选（已授权的设备不可选）
  const checkDeviceSelectable = (row: Device) => {
    return !allocatedDeviceVirtualNos.value.has(row.virtual_no)
  }

  // 显示授权对话框
  const showAllocateDialog = () => {
    allocateDialogVisible.value = true
    selectedAvailableDevices.value = []
    // 收集已授权的设备的 virtual_no
    allocatedDeviceVirtualNos.value = new Set(deviceList.value.map((device) => device.virtual_no))
    // 重置搜索条件
    Object.assign(deviceSearchForm, { ...initialDeviceSearchState })
    devicePagination.page = 1
    devicePagination.pageSize = 20
    // 加载可用设备列表
    getAvailableDevicesList()
  }

  // 执行授权
  const handleAllocate = async () => {
    if (selectedAvailableDevices.value.length === 0) {
      ElMessage.warning('请选择要授权的设备')
      return
    }

    allocateLoading.value = true
    try {
      const device_nos = selectedAvailableDevices.value.map((device) => device.virtual_no)
      const res = await EnterpriseService.allocateDevices(enterpriseId.value, {
        device_nos
      })

      if (res.code === 0) {
        operationResult.value = res.data
        allocateDialogVisible.value = false
        resultDialogVisible.value = true

        // 显示成功消息
        if (res.data.success_count > 0 && res.data.fail_count === 0) {
          ElMessage.success('设备授权成功')
        } else if (res.data.success_count > 0 && res.data.fail_count > 0) {
          ElMessage.warning(
            `部分设备授权成功：成功 ${res.data.success_count} 个，失败 ${res.data.fail_count} 个`
          )
        } else {
          ElMessage.error('设备授权失败')
        }

        getTableData()
      }
    } catch (error) {
      console.error(error)
    } finally {
      allocateLoading.value = false
    }
  }

  // 关闭授权对话框
  const handleAllocateDialogClose = () => {
    selectedAvailableDevices.value = []
  }

  // 显示撤销授权对话框
  const showRecallDialog = () => {
    if (selectedDevices.value.length === 0) {
      ElMessage.warning('请先选择要撤销的设备')
      return
    }
    recallDialogVisible.value = true
    if (recallFormRef.value) {
      recallFormRef.value.resetFields()
    }
  }

  // 执行撤销授权
  const handleRecall = async () => {
    if (!recallFormRef.value) return

    ElMessageBox.confirm(
      `确定要撤销选中的 ${selectedDevices.value.length} 个设备的授权吗？`,
      '撤销授权确认',
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
      .then(async () => {
        recallLoading.value = true
        try {
          const res = await EnterpriseService.recallDevices(enterpriseId.value, {
            device_nos: selectedDevices.value.map((device) => device.virtual_no)
          })

          if (res.code === 0) {
            operationResult.value = res.data
            recallDialogVisible.value = false
            resultDialogVisible.value = true

            // 显示成功消息
            if (res.data.success_count > 0 && res.data.fail_count === 0) {
              ElMessage.success('撤销授权成功')
            } else if (res.data.success_count > 0 && res.data.fail_count > 0) {
              ElMessage.warning(
                `部分设备撤销成功：成功 ${res.data.success_count} 个，失败 ${res.data.fail_count} 个`
              )
            } else {
              ElMessage.error('撤销授权失败')
            }

            // 清空选择
            if (tableRef.value) {
              tableRef.value.clearSelection()
            }
            selectedDevices.value = []
            getTableData()
          }
        } catch (error) {
          console.error(error)
          console.logr('撤销授权失败')
        } finally {
          recallLoading.value = false
        }
      })
      .catch(() => {})
  }

  // 关闭撤销授权对话框
  const handleRecallDialogClose = () => {
    if (recallFormRef.value) {
      recallFormRef.value.resetFields()
    }
  }
</script>

<style lang="scss" scoped>
  .enterprise-devices-page {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .device-selection-info {
      margin-top: 10px;
      margin-bottom: 12px;
      font-size: 14px;
      color: var(--el-color-info);
    }
  }
</style>
