<template>
  <ArtTableFullScreen>
    <div class="authorization-records-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        label-width="85"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        />

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

        <!-- 授权详情对话框 -->
        <ElDialog v-model="detailDialogVisible" title="授权详情" width="700px">
          <ElDescriptions v-if="currentRecord" :column="2" border>
            <ElDescriptionsItem label="企业ID">{{ currentRecord.enterprise_id }}</ElDescriptionsItem>
            <ElDescriptionsItem label="企业名称">{{ currentRecord.enterprise_name }}</ElDescriptionsItem>
            <ElDescriptionsItem label="卡ID">{{ currentRecord.card_id }}</ElDescriptionsItem>
            <ElDescriptionsItem label="ICCID">{{ currentRecord.iccid }}</ElDescriptionsItem>
            <ElDescriptionsItem label="手机号">{{ currentRecord.msisdn || '--' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="授权人ID">{{ currentRecord.authorized_by }}</ElDescriptionsItem>
            <ElDescriptionsItem label="授权人">{{ currentRecord.authorizer_name }}</ElDescriptionsItem>
            <ElDescriptionsItem label="授权人类型">
              <ElTag :type="getAuthorizerTypeTag(currentRecord.authorizer_type)">
                {{ getAuthorizerTypeText(currentRecord.authorizer_type) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="授权时间" :span="2">{{ formatDateTime(currentRecord.authorized_at) }}</ElDescriptionsItem>
            <ElDescriptionsItem label="状态" :span="2">
              <ElTag :type="getStatusTag(currentRecord.status)">
                {{ getStatusText(currentRecord.status) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="备注" :span="2">{{ currentRecord.remark || '--' }}</ElDescriptionsItem>
          </ElDescriptions>
          <template #footer>
            <div class="dialog-footer">
              <ElButton type="primary" @click="detailDialogVisible = false">关闭</ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 修改备注对话框 -->
        <ElDialog v-model="remarkDialogVisible" title="修改备注" width="500px">
          <ElForm ref="remarkFormRef" :model="remarkForm" :rules="remarkRules" label-width="80px">
            <ElFormItem label="备注" prop="remark">
              <ElInput
                v-model="remarkForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注（最多500字）"
                maxlength="500"
                show-word-limit
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="remarkDialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleSubmitRemark" :loading="remarkLoading">
                提交
              </ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { useRouter } from 'vue-router'
  import { AuthorizationService } from '@/api/modules'
  import { ElMessage, 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 ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import type {
    AuthorizationItem,
    AuthorizationStatus,
    AuthorizerType
  } from '@/types/api/authorization'
  import { CommonStatus } from '@/config/constants'

  defineOptions({ name: 'AuthorizationRecords' })

  const router = useRouter()
  const loading = ref(false)
  const detailDialogVisible = ref(false)
  const remarkDialogVisible = ref(false)
  const remarkLoading = ref(false)
  const tableRef = ref()
  const remarkFormRef = ref<FormInstance>()
  const currentRecordId = ref<number>(0)
  const currentRecord = ref<AuthorizationItem | null>(null)

  // 搜索表单初始值
  const initialSearchState = {
    enterprise_id: undefined as number | undefined,
    iccid: '',
    authorizer_type: undefined as AuthorizerType | undefined,
    status: undefined as AuthorizationStatus | undefined,
    dateRange: [] as string[]
  }

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

  // 备注表单
  const remarkForm = reactive({
    remark: ''
  })

  // 备注表单验证规则
  const remarkRules = reactive<FormRules>({
    remark: [{ max: 500, message: '备注不能超过500个字符', trigger: 'blur' }]
  })

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

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: 'ICCID',
      prop: 'iccid',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID'
      }
    },
    {
      label: '授权人类型',
      prop: 'authorizer_type',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '平台', value: 2 },
        { label: '代理', value: 3 }
      ]
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '有效', value: 1 },
        { label: '已回收', value: 0 }
      ]
    },
    {
      label: '授权时间',
      prop: 'dateRange',
      type: 'daterange',
      config: {
        type: 'daterange',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  ]

  // 列配置
  const columnOptions = [
    { label: 'ICCID', prop: 'iccid' },
    { label: '手机号', prop: 'msisdn' },
    { label: '企业名称', prop: 'enterprise_name' },
    { label: '授权人', prop: 'authorizer_name' },
    { label: '授权人类型', prop: 'authorizer_type' },
    { label: '授权时间', prop: 'authorized_at' },
    { label: '状态', prop: 'status' },
    { label: '备注', prop: 'remark' },
    { label: '操作', prop: 'operation' }
  ]

  const authorizationList = ref<AuthorizationItem[]>([])

  // 获取授权人类型标签类型
  const getAuthorizerTypeTag = (type: AuthorizerType) => {
    return type === 2 ? 'primary' : 'success'
  }

  // 获取授权人类型文本
  const getAuthorizerTypeText = (type: AuthorizerType) => {
    return type === 2 ? '平台' : '代理'
  }

  // 获取状态标签类型
  const getStatusTag = (status: AuthorizationStatus) => {
    return status === 1 ? 'success' : 'info'
  }

  // 获取状态文本
  const getStatusText = (status: AuthorizationStatus) => {
    return status === 1 ? '有效' : '已回收'
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'iccid',
      label: 'ICCID',
      minWidth: 200
    },
    {
      prop: 'msisdn',
      label: '手机号',
      width: 130,
      formatter: (row: AuthorizationItem) => row.msisdn || '-'
    },
    {
      prop: 'enterprise_name',
      label: '企业名称',
      minWidth: 150
    },
    {
      prop: 'authorizer_name',
      label: '授权人',
      width: 120
    },
    {
      prop: 'authorizer_type',
      label: '授权人类型',
      width: 110,
      formatter: (row: AuthorizationItem) => {
        return h(ElTag, { type: getAuthorizerTypeTag(row.authorizer_type) }, () =>
          getAuthorizerTypeText(row.authorizer_type)
        )
      }
    },
    {
      prop: 'authorized_at',
      label: '授权时间',
      width: 180,
      formatter: (row: AuthorizationItem) => formatDateTime(row.authorized_at)
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: AuthorizationItem) => {
        return h(ElTag, { type: getStatusTag(row.status) }, () => getStatusText(row.status))
      }
    },
    {
      prop: 'remark',
      label: '备注',
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: (row: AuthorizationItem) => row.remark || '-'
    },
    {
      prop: 'operation',
      label: '操作',
      width: 150,
      fixed: 'right',
      formatter: (row: AuthorizationItem) => {
        return h('div', { style: 'display: flex; gap: 8px;' }, [
          h(ArtButtonTable, {
            text: '详情',
            onClick: () => viewDetail(row)
          }),
          h(ArtButtonTable, {
            type: 'edit',
            onClick: () => showRemarkDialog(row)
          })
        ])
      }
    }
  ])

  onMounted(() => {
    getTableData()
  })

  // 获取授权记录列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        page_size: pagination.pageSize,
        iccid: searchForm.iccid || undefined,
        authorizer_type: searchForm.authorizer_type,
        status: searchForm.status
      }

      // 处理日期范围
      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        params.start_time = searchForm.dateRange[0]
        params.end_time = searchForm.dateRange[1]
      }

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

      const res = await AuthorizationService.getAuthorizations(params)
      if (res.code === 0) {
        authorizationList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      ElMessage.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 viewDetail = (row: AuthorizationItem) => {
    currentRecord.value = row
    detailDialogVisible.value = true
  }

  // 显示修改备注对话框
  const showRemarkDialog = (row: AuthorizationItem) => {
    currentRecordId.value = row.id
    remarkForm.remark = row.remark || ''
    remarkDialogVisible.value = true
  }

  // 提交备注修改
  const handleSubmitRemark = async () => {
    if (!remarkFormRef.value) return

    await remarkFormRef.value.validate(async (valid) => {
      if (valid) {
        remarkLoading.value = true
        try {
          await AuthorizationService.updateAuthorizationRemark(currentRecordId.value, {
            remark: remarkForm.remark
          })
          ElMessage.success('备注修改成功')
          remarkDialogVisible.value = false
          getTableData()
        } catch (error) {
          console.error(error)
          ElMessage.error('备注修改失败')
        } finally {
          remarkLoading.value = false
        }
      }
    })
  }
</script>

<style lang="scss" scoped>
  .authorization-records-page {
    // Authorization records page styles
  }
</style>
