<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"
    >
      <template #stationType="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charging_station_type" />
      </template>
      <template #stationStatus="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charging_station_status" />
      </template>
      <template #construction="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charging_construction_type" />
      </template>
      <!--      // 0、平台 1、企业 2、渠道方-->
      <template #salesType="scope">
        <el-tag v-if="scope.row.salesType == 0" type="danger">平台</el-tag>
        <el-tag v-if="scope.row.salesType == 1" type="primary">企业</el-tag>
        <el-tag v-if="scope.row.salesType == 2" type="warning">渠道方</el-tag>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #addServiceFee>
        <el-table v-loading="loading" :data="getServiceFeeData()" style="width: 100%">
          <el-table-column prop="periodFlag" label="时段标志" width="180">
            <template #default="scope">
              <span v-if="scope.row.periodFlag === 1">尖</span>
              <span v-else-if="scope.row.periodFlag === 2">峰</span>
              <span v-else-if="scope.row.periodFlag === 3">平</span>
              <span v-else-if="scope.row.periodFlag === 4">谷</span>
              <span v-else>{{ scope.row.periodFlag }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="timePeriod" label="时间段" width="180"></el-table-column>
          <el-table-column
            prop="electricityFee"
            label="电费（元/度）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="settlementServiceFee"
            label="结算服务费（元）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="settlementFeeTotal"
            label="结算费合计（元/度）"
            width="180"
          ></el-table-column>
          <el-table-column prop="operationServiceFee" label="运营服务费（元）" width="180">
            <template #default="scope">
              <div v-if="editingRowIndex === scope.$index">
                <el-input v-model="editingValue" size="small"></el-input>
                <ElButton
                  type="text"
                  size="small"
                  @click="saveEditOperationServiceFee(scope.row, scope.$index)"
                >
                  保存
                </ElButton>
                <ElButton type="text" size="small" @click="cancelEditOperationServiceFee">
                  取消
                </ElButton>
              </div>
              <span
                v-else
                class="text-#0FDCC4"
                @click="startEditOperationServiceFee(scope.row, scope.$index)"
              >
                {{ scope.row.operationServiceFee }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="valueAddedFees"
            label="增值费用（元）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="salesTotalPrice"
            label="销售合计价格（元/度）"
            width="180"
          ></el-table-column>
        </el-table>
      </template>
      <template #addStationFee="{ formData }">
        <div class="flex items-center">
          <el-input
            v-model="formData.stationFee"
            placeholder="请输入整站设置统一服务费"
            style="width: 200px"
            @keyup.enter="() => confirmUniformFeeSetting(formData.stationFee)"
          />
          <ElButton
            type="primary"
            size="small"
            class="ml-2"
            @click="() => confirmUniformFeeSetting(formData.stationFee)"
          >
            确定
          </ElButton>
        </div>
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #editServiceFee>
        <el-table v-loading="loading" :data="getServiceFeeData()" style="width: 100%">
          <el-table-column prop="periodFlag" label="时段标志" width="180">
            <template #default="scope">
              <span v-if="scope.row.periodFlag === 1">尖</span>
              <span v-else-if="scope.row.periodFlag === 2">峰</span>
              <span v-else-if="scope.row.periodFlag === 3">平</span>
              <span v-else-if="scope.row.periodFlag === 4">谷</span>
              <span v-else>{{ scope.row.periodFlag }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="timePeriod" label="时间段" width="180"></el-table-column>
          <el-table-column
            prop="electricityFee"
            label="电费（元/度）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="settlementServiceFee"
            label="结算服务费（元）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="settlementFeeTotal"
            label="结算费合计（元/度）"
            width="180"
          ></el-table-column>
          <el-table-column prop="operationServiceFee" label="运营服务费（元）" width="180">
            <template #default="scope">
              <div v-if="editingRowIndex === scope.$index">
                <el-input v-model="editingValue" size="small"></el-input>
                <ElButton
                  type="text"
                  size="small"
                  @click="saveEditOperationServiceFee(scope.row, scope.$index)"
                >
                  保存
                </ElButton>
                <ElButton type="text" size="small" @click="cancelEditOperationServiceFee">
                  取消
                </ElButton>
              </div>
              <span
                v-else
                class="text-#0FDCC4"
                @click="startEditOperationServiceFee(scope.row, scope.$index)"
              >
                {{ scope.row.operationServiceFee }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="valueAddedFees"
            label="增值费用（元）"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="salesTotalPrice"
            label="销售合计价格（元/度）"
            width="180"
          ></el-table-column>
        </el-table>
      </template>
      <template #editStationFee="{ formData }">
        <div class="flex items-center">
          <el-input
            v-model="formData.stationFee"
            placeholder="请输入整站设置统一服务费"
            style="width: 200px"
            @keyup.enter="() => confirmUniformFeeSetting(formData.stationFee)"
          />
          <ElButton
            type="primary"
            size="small"
            class="ml-2"
            @click="() => confirmUniformFeeSetting(formData.stationFee)"
          >
            确定
          </ElButton>
        </div>
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "ThirdPartyStationInfo" });
import { ref, h } from "vue";
import { ElMessage, ElMessageBox, ElButton } from "element-plus";
import ThirdPartyStationInfoAPI, {
  ThirdPartyStationInfoForm,
  ThirdPartyStationInfoPageQuery,
} from "@/api/operationsManage/billing-strategy-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import { useDictStoreHook } from "@/store/modules/dict-store"; // 添加字典存储导入

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

// 自定义新增点击处理函数，在打开新增模态框时重置统一费用设置状态
const handleAddClick = () => {
  // 重置统一费用设置状态
  isUniformFeeSet.value = false;
  // 调用原始的新增点击处理函数
  originalHandleAddClick();
};
// 字典store
const dictStore = useDictStoreHook();

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "system:billing-strategy",
  formItems: [
    {
      type: "input",
      label: "充电站ID",
      prop: "stationId",
      attrs: {
        placeholder: "充电站ID",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "充电站名称",
      prop: "stationName",
      attrs: {
        placeholder: "充电站名称",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select", // 修改为select类型
      label: "站点状态",
      prop: "stationStatus",
      attrs: {
        placeholder: "请选择站点状态",
        clearable: true,
        style: { width: "200px" },
      },
      async initFn(formItem) {
        await dictStore.loadDictItems("charging_station_status");
        formItem.options = dictStore.getDictItems("charging_station_status");
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<ThirdPartyStationInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "system:billing-strategy",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: ThirdPartyStationInfoAPI.getPage,
  // 删除接口
  deleteAction: ThirdPartyStationInfoAPI.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: ["add", "delete"],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "充电站ID", prop: "stationId" },
    {
      label: "充电站名称",
      prop: "stationName",
    },
    {
      label: "单位名称",
      prop: "unitName",
      formatter: (row: any) => {
        return row.unitName || "平台";
      },
    },
    { label: "省市辖区编码", prop: "areaCode" },
    { label: "详细地址", prop: "address" },
    { label: "服务电话", prop: "serviceTel" },
    { label: "站点类型", prop: "stationType", templet: "custom" },
    // { label: "站点类型", prop: "stationTips" },
    {
      label: "站点状态",
      prop: "stationStatus",
      templet: "custom",
    },
    {
      label: "收费类型",
      prop: "salesType",
      templet: "custom",
    },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      templet: "tool",
      operat: [
        "edit",
        "delete",
        // {
        //   name: "setTips",
        //   text: "设置提示语",
        //   attrs: {
        //     type: "success",
        //   },
        // },
      ],
    },
  ],
});

const stationId = ref();
// 新增配置
const addModalConfig: IModalConfig<ThirdPartyStationInfoForm> = reactive({
  // 权限前缀
  permPrefix: "system:billing-strategy",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 1200,
    draggable: true,
  },
  form: {
    labelWidth: 140,
  },
  // 表单项配置
  formItems: [
    {
      type: "select",
      attrs: {
        placeholder: "请选择充电站",
        style: {
          width: "200px",
        },
      },
      rules: [{ required: true, message: "充电站不能为空", trigger: "blur" }],
      label: "选择电站",
      prop: "stationId",
      options: [],
      events: {
        change: (value: string) => {
          stationId.value = value;
          const formData = addModalRef.value?.getFormData();
          const salesType = formData?.salesType;

          if (value && salesType !== undefined) {
            // 平台类型直接调用
            if (salesType === 0) {
              fetchBillingStrategy(value, salesType, 0, 0);
            }
            // 企业类型需要检查是否有企业ID
            else if (salesType === 1) {
              const firmId = formData?.firmId;
              if (firmId) {
                fetchBillingStrategy(value, salesType, 0, firmId);
              }
            }
            // 渠道方类型需要检查是否有渠道方ID
            else if (salesType === 2) {
              const thirdPartyId = formData?.id;
              if (thirdPartyId) {
                fetchBillingStrategy(value, salesType, thirdPartyId, 0);
              }
            }
          }
        },
      },
      async initFn(formItem) {
        try {
          // 调用接口获取充电站数据
          const response = await ThirdPartyStationInfoAPI.getChargingPileSelect();
          if (Array.isArray(response)) {
            formItem.options = response.map((item) => ({
              label: item.stationName,
              value: item.id,
            }));
          } else {
            console.warn("接口返回数据格式不正确，期望数组格式:", response);
            formItem.options = [];
          }
        } catch (error) {
          console.error("获取充电站数据失败:", error);
          formItem.options = [];
        }
      },
    },
    {
      type: "radio",
      label: "收费类型",
      prop: "salesType",
      attrs: {
        placeholder: "请选择收费类型",
      },
      // 0、平台 1、企业 2、渠道方
      options: [
        {
          label: "平台",
          value: 0,
        },
        {
          label: "企业",
          value: 1,
        },
        {
          label: "渠道方",
          value: 2,
        },
      ],
      rules: [{ required: true, message: "收费类型不能为空", trigger: "blur" }],
      events: {
        change: (value: number) => {
          const formData = addModalRef.value?.getFormData();
          const stationId = formData?.stationId;

          if (stationId && value !== undefined) {
            if (value === 0) {
              fetchBillingStrategy(stationId, value, 0, 0);
            } else if (value === 1) {
              serviceFeeData.value = [];
              const firmId = formData?.firmId;
              if (firmId) {
                fetchBillingStrategy(stationId, value, 0, firmId);
              }
            } else if (value === 2) {
              serviceFeeData.value = [];
              const thirdPartyId = formData?.id;
              if (thirdPartyId) {
                fetchBillingStrategy(stationId, value, thirdPartyId, 0);
              }
            }
          }
        },
      },
    },
    {
      type: "select",
      label: "选择企业",
      prop: "firmId",
      attrs: {
        placeholder: "请选择企业",
        style: {
          width: "200px",
        },
      },
      rules: [
        {
          required: true,
          message: "企业不能为空",
          trigger: "blur",
          validator: (_, value, callback, formData) => {
            // 只有当收费类型为1（企业）时才校验
            if (formData.salesType === 1) {
              if (!value) {
                callback(new Error("企业不能为空"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
        },
      ],
      options: [],
      visible: (formData: any) => {
        return formData.salesType === 1;
      },
      events: {
        change: (value: number) => {
          const formData = addModalRef.value?.getFormData();
          const stationId = formData?.stationId;
          const salesType = formData?.salesType;
          if (stationId && salesType === 1 && value) {
            fetchBillingStrategy(stationId, salesType, 0, value);
          }
        },
      },
      async initFn(formItem) {
        try {
          // 调用接口获取企业数据
          const response = await ThirdPartyStationInfoAPI.getFirmSelect();
          if (Array.isArray(response)) {
            formItem.options = response.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }
        } catch (error) {
          console.error("获取企业数据失败:", error);
        }
      },
    },
    {
      type: "select",
      label: "选择渠道方",
      prop: "id",
      attrs: {
        placeholder: "请选择渠道方",
        style: {
          width: "200px",
        },
      },
      rules: [
        {
          required: true,
          message: "渠道方不能为空",
          trigger: "blur",
          validator: (_, value, callback, formData) => {
            if (formData.salesType === 2) {
              if (!value) {
                callback(new Error("渠道方不能为空"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
        },
      ],
      options: [],
      visible: (formData: any) => {
        return formData.salesType === 2;
      },
      events: {
        change: (value: number) => {
          // 当渠道方选择改变时调用接口
          const formData = addModalRef.value?.getFormData();
          const stationId = formData?.stationId;
          const salesType = formData?.salesType;

          if (stationId && salesType === 2 && value) {
            fetchBillingStrategy(stationId, salesType, value, 0);
          }
        },
      },
      async initFn(formItem) {
        try {
          // 调用接口获取渠道方数据
          const response = await ThirdPartyStationInfoAPI.getChannelSelect();
          if (Array.isArray(response)) {
            formItem.options = response.map((item) => ({
              label: item.stationName,
              value: item.id,
            }));
          }
        } catch (error) {
          console.error("获取渠道方数据失败:", error);
        }
      },
    },
    {
      type: "custom",
      label: "整站设置统一服务费",
      prop: "stationFee",
      slotName: "addStationFee",
    },
    {
      type: "custom",
      label: "服务费设置",
      prop: "serviceFee",
      slotName: "addServiceFee",
    },
  ],
  // 提交函数
  formAction: (data: ThirdPartyStationInfoForm) => {
    // 检查统一费用是否已设置
    if (!isUniformFeeSet.value) {
      ElMessageBox.confirm("统一费用尚未设置，确定要提交吗？", "确认提交", {
        cancelButtonText: "去设置",
        type: "warning",
      })
        .then(() => {
          // 用户确认提交，即使未设置统一费用
          if (data.id) {
            // 编辑
            // return ThirdPartyStationInfoAPI.update(data.id as string, data);
            return Promise.resolve();
          } else {
            // return ThirdPartyStationInfoAPI.create(data);
            return Promise.resolve();
          }
        })
        .catch(() => {
          // 用户选择去设置，不提交
          ElMessage.info("请先设置统一费用");
          return Promise.reject(new Error("未设置统一费用"));
        });
    } else {
      // 统一费用已设置，正常提交
      if (data.id) {
        // 编辑
        // return ThirdPartyStationInfoAPI.update(data.id as string, data);
        return Promise.resolve();
      } else {
        // return ThirdPartyStationInfoAPI.create(data);
        return Promise.resolve();
      }
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<ThirdPartyStationInfoForm> = reactive({
  permPrefix: "system:billing-strategy",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 1000,
  },
  pk: "id",
  formAction(data: any) {
    // 检查统一费用是否已设置
    if (!isUniformFeeSet.value) {
      return ElMessageBox.confirm("统一费用尚未设置，确定要提交吗？", "确认提交", {
        confirmButtonText: "确定提交",
        cancelButtonText: "去设置",
        type: "warning",
      })
        .then(() => {
          // 用户确认提交，即使未设置统一费用
          return Promise.resolve();
        })
        .catch(() => {
          // 用户选择去设置，不提交
          ElMessage.info("请先设置统一费用");
          return Promise.reject(new Error("未设置统一费用"));
        });
    } else {
      // 统一费用已设置，正常提交
      return Promise.resolve();
    }
  },
  formItems: addModalConfig.formItems.map((item) => {
    // 为编辑模态框复制表单项，并添加相应的事件监听器
    if (item.prop === "stationId") {
      return {
        ...item,
        events: {
          change: (value: string) => {
            // 当充电站选择改变时，根据当前的收费类型进行不同处理
            const formData = editModalRef.value?.getFormData();
            const salesType = formData?.salesType;
            if (value && salesType !== undefined) {
              // 平台类型直接调用
              if (salesType === 0) {
                fetchBillingStrategy(value, salesType, null, null);
              }
              // 企业类型需要检查是否有企业ID
              else if (salesType === 1) {
                serviceFeeData.value = [];
                const firmId = formData?.firmId;
                if (firmId) {
                  fetchBillingStrategy(value, salesType, null, firmId);
                }
              }
              // 渠道方类型需要检查是否有渠道方ID
              else if (salesType === 2) {
                serviceFeeData.value = [];
                const thirdPartyId = formData?.id; // 注意这里使用的是 id 字段
                if (thirdPartyId) {
                  fetchBillingStrategy(value, salesType, thirdPartyId, null);
                }
              }
            }
          },
        },
        // 在编辑模式下确保选项已加载
        async initFn(formItem) {
          try {
            // 调用接口获取充电站数据
            const response = await ThirdPartyStationInfoAPI.getChargingPileSelect();
            if (Array.isArray(response)) {
              formItem.options = response.map((item) => ({
                label: item.stationName,
                value: item.id,
              }));
            } else {
              console.warn("接口返回数据格式不正确，期望数组格式:", response);
              formItem.options = [];
            }
          } catch (error) {
            console.error("获取充电站数据失败:", error);
            formItem.options = [];
          }
        },
      };
    } else if (item.prop === "salesType") {
      return {
        ...item,
        events: {
          change: (value: number) => {
            // 当收费类型选择改变时，根据不同的收费类型进行不同处理
            const formData = editModalRef.value?.getFormData();
            const stationId = formData?.stationId;

            if (stationId && value !== undefined) {
              // 平台类型直接调用
              if (value === 0) {
                fetchBillingStrategy(stationId, value, null, null);
              }
              // 企业类型需要等待企业选择后再调用
              else if (value === 1) {
                const firmId = formData?.firmId;
                if (firmId) {
                  fetchBillingStrategy(stationId, value, null, firmId);
                }
              }
              // 渠道方类型需要等待渠道方选择后再调用
              else if (value === 2) {
                const thirdPartyId = formData?.id; // 注意这里使用的是 id 字段
                if (thirdPartyId) {
                  fetchBillingStrategy(stationId, value, thirdPartyId, null);
                }
              }
            }
          },
        },
      };
    } else if (item.prop === "firmId") {
      // 企业下拉框添加显隐控制和change事件
      return {
        ...item,
        rules: [
          {
            required: true,
            message: "企业不能为空",
            trigger: "blur",
            validator: (_, value, callback, formData) => {
              // 只有当收费类型为1（企业）时才校验
              if (formData.salesType === 1) {
                if (!value) {
                  callback(new Error("企业不能为空"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
          },
        ],
        visible: (formData: any) => {
          // 只有当收费类型为1（企业）时才显示
          return formData.salesType === 1;
        },
        events: {
          change: (value: number) => {
            // 当企业选择改变时调用接口
            const formData = editModalRef.value?.getFormData();
            const stationId = formData?.stationId;
            const salesType = formData?.salesType;

            if (stationId && salesType === 1 && value) {
              fetchBillingStrategy(stationId, salesType, 0, value);
            }
          },
        },
        // 在编辑模式下确保选项已加载
        async initFn(formItem) {
          try {
            // 调用接口获取企业数据
            const response = await ThirdPartyStationInfoAPI.getFirmSelect();
            if (Array.isArray(response)) {
              formItem.options = response.map((item) => ({
                label: item.name,
                value: item.id,
              }));
            }
          } catch (error) {
            console.error("获取企业数据失败:", error);
          }
        },
      };
    } else if (item.prop === "id") {
      // 渠道方下拉框添加显隐控制和change事件
      return {
        ...item,
        rules: [
          {
            required: true,
            message: "渠道方不能为空",
            trigger: "blur",
            validator: (_, value, callback, formData) => {
              // 只有当收费类型为2（渠道方）时才校验
              if (formData.salesType === 2) {
                if (!value) {
                  callback(new Error("渠道方不能为空"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
          },
        ],
        visible: (formData: any) => {
          // 只有当收费类型为2（渠道方）时才显示
          return formData.salesType === 2;
        },
        events: {
          change: (value: number) => {
            // 当渠道方选择改变时调用接口
            const formData = editModalRef.value?.getFormData();
            const stationId = formData?.stationId;
            const salesType = formData?.salesType;

            if (stationId && salesType === 2 && value) {
              fetchBillingStrategy(stationId, salesType, value, 0);
            }
          },
        },
        // 在编辑模式下确保选项已加载
        async initFn(formItem) {
          try {
            // 调用接口获取渠道方数据
            const response = await ThirdPartyStationInfoAPI.getChannelSelect();
            if (Array.isArray(response)) {
              formItem.options = response.map((item) => ({
                label: item.stationName,
                value: item.id,
              }));
            }
          } catch (error) {
            console.error("获取渠道方数据失败:", error);
          }
        },
      };
    } else if (item.prop === "stationFee") {
      // 整站设置统一服务费
      return {
        ...item,
        type: "custom",
        slotName: "editStationFee",
      };
    } else if (item.prop === "serviceFee") {
      // 服务费设置
      return {
        ...item,
        type: "custom",
        slotName: "editServiceFee",
      };
    }
    return item;
  }),
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      // 根据销售类型传入相应参数
      const stationId = data.row.id;
      const salesType = data.row.salesType !== undefined ? data.row.salesType : 0; // 默认为平台类型
      let firmId = 0;
      let thirdPartyId = 0;

      // 根据销售类型设置相应参数
      if (salesType === 1) {
        firmId = data.row.firmId || 0;
      } else if (salesType === 2) {
        thirdPartyId = data.row.thirdPartyId || data.row.id || 0;
      }

      // 重置统一费用设置状态
      isUniformFeeSet.value = false;

      // 获取表单数据
      const formData = await ThirdPartyStationInfoAPI.getFormData(
        stationId,
        salesType,
        firmId,
        thirdPartyId
      );

      // 获取服务费策略数据并填充到表格中
      fetchBillingStrategy(stationId, salesType, thirdPartyId, firmId);

      // 确保表单数据包含必要的字段用于回显
      const enrichedFormData = {
        ...formData,
        stationId,
        salesType,
        firmId: firmId || formData.firmId,
        id: thirdPartyId || formData.id, // 注意这里使用的是 id 字段存储 thirdPartyId
      };

      // 返回表单数据用于回显
      return enrichedFormData;
    });
  } else if (data.name === "setTips") {
    // 显示设置提示语弹窗
    ElMessageBox.prompt("设置提示语", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPlaceholder: "请输入提示语",
      inputValue: data.row.tips || "",
      inputPattern: /^.{0,100}$/,
      inputErrorMessage: "提示语长度不能超过100个字符",
    })
      .then(async ({ value }) => {
        try {
          await ThirdPartyStationInfoAPI.setTips({
            stationId: parseInt(data.row.id),
            stationTips: value,
          });
          ElMessage.success("提示语设置成功");
          // 刷新列表
          contentRef.value?.getList();
        } catch (error) {
          console.error("设置提示语失败:", error);
        }
      })
      .catch(() => {
        ElMessage.info("取消设置");
      });
  }
};

// 处理工具栏按钮点击（删除等）
const handleToolbarClick = (name: string) => {
  console.log(name);
};

// 存储从接口获取的服务费数据
const serviceFeeData = ref([]);
const loading = ref(false);
// 存储正在编辑的行索引
const editingRowIndex = ref(-1);
// 存储编辑时的临时值
const editingValue = ref("");
// 跟踪统一费用是否已设置
const isUniformFeeSet = ref(false);

// 获取服务费表格数据
const getServiceFeeData = () => {
  return serviceFeeData.value;
};

// 调用getBillingStrategy接口获取服务费数据
const fetchBillingStrategy = async (
  stationId: string,
  salesType: number,
  thirdPartyId: number = 0,
  firmId: number = 0
) => {
  loading.value = true;
  try {
    const response = await ThirdPartyStationInfoAPI.getBillingStrategy(
      stationId,
      salesType,
      thirdPartyId,
      firmId
    );
    console.log("获取计费策略数据:", response);

    // 格式化时间函数
    const formatTimePeriod = (timeStr: string) => {
      if (!timeStr || timeStr.length !== 6) return timeStr;
      const hours = timeStr.substring(0, 2);
      const minutes = timeStr.substring(2, 4);
      const seconds = timeStr.substring(4, 6);
      return `${hours}:${minutes}:${seconds}`;
    };
    if (response && Array.isArray(response)) {
      serviceFeeData.value = response.map((item) => ({
        timePeriod: formatTimePeriod(item.timePeriod),
        electricityFee: item.electricityPrice,
        settlementServiceFee: item.settlementServiceFee,
        settlementFeeTotal: item.settlementTotalPrice,
        operationServiceFee: item.operationServiceFee,
        salesTotalPrice: item.saleTotalPrice,
        valueAddedFees: item.valueAddedFees,
        periodFlag: item.periodFlag,
      }));
    } else {
      serviceFeeData.value = [];
    }
  } catch (error) {
    console.error("获取计费策略数据失败:", error);
    serviceFeeData.value = [];
  } finally {
    loading.value = false;
  }
};

// 开始编辑运营服务费
const startEditOperationServiceFee = (row: any, index: number) => {
  editingRowIndex.value = index;
  editingValue.value = row.operationServiceFee || "";
};

// 保存编辑的运营服务费
const saveEditOperationServiceFee = async (row: any, index: number) => {
  // 验证输入值是否为数字（整数或小数）
  if (!/^-?\d+(\.\d+)?$/.test(editingValue.value)) {
    ElMessage.error("请输入有效的数字");
    return;
  }

  // 获取当前表单数据以获取必要参数
  let formData = addModalRef.value?.getFormData();
  if (!formData || !formData.stationId) {
    formData = editModalRef.value?.getFormData();
  }

  if (!formData || !formData.stationId) {
    ElMessage.error("无法获取表单数据，请确保已选择电站");
    return;
  }

  // 构造保存参数数组
  const saveParamsArray = [
    {
      operationServiceFee: parseFloat(editingValue.value),
      stationInfoId: formData.stationId,
      salesType: formData.salesType,
      periodFlag: row.periodFlag,
    },
  ];

  // 根据销售类型添加额外参数
  if (formData.salesType === 1) {
    // 企业类型
    saveParamsArray[0].firmId = formData.firmId;
  } else if (formData.salesType === 2) {
    // 渠道方类型
    saveParamsArray[0].thirdPartyId = formData.id;
  }
  try {
    // 调用保存接口，传递数组参数
    await ThirdPartyStationInfoAPI.saveBillingStrategy(saveParamsArray);
    ElMessage.success("保存成功");
    // 更新本地数据
    serviceFeeData.value[index].operationServiceFee = parseFloat(editingValue.value);
    // 标记统一费用已设置
    isUniformFeeSet.value = true;
    // 重置编辑状态
    editingRowIndex.value = -1;
    editingValue.value = "";
  } catch (error) {
    ElMessage.error("保存失败: " + (error as Error).message);
  }
};

// 取消编辑
const cancelEditOperationServiceFee = () => {
  editingRowIndex.value = -1;
  editingValue.value = "";
};

// 处理统一费用设置
const handleUniformFeeSetting = async (uniformFee: string) => {
  // 验证输入值是否为数字（整数或小数）
  if (!uniformFee || !/^-?\d+(\.\d+)?$/.test(uniformFee)) {
    // 如果输入为空或无效，则不执行任何操作
    return;
  }

  const feeValue = parseFloat(uniformFee);

  // 获取当前表单数据以获取必要参数
  let formData = addModalRef.value?.getFormData();
  if (!formData || !formData.stationId) {
    formData = editModalRef.value?.getFormData();
  }

  if (!formData || !formData.stationId) {
    ElMessage.error("无法获取表单数据，请确保已选择电站");
    return;
  }

  // 构造保存参数数组
  const saveParamsArray = serviceFeeData.value.map((row: any) => ({
    operationServiceFee: feeValue,
    stationInfoId: formData.stationId,
    salesType: formData.salesType,
    periodFlag: row.periodFlag,
    // 根据销售类型添加额外参数
    ...(formData.salesType === 1 && { firmId: formData.firmId }), // 企业类型
    ...(formData.salesType === 2 && { thirdPartyId: formData.id }), // 渠道方类型
  }));

  try {
    // 调用保存接口，传递数组参数
    await ThirdPartyStationInfoAPI.saveBillingStrategy(saveParamsArray);
    ElMessage.success("统一设置成功");

    // 更新本地数据
    serviceFeeData.value = serviceFeeData.value.map((row: any) => ({
      ...row,
      operationServiceFee: feeValue,
    }));

    // 标记统一费用已设置
    isUniformFeeSet.value = true;
  } catch (error) {
    ElMessage.error("统一设置失败: " + (error as Error).message);
  }
};

// 确认统一费用设置
const confirmUniformFeeSetting = (uniformFee: string) => {
  // 验证输入值是否为数字（整数或小数）
  if (!uniformFee || !/^-?\d+(\.\d+)?$/.test(uniformFee)) {
    ElMessage.error("请输入有效的数字");
    return;
  }

  const feeValue = parseFloat(uniformFee);

  ElMessageBox.confirm(`确定要将所有时间段的运营服务费设置为 ${feeValue} 元吗？`, "确认设置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      handleUniformFeeSetting(uniformFee);
    })
    .catch(() => {
      // 用户取消操作
      ElMessage.info("已取消设置");
    });
};
</script>
