<template>
  <div class="page-container">
    <ProTable ref="tableRef" :columns="columns" :request="loadData" :toolbar="{ title: '资产申请' }" :custom-row="(record: any) => ({ onClick: () => showChangeLog(record), style: { cursor: 'pointer' } })">
      <template #toolbar-actions>
        <a-button v-permission="'biz:request:add'" type="primary" @click="handleAdd"><PlusOutlined /> 新增申请</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 'pending' ? 'orange' : record.status === 'approved' ? 'green' : record.status === 'rejected' ? 'red' : 'default'">{{ record.status === 'pending' ? '待审批' : record.status === 'approved' ? '已批准' : record.status === 'rejected' ? '已拒绝' : '已取消' }}</a-tag>
        </template>
        <template v-if="column.key === 'operations'">
          <a-space :size="4" @click.stop>
            <a-button v-permission="'biz:request:edit'" type="link" size="small" @click.stop="handleEdit(record)"><EditOutlined /> 编辑</a-button>
            <a-popconfirm v-permission="'biz:request:delete'" title="确认删除？" @confirm="handleDelete(record.id)">
              <a-button type="link" size="small" danger @click.stop><DeleteOutlined /> 删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ProTable>

    <a-modal v-model:open="visible" :title="isEdit ? '编辑申请' : '新增申请'" @ok="handleSubmit" width="600px">
      <a-form :model="form" :label-col="{ span: 6 }">
        <a-form-item label="申请单号"><a-input v-model:value="form.request_no" disabled /></a-form-item>
        <a-form-item label="申请人">
          <a-select v-model:value="form.user_id" show-search placeholder="请选择申请人" option-filter-prop="label" :options="userOptions" allow-clear />
        </a-form-item>
        <a-form-item label="资产类型"><a-input v-model:value="form.item_type" /></a-form-item>
        <a-form-item label="分类">
          <a-select v-model:value="form.category_id" show-search placeholder="请选择分类" option-filter-prop="label" :options="categoryOptions" allow-clear />
        </a-form-item>
        <a-form-item label="数量"><a-input-number v-model:value="form.quantity" :min="1" style="width:100%" /></a-form-item>
        <a-form-item label="申请原因"><a-textarea v-model:value="form.reason" :rows="2" /></a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="form.status" :options="requestStatusOptions" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="logVisible" title="变更记录" width="800px" :footer="null">
      <a-table :columns="logColumns" :data-source="logData" :pagination="false" size="small" row-key="id">
        <template #bodyCell="{ column, record: row }">
          <template v-if="column.key === 'change_type'">
            <a-tag :color="row.change_type === 'create' ? 'green' : row.change_type === 'delete' ? 'red' : 'blue'">{{ row.change_type === 'create' ? '新增' : row.change_type === 'delete' ? '删除' : '修改' }}</a-tag>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@antdv-next/icons";
import { message } from "antdv-next";
import { ref } from "vue";
import { requestApi, changeRecordApi, getCategoryList, getUserList } from "@/api/asset";
import ProTable from "@/components/Pro/ProTable/index.vue";
import type { ProTableColumn } from "@/types/pro";

const tableRef = ref();
const visible = ref(false); const isEdit = ref(false);
const form = ref<Record<string, unknown>>({});

const userOptions = ref<{ label: string; value: string }[]>([]);
const categoryOptions = ref<{ label: string; value: string }[]>([]);
const requestStatusOptions = [
  { label: '待审批', value: 'pending' },
  { label: '已批准', value: 'approved' },
  { label: '已拒绝', value: 'rejected' },
  { label: '已取消', value: 'cancelled' },
];

const loadOptions = async () => {
  try {
    const [catRes, userRes]: any[] = await Promise.all([
      getCategoryList(),
      getUserList(),
    ]);
    const extractData = (res: any) => (res.data || res) as any[];
    categoryOptions.value = (extractData(catRes) || []).map((c: any) => ({ label: c.name + ' [' + c.code + ']', value: c.id }));
    userOptions.value = ((userRes.data || userRes)?.list || []).map((u: any) => ({ label: u.nick_name || u.user_name, value: u.id }));
  } catch { /* ignore */ }
};

const logVisible = ref(false);
const logData = ref<Record<string, unknown>[]>([]);
const logColumns = [
  { title: "时间", dataIndex: "create_time", key: "create_time", width: 170 },
  { title: "变更类型", dataIndex: "change_type", key: "change_type", width: 80 },
  { title: "变更字段", dataIndex: "field_name", key: "field_name", width: 120 },
  { title: "旧值", dataIndex: "old_value", key: "old_value", ellipsis: true },
  { title: "新值", dataIndex: "new_value", key: "new_value", ellipsis: true },
  { title: "操作人", dataIndex: "operator_name", key: "operator_name", width: 100 },
];

const columns: ProTableColumn[] = [
  { title: "申请单号", dataIndex: "request_no", key: "request_no", search: true, searchType: "input" },
  { title: "申请人", dataIndex: "user_name", key: "user_name" },
  { title: "资产类型", dataIndex: "item_type", key: "item_type" },
  { title: "分类", dataIndex: "category_name", key: "category_name" },
  { title: "数量", dataIndex: "quantity", key: "quantity" },
  { title: "状态", dataIndex: "status", key: "status" },
  { title: "审批人", dataIndex: "approver_name", key: "approver_name" },
  { title: "操作", dataIndex: "operations", key: "operations", width: 200, fixed: "right" as const },
];

const loadData = async (params: Record<string, unknown>) => {
  try {
    const res: any = await requestApi.page({ page: params.current, pageSize: params.pageSize, keyword: params.keyword });
    const pageData = res.data || res;
    return { data: pageData.list || [], total: pageData.total || 0, success: true };
  } catch { return { data: [], total: 0, success: false }; }
};

const showChangeLog = async (record: Record<string, unknown>) => {
  try {
    const res: any = await changeRecordApi.page({ asset_type: "asset_request", asset_id: record.id, page: 1, pageSize: 200 });
    logData.value = (res.data || res).list || [];
    logVisible.value = true;
  } catch { message.error("获取变更记录失败"); }
};

const handleAdd = async () => { isEdit.value = false; form.value = { quantity: 1, status: 'pending' }; await loadOptions(); visible.value = true; };
const handleEdit = async (r: Record<string, unknown>) => { isEdit.value = true; form.value = { ...r }; await loadOptions(); visible.value = true; };
const handleDelete = async (id: string) => {
  await requestApi.del(id);
  message.success("删除成功");
  tableRef.value?.reload();
};
const handleSubmit = async () => {
  await requestApi.save(form.value);
  message.success(isEdit.value ? "更新成功" : "创建成功");
  visible.value = false;
  tableRef.value?.reload();
};
</script>
