<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 搜索表单卡片 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              筛选条件
            </span>
          </div>
        </template>
        <el-form :model="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList" class="search-form">
          <el-form-item label="代理名称" prop="agentName">
            <el-input 
              v-model="state.queryForm.agentName" 
              placeholder="请输入代理名称" 
              clearable
              style="width: 200px" /> 
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              招标代理管理
            </span>
            <div class="header-actions">
              <el-button 
                icon="Files" 
                link 
                type="primary" 
                @click="openSummaryDialog"
              >
                代理汇总
              </el-button>
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog('add')"
                v-auth="'purchase_purchasingagent_add'">
                新增
              </el-button>
              <right-toolbar v-model:showSearch="showSearch" class="ml10" @queryTable="getDataList" />
            </div>
          </div>
        </template>

        <!-- 表格 -->
        <el-table 
          ref="tableRef"
          :data="state.dataList" 
          v-loading="state.loading" 
          stripe
          :cell-style="tableStyle.cellStyle" 
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="agentName" label="代理名称" min-width="200" show-overflow-tooltip>
            <template #header>
              <el-icon><Document /></el-icon>
              <span style="margin-left: 4px">代理名称</span>
            </template>
          </el-table-column>
          <el-table-column prop="contactPerson" label="联系人" width="120" show-overflow-tooltip>
            <template #header>
              <el-icon><User /></el-icon>
              <span style="margin-left: 4px">联系人</span>
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="联系电话" width="140" show-overflow-tooltip>
            <template #header>
              <el-icon><Phone /></el-icon>
              <span style="margin-left: 4px">联系电话</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="登录用户名" width="140" show-overflow-tooltip>
            <template #header>
              <el-icon><UserFilled /></el-icon>
              <span style="margin-left: 4px">登录用户名</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
            <template #header>
              <el-icon><EditPen /></el-icon>
              <span style="margin-left: 4px">备注</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip>
            <template #header>
              <el-icon><Clock /></el-icon>
              <span style="margin-left: 4px">创建时间</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="150">
            <template #default="scope">
              <el-button 
                icon="Edit" 
                link 
                type="primary"
                v-auth="'purchase_purchasingagent_edit'"
                @click="formDialogRef.openDialog('edit', scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link 
                type="danger"
                v-auth="'purchase_purchasingagent_del'"
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="state.total > 0"
          :total="state.total"
          v-model:page="state.page"
          v-model:limit="state.limit"
          @pagination="getDataList"
        />
      </el-card>
    </div>

    <!-- 编辑、新增表单对话框 -->
    <FormDialog ref="formDialogRef" @refresh="getDataList" />

    <!-- 代理汇总弹窗 -->
    <el-dialog
      v-model="summaryDialogVisible"
      title="代理数据汇总"
      width="85%"
      destroy-on-close
      class="agent-summary-dialog"
    >
      <el-form :model="summaryQuery" inline class="summary-query-form">
        <el-form-item label="需求部门">
          <el-select
            v-model="summaryQuery.deptCode"
            placeholder="请选择"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划采购开始时间">
          <el-date-picker
            v-model="summaryQuery.planStartDate"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
            style="width: 180px"
            clearable
          />
        </el-form-item>
        <el-form-item label="计划采购结束时间">
          <el-date-picker
            v-model="summaryQuery.planEndDate"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
            style="width: 180px"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否履约评价">
          <el-select v-model="summaryQuery.hasAcceptEvaluation" placeholder="请选择" clearable style="width: 140px">
            <el-option label="已履约评价" value="1" />
            <el-option label="未履约评价" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="querySummary">查询</el-button>
          <el-button @click="clearSummaryQuery">清空</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="summaryList"
        v-loading="summaryLoading"
        border
        stripe
        max-height="400"
        class="summary-table"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="agentName" label="代理机构" min-width="200" show-overflow-tooltip />
        <el-table-column prop="projectCount" label="代理项目" width="100" align="center" />
        <el-table-column prop="budgetAmount" label="预算金额" width="140" align="right">
          <template #default="{ row }">
            {{ formatMoney(row.budgetAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="contractAmount" label="合同(成交)金额" width="140" align="right">
          <template #default="{ row }">
            {{ formatMoney(row.contractAmount) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="PurchaseAgent">
import { ref, reactive, defineAsyncComponent } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { getPage, delObj, getAgentSummary } from "/@/api/purchase/purchaseagent";
import { deptTree } from '/@/api/admin/dept';
import { useMessage, useMessageBox } from "/@/hooks/message";
import { List, Document, EditPen, Clock, Search, User, Phone, UserFilled } from '@element-plus/icons-vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

/** 代理汇总弹窗 */
const summaryDialogVisible = ref(false);
const summaryLoading = ref(false);
const summaryList = ref<any[]>([]);
const summaryQuery = reactive({
  deptCode: '',
  planStartDate: '',
  planEndDate: '',
  hasAcceptEvaluation: '',
});
const deptOptions = ref<{ label: string; value: string }[]>([]);

const flattenDept = (nodes: any[], list: { label: string; value: string }[]) => {
  if (!nodes || !Array.isArray(nodes)) return;
  nodes.forEach((n: any) => {
    const code = n.deptId ?? n.id ?? n.deptCode;
    const name = n.name ?? n.deptName ?? '';
    if (code != null && String(code)) list.push({ label: name || String(code), value: String(code) });
    if (n.children?.length) flattenDept(n.children, list);
  });
};

const openSummaryDialog = async () => {
  summaryDialogVisible.value = true;
  if (deptOptions.value.length === 0) {
    try {
      const res = await deptTree();
      const tree = res?.data ?? res ?? [];
      const list: { label: string; value: string }[] = [];
      flattenDept(Array.isArray(tree) ? tree : [], list);
      deptOptions.value = list;
    } catch (_) {
      deptOptions.value = [];
    }
  }
  querySummary();
};

const querySummary = async () => {
  summaryLoading.value = true;
  try {
    const res = await getAgentSummary({
      deptCode: summaryQuery.deptCode || undefined,
      planStartDate: summaryQuery.planStartDate || undefined,
      planEndDate: summaryQuery.planEndDate || undefined,
      hasAcceptEvaluation: summaryQuery.hasAcceptEvaluation || undefined,
    });
    summaryList.value = res?.data && Array.isArray(res.data) ? res.data : [];
  } catch (_) {
    summaryList.value = [];
  } finally {
    summaryLoading.value = false;
  }
};

const clearSummaryQuery = () => {
  summaryQuery.deptCode = '';
  summaryQuery.planStartDate = '';
  summaryQuery.planEndDate = '';
  summaryQuery.hasAcceptEvaluation = '';
  querySummary();
};

const formatMoney = (v: any) => {
  if (v == null || v === '') return '—';
  const n = Number(v);
  if (Number.isNaN(n)) return String(v);
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
};

// 定义变量内容
const tableRef = ref()
const formDialogRef = ref()
const searchFormRef = ref()
const showSearch = ref(true)

/**
 * 定义响应式表格数据
 */
const state: BasicTableProps = reactive<BasicTableProps>({
  pageList: getPage,
  queryForm: {
    agentName: '',
  },
  createdIsNeed: true
});

/**
 * 使用 useTable 定义表格相关操作
 */
const { getDataList, tableStyle } = useTable(state);

/**
 * 重置搜索表单
 */
const handleReset = () => {
  searchFormRef.value?.resetFields();
  getDataList();
};

/**
 * 删除当前行
 * @param row - 当前行数据
 */
const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  try {
    await delObj({"id":row.id});
    useMessage().success('删除成功');
    getDataList();
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败');
  }
};
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>

