<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:failure:add'" type="primary" @click="handleAdd"><PlusOutlined /> 新增故障</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 'open' ? 'red' : record.status === 'in_progress' ? 'orange' : record.status === 'resolved' ? 'blue' : 'green'">{{ record.status === 'open' ? '待处理' : record.status === 'in_progress' ? '处理中' : record.status === 'resolved' ? '已修复' : '已关闭' }}</a-tag>
        </template>
        <template v-if="column.key === 'operations'">
          <a-space :size="4" @click.stop>
            <a-button v-permission="'biz:failure:edit'" type="link" size="small" @click.stop="handleEdit(record)"><EditOutlined /> 编辑</a-button>
            <a-popconfirm v-permission="'biz:failure: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.failure_name" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="关联类型">
            <a-select v-model:value="form.target_type" placeholder="请选择关联类型" :options="targetTypeOptions" />
          </a-form-item></a-col>
          <a-col :span="12"><a-form-item label="关联资产ID"><a-input v-model:value="form.target_id" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="故障日期" required><a-input v-model:value="form.failure_date" type="date" /></a-form-item></a-col>
          <a-col :span="12"><a-form-item label="状态">
            <a-select v-model:value="form.status" :options="failureStatusOptions" />
          </a-form-item></a-col>
          <a-col :span="12"><a-form-item label="报告人">
            <a-select v-model:value="form.reported_by" 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.resolved_by" show-search placeholder="请选择解决人" option-filter-prop="label" :options="userOptions" allow-clear />
          </a-form-item></a-col>
          <a-col :span="24"><a-form-item label="故障描述" :label-col="{ span: 3 }"><a-textarea v-model:value="form.failure_description" :rows="3" /></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 { failureApi, changeRecordApi, 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 targetTypeOptions = [
  { label: '设备', value: 'device' },
  { label: '许可证', value: 'license' },
  { label: '配件', value: 'accessory' },
];
const failureStatusOptions = [
  { label: '待处理', value: 'open' },
  { label: '处理中', value: 'in_progress' },
  { label: '已修复', value: 'resolved' },
  { label: '已关闭', value: 'closed' },
];

const loadOptions = async () => {
  try {
    const userRes: any = await getUserList();
    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: "failure_name", key: "failure_name", search: true, searchType: "input" },
  { title: "关联类型", dataIndex: "target_type", key: "target_type" },
  { title: "状态", dataIndex: "status", key: "status" },
  { title: "报告人", dataIndex: "reported_user_name", key: "reported_user_name" },
  { title: "解决人", dataIndex: "resolved_user_name", key: "resolved_user_name" },
  { title: "故障日期", dataIndex: "failure_date", key: "failure_date" },
  { title: "操作", dataIndex: "operations", key: "operations", width: 200, fixed: "right" as const },
];

const loadData = async (params: Record<string, unknown>) => {
  try {
    const res: any = await failureApi.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: "failure", 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 = { status: 'open' }; 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 failureApi.del(id);
  message.success("删除成功");
  tableRef.value?.reload();
};
const handleSubmit = async () => {
  await failureApi.save(form.value);
  message.success(isEdit.value ? "更新成功" : "创建成功");
  visible.value = false;
  tableRef.value?.reload();
};
</script>
