<template>
  <div class="app-container h-full flex flex-1 flex-col">
    <!-- 搜索 -->
    <page-search
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    ></page-search>

    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @add-click="handleAddClick"
      @export-click="handleExportClick"
      @search-click="handleSearchClick"
      @toolbar-click="handleToolbarClick"
      @operate-click="handleOperateClick"
      @filter-change="handleFilterChange"
    ></page-content>

    <!-- 编辑提示语弹窗 -->
    <el-dialog
      v-model="tipsDialogVisible"
      :title="tipsDialogTitle"
      width="500px"
      draggable
    >
      <el-form :model="tipsForm" label-width="100px">
        <el-form-item label="充电提示语">
          <el-input
            v-model="tipsForm.connectorTips"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入充电提示语，如：充电减免2小时停车费"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="tipsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTipsSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 按站点一键修改弹窗 -->
    <el-dialog
      v-model="stationTipsDialogVisible"
      title="按站点一键修改提示语"
      width="500px"
      draggable
    >
      <el-form :model="stationTipsForm" label-width="100px">
        <el-form-item label="选择站点">
          <el-select
            v-model="stationTipsForm.stationInfoId"
            placeholder="请选择站点"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in stationOptions"
              :key="item.id"
              :label="item.stationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充电提示语">
          <el-input
            v-model="stationTipsForm.connectorTips"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入充电提示语"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stationTipsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStationTipsSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "ThirdPartyEquipmentInfo" });

import ThirdPartyEquipmentInfoAPI, {
  ThirdPartyEquipmentInfoPageQuery,
  ConnectorTipsUpdateDTO,
} from "@/api/equipmentManage/third-party-equipment-info-api";
import BillingStrategyAPI from "@/api/operationsManage/billing-strategy-api";
import type { IObject, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import { ElMessage } from "element-plus";

// 组合式 CRUD
const {
  searchRef,
  contentRef,
  handleQueryClick,
  handleResetClick,
  handleAddClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();

// 站点选项
const stationOptions = ref<any[]>([]);

// 获取站点列表
const loadStationOptions = async () => {
  try {
    const data = await BillingStrategyAPI.getChargingPileSelect();
    stationOptions.value = data || [];
  } catch (error) {
    console.error("获取站点列表失败", error);
  }
};

onMounted(() => {
  loadStationOptions();
});

// ============== 编辑提示语弹窗 ==============
const tipsDialogVisible = ref(false);
const tipsDialogTitle = ref("编辑提示语");
const tipsForm = reactive<ConnectorTipsUpdateDTO>({
  id: undefined,
  ids: undefined,
  connectorTips: "",
});

// 打开单个编辑弹窗
const openEditTipsDialog = (row: any) => {
  tipsDialogTitle.value = "编辑提示语";
  tipsForm.id = row.id;
  tipsForm.ids = undefined;
  tipsForm.connectorTips = row.connectorTips || "";
  tipsDialogVisible.value = true;
};

// 打开批量编辑弹窗
const openBatchEditTipsDialog = () => {
  const selectedData = contentRef.value?.getSelectionData() || [];
  if (selectedData.length === 0) {
    ElMessage.warning("请先选择要修改的充电桩");
    return;
  }
  tipsDialogTitle.value = `批量修改提示语（已选${selectedData.length}条）`;
  tipsForm.id = undefined;
  tipsForm.ids = selectedData.map((item: any) => item.id);
  tipsForm.connectorTips = "";
  tipsDialogVisible.value = true;
};

// 提交提示语修改
const handleTipsSubmit = async () => {
  try {
    await ThirdPartyEquipmentInfoAPI.updateTips(tipsForm);
    ElMessage.success("修改成功");
    tipsDialogVisible.value = false;
    contentRef.value?.handleRefresh();
  } catch (error) {
    console.error("修改失败", error);
  }
};

// ============== 按站点一键修改弹窗 ==============
const stationTipsDialogVisible = ref(false);
const stationTipsForm = reactive<ConnectorTipsUpdateDTO>({
  stationInfoId: undefined,
  connectorTips: "",
});

// 打开按站点修改弹窗
const openStationTipsDialog = () => {
  stationTipsForm.stationInfoId = undefined;
  stationTipsForm.connectorTips = "";
  stationTipsDialogVisible.value = true;
};

// 提交按站点修改
const handleStationTipsSubmit = async () => {
  if (!stationTipsForm.stationInfoId) {
    ElMessage.warning("请选择站点");
    return;
  }
  try {
    const count = await ThirdPartyEquipmentInfoAPI.updateTips(stationTipsForm);
    ElMessage.success(`修改成功，共更新${count}条记录`);
    stationTipsDialogVisible.value = false;
    contentRef.value?.handleRefresh();
  } catch (error) {
    console.error("修改失败", error);
  }
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "system:third-party-equipment-info",
  formItems: [
    {
      type: "select",
      label: "所属站点",
      prop: "stationName",
      attrs: {
        placeholder: "请选择站点",
        clearable: true,
        filterable: true,
        style: { width: "200px" },
      },
      options: [],
      async initFn(formItem) {
        const data = await BillingStrategyAPI.getChargingPileSelect();
        formItem.options = (data || []).map((item: any) => ({
          label: item.stationName,
          value: item.stationName,
        }));
      },
    },
    {
      type: "input",
      label: "设备编码",
      prop: "equipmentId",
      attrs: {
        placeholder: "设备编码",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "设备名称",
      prop: "equipmentName",
      attrs: {
        placeholder: "设备名称",
        clearable: true,
        style: { width: "200px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<ThirdPartyEquipmentInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "system:third-party-equipment-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: ThirdPartyEquipmentInfoAPI.getPage,
  // 删除接口
  deleteAction: ThirdPartyEquipmentInfoAPI.deleteByIds,
  // 数据解析函数
  parseData(res: any) {
    return {
      total: res.total,
      list: res.list,
    };
  },
  // 分页配置
  pagination: {
    background: true,
    layout: "total, sizes, prev, pager, next, jumper",
    pageSize: 20,
    pageSizes: [10, 20, 30, 50],
  },
  // 工具栏配置
  toolbar: [
    "export",
    {
      name: "batchEditTips",
      text: "批量修改提示语",
      perm: "edit",
      attrs: { icon: "edit", type: "warning" },
    },
    {
      name: "stationEditTips",
      text: "按站点一键修改",
      perm: "edit",
      attrs: { icon: "setting", type: "primary" },
    },
  ],
  defaultToolbar: ["refresh", "filter"],
  // 导出接口
  exportAction: ThirdPartyEquipmentInfoAPI.export,
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "接口ID", prop: "connectorId" },
    { label: "接口名称", prop: "connectorName" },
    { label: "所属充电站", prop: "stationName" },
    { label: "总功率(kW)", prop: "power" },
    { label: "设备编码", prop: "equipmentId" },
    { label: "设备名称", prop: "equipmentName" },
    {
      label: "车位号",
      prop: "parkNo",
      templet: "format",
      formatter: (row: any) => {
        return row.parkNo || "--";
      },
    },
    {
      label: "国家标准",
      prop: "nationalStandard",
      templet: "format",
      formatter: (row: any) => {
        return row.nationalStandard == 1 ? "2011" : "2015";
      },
    },
    {
      label: "充电提示语",
      prop: "connectorTips",
      minWidth: 150,
      templet: "format",
      formatter: (row: any) => {
        return row.connectorTips || "--";
      },
    },
    {
      label: "操作",
      prop: "operation",
      width: 120,
      templet: "tool",
      operat: ["edit"],
    },
  ],
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    openEditTipsDialog(data.row);
  }
};

// 处理工具栏按钮点击
const handleToolbarClick = (name: string) => {
  if (name === "batchEditTips") {
    openBatchEditTipsDialog();
  } else if (name === "stationEditTips") {
    openStationTipsDialog();
  }
};
</script>
