<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>{{ $t('enterpriseDevices.title') }}</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"
        @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">{{
              $t('enterpriseDevices.buttons.allocateDevices')
            }}</ElButton>
            <ElButton
              type="warning"
              :disabled="selectedDevices.length === 0"
              @click="showRecallDialog"
            >
              {{ $t('enterpriseDevices.buttons.recallDevices') }}
            </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="$t('enterpriseDevices.dialog.allocateTitle')"
          width="700px"
          @close="handleAllocateDialogClose"
        >
          <ElForm
            ref="allocateFormRef"
            :model="allocateForm"
            :rules="allocateRules"
            label-width="120px"
          >
            <ElFormItem :label="$t('enterpriseDevices.form.deviceNos')" prop="virtual_nos">
              <ElInput
                v-model="deviceNosText"
                type="textarea"
                :rows="6"
                :placeholder="$t('enterpriseDevices.form.deviceNosPlaceholder')"
                @input="handleDeviceNosChange"
              />
              <div style="margin-top: 4px; font-size: 12px; color: var(--el-color-info)">
                {{
                  $t('enterpriseDevices.form.selectedCount', {
                    count: allocateForm.virtual_nos?.length || 0
                  })
                }}
              </div>
            </ElFormItem>
            <ElFormItem :label="$t('enterpriseDevices.form.remark')">
              <ElInput
                v-model="allocateForm.remark"
                type="textarea"
                :rows="3"
                :placeholder="$t('enterpriseDevices.form.remarkPlaceholder')"
              />
            </ElFormItem>
          </ElForm>

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

        <!-- 撤销授权对话框 -->
        <ElDialog
          v-model="recallDialogVisible"
          :title="$t('enterpriseDevices.dialog.recallTitle')"
          width="600px"
          @close="handleRecallDialogClose"
        >
          <ElForm ref="recallFormRef" :model="recallForm" :rules="recallRules">
            <ElFormItem :label="$t('enterpriseDevices.form.selectedDevices')">
              <div>
                {{
                  $t('enterpriseDevices.form.selectedCount', {
                    count: 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="$t('enterpriseDevices.dialog.resultTitle')"
          width="700px"
        >
          <ElDescriptions :column="2" border>
            <ElDescriptionsItem :label="$t('enterpriseDevices.result.successCount')">
              <ElTag type="success">{{ operationResult.success_count }}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('enterpriseDevices.result.failCount')">
              <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">{{
              $t('enterpriseDevices.result.failedItems')
            }}</ElDivider>
            <ElTable :data="operationResult.failed_items" border max-height="300">
              <ElTableColumn
                prop="virtual_no"
                :label="$t('enterpriseDevices.result.deviceNo')"
                width="180"
              />
              <ElTableColumn prop="reason" :label="$t('enterpriseDevices.result.reason')" />
            </ElTable>
          </div>

          <!-- 显示已授权设备 -->
          <div
            v-if="
              operationResult.authorized_devices && operationResult.authorized_devices.length > 0
            "
            style="margin-top: 20px"
          >
            <ElDivider content-position="left">{{
              $t('enterpriseDevices.result.authorizedDevices')
            }}</ElDivider>
            <ElTable :data="operationResult.authorized_devices" border max-height="200">
              <ElTableColumn
                prop="virtual_no"
                :label="$t('enterpriseDevices.result.deviceNo')"
                width="180"
              />
              <ElTableColumn
                prop="device_id"
                :label="$t('enterpriseDevices.result.deviceId')"
                width="100"
              />
              <ElTableColumn :label="$t('enterpriseDevices.result.cardCount')">
                <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 } 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'

  defineOptions({ name: 'EnterpriseDevices' })

  const { t } = useI18n()
  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 allocateFormRef = ref<FormInstance>()
  const recallFormRef = ref<FormInstance>()
  const selectedDevices = ref<EnterpriseDeviceItem[]>([])
  const enterpriseId = ref<number>(0)
  const enterpriseInfo = ref<EnterpriseItem | null>(null)
  const deviceNosText = ref('')
  const operationResult = ref<AllocateDevicesResponse | RecallDevicesResponse>({
    success_count: 0,
    fail_count: 0,
    failed_items: null,
    authorized_devices: null
  })

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

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

  // 授权表单
  const allocateForm = reactive({
    virtual_nos: [] as string[],
    remark: ''
  })

  // 授权表单验证规则
  const allocateRules = reactive<FormRules>({
    virtual_nos: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error(t('enterpriseDevices.validation.deviceNosRequired')))
          } else if (value.length > 100) {
            callback(new Error(t('enterpriseDevices.validation.deviceNosMaxLength')))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  })

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

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

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

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: t('enterpriseDevices.searchForm.deviceNo'),
      prop: 'virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: t('enterpriseDevices.searchForm.deviceNoPlaceholder')
      }
    }
  ]

  // 列配置
  const columnOptions = [
    { label: t('enterpriseDevices.table.deviceId'), prop: 'device_id' },
    { label: t('enterpriseDevices.table.deviceNo'), prop: 'virtual_no' },
    { label: t('enterpriseDevices.table.deviceName'), prop: 'device_name' },
    { label: t('enterpriseDevices.table.deviceModel'), prop: 'device_model' },
    { label: t('enterpriseDevices.table.cardCount'), prop: 'card_count' },
    { label: t('enterpriseDevices.table.authorizedAt'), prop: 'authorized_at' }
  ]

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

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'device_id',
      label: t('enterpriseDevices.table.deviceId'),
      width: 100
    },
    {
      prop: 'virtual_no',
      label: t('enterpriseDevices.table.deviceNo'),
      minWidth: 150
    },
    {
      prop: 'device_name',
      label: t('enterpriseDevices.table.deviceName'),
      minWidth: 150
    },
    {
      prop: 'device_model',
      label: t('enterpriseDevices.table.deviceModel'),
      width: 120
    },
    {
      prop: 'card_count',
      label: t('enterpriseDevices.table.cardCount'),
      width: 100
    },
    {
      prop: 'authorized_at',
      label: t('enterpriseDevices.table.authorizedAt'),
      width: 180,
      formatter: (row: EnterpriseDeviceItem) =>
        row.authorized_at ? formatDateTime(row.authorized_at) : '-'
    }
  ])

  onMounted(() => {
    const id = route.query.id
    if (id) {
      enterpriseId.value = Number(id)
      getEnterpriseInfo()
      getTableData()
    } else {
      ElMessage.error(t('enterpriseDevices.messages.loadFailed'))
      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)
      ElMessage.error(t('enterpriseDevices.messages.loadFailed'))
    } 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 showAllocateDialog = () => {
    allocateDialogVisible.value = true
    deviceNosText.value = ''
    allocateForm.virtual_nos = []
    allocateForm.remark = ''
    if (allocateFormRef.value) {
      allocateFormRef.value.resetFields()
    }
  }

  // 处理设备号输入变化
  const handleDeviceNosChange = () => {
    // 解析输入的设备号，支持逗号、空格、换行分隔
    const deviceNos = deviceNosText.value
      .split(/[,\s\n]+/)
      .map((no) => no.trim())
      .filter((no) => no.length > 0)
    allocateForm.virtual_nos = deviceNos
  }

  // 执行授权
  const handleAllocate = async () => {
    if (!allocateFormRef.value) return

    await allocateFormRef.value.validate(async (valid) => {
      if (valid) {
        if (allocateForm.virtual_nos.length === 0) {
          ElMessage.warning(t('enterpriseDevices.messages.deviceNosEmpty'))
          return
        }

        if (allocateForm.virtual_nos.length > 100) {
          ElMessage.warning(t('enterpriseDevices.messages.deviceNosMaxLimit'))
          return
        }

        allocateLoading.value = true
        try {
          const res = await EnterpriseService.allocateDevices(enterpriseId.value, {
            virtual_nos: allocateForm.virtual_nos,
            remark: allocateForm.remark || undefined
          })

          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(t('enterpriseDevices.messages.allocateSuccess'))
            } else if (res.data.success_count > 0 && res.data.fail_count > 0) {
              ElMessage.warning(
                t('enterpriseDevices.messages.allocatePartialSuccess', {
                  success: res.data.success_count,
                  fail: res.data.fail_count
                })
              )
            } else {
              ElMessage.error(t('enterpriseDevices.messages.allocateFailed'))
            }

            getTableData()
          }
        } catch (error) {
          console.error(error)
          ElMessage.error(t('enterpriseDevices.messages.allocateFailed'))
        } finally {
          allocateLoading.value = false
        }
      }
    })
  }

  // 关闭授权对话框
  const handleAllocateDialogClose = () => {
    if (allocateFormRef.value) {
      allocateFormRef.value.resetFields()
    }
  }

  // 显示撤销授权对话框
  const showRecallDialog = () => {
    if (selectedDevices.value.length === 0) {
      ElMessage.warning(t('enterpriseDevices.messages.noSelection'))
      return
    }
    recallDialogVisible.value = true
    if (recallFormRef.value) {
      recallFormRef.value.resetFields()
    }
  }

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

    ElMessageBox.confirm(
      t('enterpriseDevices.messages.recallConfirmText', {
        count: selectedDevices.value.length
      }),
      t('enterpriseDevices.messages.recallConfirm'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
      .then(async () => {
        recallLoading.value = true
        try {
          const res = await EnterpriseService.recallDevices(enterpriseId.value, {
            virtual_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(t('enterpriseDevices.messages.recallSuccess'))
            } else if (res.data.success_count > 0 && res.data.fail_count > 0) {
              ElMessage.warning(
                t('enterpriseDevices.messages.recallPartialSuccess', {
                  success: res.data.success_count,
                  fail: res.data.fail_count
                })
              )
            } else {
              ElMessage.error(t('enterpriseDevices.messages.recallFailed'))
            }

            // 清空选择
            if (tableRef.value) {
              tableRef.value.clearSelection()
            }
            selectedDevices.value = []
            getTableData()
          }
        } catch (error) {
          console.error(error)
          ElMessage.error(t('enterpriseDevices.messages.recallFailed'))
        } 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;
    }
  }
</style>
