<template>
  <div style="width: 100%;height: 100%">
    <a-card style="margin-bottom: 5px" title="激活记录">
      <a-form ref="searchFormRef" :model="searchForm" layout="inline">
        <a-form-item label="mac地址" name="macAddress">
          <a-input
            v-model:value="searchForm.macAddress"
            allow-clear
            autocomplete="off"
            placeholder="请输入mac地址"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="激活模块" name="modules">
          <a-select
            v-model:value="searchForm.modules"
            :max-tag-count="1"
            allow-clear
            mode="multiple"
            placeholder="全部"
            style="width: 200px"
          >
            <a-select-option value="simulate">模拟式模块</a-select-option>
            <a-select-option value="digital">数字式模块</a-select-option>
            <a-select-option value="contrast">比对式模块</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="query">
            <template #icon>
              <search-outlined/>
            </template>
            查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetForm">
            <template #icon>
              <reload-outlined/>
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card>
      <a-space style="margin-bottom: 10px;" wrap>
        <a-button type="primary" @click="visible = true">
          <template #icon>
            <file-protect-outlined/>
          </template>
          设备激活
        </a-button>
        <a-button @click="backupData">
          <template #icon>
            <download-outlined/>
          </template>
          备份数据
        </a-button>
        <a-button @click="confirmImportBackup">
          <template #icon>
            <upload-outlined/>
          </template>
          导入备份
        </a-button>
        <a-button danger @click="confirmClearData">
          <template #icon>
            <delete-outlined/>
          </template>
          清空数据
        </a-button>
      </a-space>
      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="pagination"
        :rowKey="(record: any) => record.id"
        bordered
        size="small"
      >
        <template #emptyText>
          <a-empty description="暂无记录"/>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'module'">
            <a-tag color="green" v-for="m in record.module.split(',')" :key="m">
              {{ m === 'simulate' ? '模拟式模块' : m === 'digital' ? '数字式模块' : '比对式模块' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="copyToClipboard(record.activationCode)">
                <template #icon>
                  <copy-outlined />
                </template>
                复制激活码
              </a-button>
              <a-popconfirm
                title="确认删除这条记录吗？"
                ok-text="删除"
                cancel-text="取消"
                @confirm="removeRecord(record.id)"
              >
                <a-button danger size="small">
                  <template #icon>
                    <delete-outlined />
                  </template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>

  <a-modal
    v-model:visible="visible"
    :keyboard="false"
    :mask-closable="false"
    centered
    destroy-on-close
    width="940px"
    wrapClassName="apple-activation-modal"
  >
    <template #title>
      <file-protect-outlined/>
      设备激活
    </template>
    <ActiveForm ref="activateFormRef"></ActiveForm>
    <template #footer>
      <a-button type="primary" @click="save">
        保存
      </a-button>
      <a-button @click="visible = false">关闭</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { FormInstance, Modal, message } from "ant-design-vue";
import { onMounted, ref } from "vue";
import ActiveForm from "@/views/activate/ActiveForm.vue";
import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api";

const searchFormRef = ref<FormInstance>();
const activateFormRef = ref();
const searchForm = ref({
  macAddress: '',
  modules: [],
})
const loading = ref(false)
const visible = ref(false)
const dataSource = ref<any[]>([])
const pagination = ref({
  total: 0,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`
})
const columns = [
  {
    title: '申请方',
    dataIndex: 'applicant',
    key: 'applicant',
    align: 'center',
    width: 120,
  },
  {
    title: 'mac地址',
    dataIndex: 'macAddress',
    key: 'macAddress',
    align: 'center',
    width: 150,
  },
  {
    title: '申请码',
    dataIndex: 'applicationCode',
    key: 'applicationCode',
    align: 'center',
    ellipsis: true,
    width: 120,
  },
  {
    title: '激活模块',
    dataIndex: 'module',
    key: 'module',
    align: 'center',
    width: 220,
  },
  {
    title: '激活码',
    dataIndex: 'activationCode',
    key: 'activationCode',
    align: 'center',
    ellipsis: true,
    width: 120,
  },
  {
    title: '生成时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 150,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 220,
  },
]

const resetForm = () => {
  searchFormRef.value?.resetFields();
  query()
}

onMounted(() => {
  resetForm()
})

const query = () => {
  loading.value = true
  const params: any = {
    macAddress: searchForm.value.macAddress,
    modules: [...searchForm.value.modules],
  }
  setTimeout(() => {
    ipc.invoke(ipcApiRoute.activateRecord.list, params).then((res: any[]) => {
      dataSource.value = res
      pagination.value.total = dataSource.value.length
      pagination.value.current = 1
      loading.value = false
    }).catch((err: any) => {
      console.error(err)
      loading.value = false
    })
  }, 300)
}

const save = () => {
  const data = activateFormRef.value.getData()
  if (!data) {
    message.warning('请先生成激活码')
    return
  }
  ipc.invoke(ipcApiRoute.activateRecord.save, data).then(() => {
    message.success('保存成功')
    visible.value = false
    resetForm()
  }).catch((err: any) => {
    console.error(err)
    message.error('保存失败')
  })
}

const removeRecord = (id: number) => {
  ipc.invoke(ipcApiRoute.activateRecord.removeById, { id }).then(() => {
    message.success('删除成功')
    query()
  }).catch((err: any) => {
    console.error(err)
    message.error('删除失败')
  })
}

const confirmClearData = () => {
  Modal.confirm({
    title: '确认清空全部数据吗？',
    content: '清空后当前本地激活记录将被删除，请先确认是否需要备份。',
    okText: '清空',
    cancelText: '取消',
    okButtonProps: {
      danger: true
    },
    onOk: () => clearData()
  })
}

const clearData = () => {
  ipc.invoke(ipcApiRoute.activateRecord.clear).then(() => {
    message.success('已清空本地数据')
    query()
  }).catch((err: any) => {
    console.error(err)
    message.error('清空失败')
  })
}

const backupData = () => {
  ipc.invoke(ipcApiRoute.activateRecord.backup).then((res: any) => {
    if (res?.canceled) {
      return
    }
    message.success(`备份成功，共导出 ${res.count} 条记录`)
  }).catch((err: any) => {
    console.error(err)
    message.error('备份失败')
  })
}

const confirmImportBackup = () => {
  Modal.confirm({
    title: '确认导入备份吗？',
    content: '导入备份会先清空当前本地数据，再恢复备份内容。',
    okText: '导入',
    cancelText: '取消',
    okButtonProps: {
      danger: true
    },
    onOk: () => importBackup()
  })
}

const importBackup = () => {
  ipc.invoke(ipcApiRoute.activateRecord.importBackup).then((res: any) => {
    if (res?.canceled) {
      return
    }
    message.success(`导入成功，共恢复 ${res.count} 条记录`)
    query()
  }).catch((err: any) => {
    console.error(err)
    message.error('导入失败，请检查备份文件格式')
  })
}

const copyToClipboard = (text: string) => {
  if (!text) {
    message.warning('没有内容可复制')
    return
  }

  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  })
}
</script>
<style lang="less" scoped>
:deep(.apple-activation-modal .ant-modal-content) {
  border-radius: 30px;
  overflow: hidden;
  border: 1px solid rgba(15, 23, 42, 0.08);
  box-shadow: 0 28px 60px rgba(15, 23, 42, 0.22);
  background:
    linear-gradient(180deg, rgba(250, 250, 252, 0.98), rgba(243, 245, 247, 0.98));
}

:deep(.apple-activation-modal .ant-modal-header) {
  padding: 18px 24px 14px;
  background: transparent;
  border-bottom: 1px solid rgba(15, 23, 42, 0.06);
}

:deep(.apple-activation-modal .ant-modal-title) {
  font-size: 18px;
  font-weight: 650;
  color: #111827;
}

:deep(.apple-activation-modal .ant-modal-body) {
  padding: 12px 14px 8px;
  background: transparent;
  max-height: 76vh;
  overflow-y: auto;
}

:deep(.apple-activation-modal .ant-modal-footer) {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 12px 20px 18px;
  border-top: 1px solid rgba(15, 23, 42, 0.06);
  background: transparent;
}

:deep(.apple-activation-modal .ant-btn) {
  min-width: 88px;
  height: 38px;
  border-radius: 12px;
}

:deep(.apple-activation-modal .ant-btn-primary) {
  border: none;
  background: linear-gradient(180deg, #0a84ff, #0071e3);
  box-shadow: 0 10px 24px rgba(0, 113, 227, 0.22);
}
</style>
