<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="'asset:offering:add'" type="primary" @click="handleAdd"><PlusOutlined /> 新增服务</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'assigned_user_name'">
          <a-tag v-if="record.assigned_user_name" color="blue">{{ record.assigned_user_name }}</a-tag>
          <span v-else style="color:#999">未分配</span>
        </template>
        <template v-if="column.key === 'offering_status'">
          <a-tag :color="record.offering_status === 'active' ? 'green' : 'default'">{{ record.offering_status === 'active' ? '生效中' : record.offering_status }}</a-tag>
        </template>
        <template v-if="column.key === 'operations'">
          <a-space :size="4" @click.stop>
            <a-button v-permission="'asset:offering:edit'" type="link" size="small" @click.stop="handleEdit(record)"><EditOutlined /> 编辑</a-button>
            <a-popconfirm v-permission="'asset:offering: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="700px">
      <a-form :model="form" :label-col="{ span: 6 }">
        <a-row :gutter="16">
          <a-col :span="12"><a-form-item label="服务名称" required><a-input v-model:value="form.name" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="服务编号"><a-input v-model:value="form.service_number" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="责任人">
            <a-select v-model:value="form.assigned_to" show-search placeholder="请选择责任人" option-filter-prop="label" :options="userOptions" allow-clear />
          </a-form-item></a-col>
          <a-col :span="12"><a-form-item label="供应商">
            <a-select v-model:value="form.supplier_id" show-search placeholder="请选择供应商" option-filter-prop="label" :options="supplierOptions" allow-clear />
          </a-form-item></a-col>
          <a-col :span="12"><a-form-item label="开始日期"><a-input v-model:value="form.start_date" type="date" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="结束日期"><a-input v-model:value="form.end_date" type="date" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="费用"><a-input-number v-model:value="form.cost" style="width:100%" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="状态">
            <a-select v-model:value="form.offering_status" :options="offeringStatusOptions" />
          </a-form-item></a-col>
          <a-col :span="24"><a-form-item label="备注" :label-col="{ span: 3 }"><a-textarea v-model:value="form.notes" :rows="2" /></a-form-item></a-col>
        </a-row>
      </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 { offeringApi, changeRecordApi, findAssetManager, getSupplierList, getUserList } from "@/api/asset";
import { useAuthStore } from "@/stores/auth";
import ProTable from "@/components/Pro/ProTable/index.vue";
import type { ProTableColumn } from "@/types/pro";

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

const supplierOptions = ref<{ label: string; value: string }[]>([]);
const userOptions = ref<{ label: string; value: string }[]>([]);
const offeringStatusOptions = [
  { label: '生效中', value: 'active' },
  { label: '已过期', value: 'expired' },
  { label: '已取消', value: 'cancelled' },
];

const loadOptions = async () => {
  try {
    const [supRes, userRes]: any[] = await Promise.all([
      getSupplierList(),
      getUserList(),
    ]);
    const extractData = (res: any) => (res.data || res) as any[];
    supplierOptions.value = (extractData(supRes) || []).map((s: any) => ({ label: s.name, value: s.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: "name", key: "name", search: true, searchType: "input" },
  { title: "服务编号", dataIndex: "service_number", key: "service_number" },
  { title: "责任人", dataIndex: "assigned_user_name", key: "assigned_user_name" },
  { title: "供应商", dataIndex: "supplier_name", key: "supplier_name" },
  { title: "状态", dataIndex: "offering_status", key: "offering_status" },
  { title: "开始日期", dataIndex: "start_date", key: "start_date" },
  { title: "结束日期", dataIndex: "end_date", key: "end_date" },
  { title: "费用", dataIndex: "cost", key: "cost" },
  { title: "操作", dataIndex: "operations", key: "operations", width: 200, fixed: "right" as const },
];

const loadData = async (params: Record<string, unknown>) => {
  try {
    const res: any = await offeringApi.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: "offering", 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 = { offering_status: 'active' };
  await loadOptions();
  try {
    const res: any = await findAssetManager(authStore.user?.deptId);
    if (res.code === 1 && res.data) {
      form.value.assigned_to = res.data.id;
    }
  } catch { /* ignore */ }
  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 offeringApi.del(id);
  message.success("删除成功");
  tableRef.value?.reload();
};
const handleSubmit = async () => {
  await offeringApi.save(form.value);
  message.success(isEdit.value ? "更新成功" : "创建成功");
  visible.value = false;
  tableRef.value?.reload();
};
</script>
