<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"
    >
      <template #orderType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="charge_order_type" v-bind="scope.attrs" />
      </template>
      <template #status="scope">
        <Dict
          v-model="scope.formData[scope.prop]"
          code="charge_order_status"
          v-bind="scope.attrs"
        />
      </template>
      <template #stopReason="scope">
        <Dict v-model="scope.formData[scope.prop]" code="charge_stop_reason" v-bind="scope.attrs" />
      </template>
      <template #maspStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="masp_status" v-bind="scope.attrs" />
      </template>
    </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 #orderType="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charge_order_type" />
      </template>
      <template #chargeTime="scope">
        <span>{{ formatSeconds(scope.row[scope.prop]) }}</span>
      </template>
      <template #status="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charge_order_status" />
      </template>
      <template #stopType="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="stop_type" />
      </template>
      <template #maspStatus="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="masp_status" />
      </template>
      <template #stopReason="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="charge_stop_reason" />
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #orderType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="charge_order_type" v-bind="scope.attrs" />
      </template>
      <template #status="scope">
        <Dict
          v-model="scope.formData[scope.prop]"
          code="charge_order_status"
          v-bind="scope.attrs"
        />
      </template>
      <template #stopType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="stop_type" v-bind="scope.attrs" />
      </template>
      <template #maspStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="masp_status" v-bind="scope.attrs" />
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #chargeOrderNo="scope">
        <span class="color-coolGray">{{ scope.formData[scope.prop] }}</span>
      </template>
      <template #orderType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="charge_order_type" v-bind="scope.attrs" />
      </template>
      <template #status="scope">
        <Dict
          v-model="scope.formData[scope.prop]"
          code="charge_order_status"
          v-bind="scope.attrs"
        />
      </template>
      <template #stopType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="stop_type" v-bind="scope.attrs" />
      </template>
      <template #maspStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="masp_status" v-bind="scope.attrs" />
      </template>
      <template #remark="scope">
        <el-input
          v-model="scope.formData[scope.prop]"
          type="textarea"
          v-bind="scope.attrs"
        />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import BillingStrategyAPI from "@/api/operationsManage/billing-strategy-api";
import { ElLoading } from "element-plus";
defineOptions({ name: "ChargeOrderInfo" });
import ChargeOrderInfoAPI, {
  ChargeOrderInfoForm,
  ChargeOrderInfoPageQuery,
} from "@/api/orderManage/charge-order-info-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";

// 处理时间范围参数的通用函数
const processTimeParams = (params: any) => {
  const processedParams = { ...params };
  if ("createTime" in processedParams) {
    const createTime = processedParams.createTime as string[];
    if (createTime?.length > 1) {
      processedParams.startTime = createTime[0] + " 00:00:00";
      processedParams.endTime = createTime[1] + " 23:59:59";
    }
    delete processedParams.createTime;
  }
  return processedParams;
};

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

// 重写导出函数，处理时间参数
const handleExportClick = () => {
  const queryParams = searchRef.value?.getQueryParams();
  if (queryParams) {
    const processedParams = processTimeParams(queryParams);
    // 过滤空值参数
    const filteredParams: any = {};
    for (const key in processedParams) {
      const value = processedParams[key];
      if (value !== "" && value !== null && value !== undefined) {
        if (Array.isArray(value)) {
          if (value.length > 0) {
            filteredParams[key] = value;
          }
        } else {
          filteredParams[key] = value;
        }
      }
    }
    contentRef.value?.exportPageData(filteredParams);
  }
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:charge-order-info",
  formItems: [
    {
      type: "custom",
      slotName: "orderType",
      label: "订单类型", // 0 平台订单 1 企业订单
      prop: "orderType",
      attrs: {
        placeholder: "订单类型",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "终端编号",
      prop: "connectorId",
      attrs: {
        placeholder: "终端编号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "充电订单号",
      prop: "chargeOrderNo",
      attrs: {
        placeholder: "充电订单号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "custom",
      slotName: "status",
      label: "状态", //0待启动 1 充电中 2 结算中 3 已完成, 5未成功充电
      prop: "status",
      attrs: {
        placeholder: "选择状态",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "custom",
      slotName: "stopReason",
      label: "结束原因", //1 主动停止 2 充满停止 3 余额不足停止, 4电桩按钮停止
      prop: "stopReason",
      attrs: {
        placeholder: "选择结束原因",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "用户手机号",
      prop: "phoneNum",
      attrs: {
        placeholder: "用户手机号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select",
      label: "所属站点",
      prop: "thirdStationId",
      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.id,
        }));
      },
    },
    {
      type: "date-picker",
      label: "创建时间",
      prop: "createTime",
      attrs: {
        type: "daterange",
        "range-separator": "~",
        "start-placeholder": "开始时间",
        "end-placeholder": "截止时间",
        "value-format": "YYYY-MM-DD",
        style: { width: "240px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<ChargeOrderInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:charge-order-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: (params: any) => {
    const processedParams = processTimeParams(params);
    return ChargeOrderInfoAPI.getPage(processedParams);
  },
  // 删除接口
  deleteAction: ChargeOrderInfoAPI.deleteByIds,
  // 导出接口
  exportAction: ChargeOrderInfoAPI.exportExcel,
  // 数据解析函数
  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"],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "充电订单号", prop: "chargeOrderNo" },
    { label: "用户手机号", prop: "phoneNum" },
    {
      label: "订单类型", // 1 个人订单 2 集团订单
      prop: "orderType",
      templet: "custom",
      slotName: "orderType",
    },
    { label: "充电站名称", prop: "stationName" },
    { label: "设备名称", prop: "connectorName" },
    { label: "充电桩编号", prop: "equipmentId" },
    { label: "终端编号", prop: "connectorId" },
    { label: "充电开始时间", prop: "startTime" },
    { label: "充电结束时间", prop: "endTime" },
    {
      label: "充电时间", //：秒
      prop: "chargeTime",
      templet: "custom",
      slotName: "chargeTime",
    },
    { label: "车辆实时充电电量", prop: "soc" },
    {
      label: "订单状态", //0待启动 1 充电中 2 结算中 3 已完成, 5未成功充电
      prop: "status",
      templet: "custom",
      slotName: "status",
    },
    {
      label: "实际充电度数", //（单位：0.001 kw/h）
      prop: "totalCharge",
    },
    { label: "平台实际收取金额", prop: "realCost" },
    { label: "平台总服务费", prop: "realServiceCost" },
    { label: "三方充电消费总额", prop: "thirdPartyTotalCost" },
    { label: "三方充电服务费", prop: "thirdPartyServerfee" },
    { label: "三方充电金额", prop: "thirdPartyElecfee" },
    { label: "预充值金额", prop: "preAmt" },
    { label: "优惠金额", prop: "discountMoney" },
    { label: "优惠描述", prop: "discountDesc" },
    { label: "优惠券金额", prop: "couponPrice" },
    {
      label: "结束原因",
      prop: "stopReason",
      templet: "custom",
      slotName: "stopReason",
    },
    { label: "企业名称", prop: "firmName" },
    { label: "企业专享优惠价", prop: "firmPrice" },
    { label: "备注", prop: "remark" },
    { label: "创建时间", prop: "createTime" },
    {
      label: "操作",
      prop: "operation",
      templet: "tool",
      operat: [
        "edit",
        {
          name: "fixes",
          text: "修复",
          attrs: {
            type: "danger",
            link: true,
            size: "small",
          },
        },
      ],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<ChargeOrderInfoForm> = reactive({
  // 权限前缀
  permPrefix: "business:charge-order-info",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "custom",
      label: "充电订单号",
      prop: "chargeOrderNo",
      slotName: "chargeOrderNo",
    },
    {
      type: "custom",
      label: "状态",
      prop: "status",
      slotName: "status",
      attrs: {
        placeholder: "状态",
        style: { width: "100%" },
      },
    },
  ],
  // 提交函数
  formAction: (data: ChargeOrderInfoForm) => {
    if (data.id) {
      // 编辑
      return ChargeOrderInfoAPI.update(data.id as string, data);
    } else {
      // 新增
      return ChargeOrderInfoAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<ChargeOrderInfoForm> = reactive({
  permPrefix: "business:charge-order-info",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return ChargeOrderInfoAPI.update(data.id as string, data);
  },
  formItems: [
    {
      type: "custom",
      label: "充电订单号",
      prop: "chargeOrderNo",
      slotName: "chargeOrderNo",
    },
    {
      type: "custom",
      label: "状态",
      prop: "status",
      slotName: "status",
      attrs: {
        placeholder: "状态",
        style: { width: "100%" },
      },
    },
    {
      type: "custom",
      label: "备注",
      prop: "remark",
      slotName: "remark",
      attrs: {
        placeholder: "请输入备注",
        rows: 4,
        clearable: true,
        style: { width: "100%" },
      },
    },
  ],
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      const formData = await ChargeOrderInfoAPI.getFormData(data.row.id);
      // 如果备注字段为空,自动设置默认值为"手动结束"
      if (formData && !formData.remark) {
        formData.remark = "手动结束";
      }
      return formData;
    });
  }
  if (data.name === "fixes") {
    ElMessageBox.confirm(`确认要修复充电订单 ${data.row.chargeOrderNo} 吗？`, "修复订单确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: "正在修复订单...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        ChargeOrderInfoAPI.orderFixes(data.row.chargeOrderNo)
          .then((res: any) => {
            ElMessage.success(res);
            // 刷新列表，保持在当前分页
            contentRef.value?.handleRefresh(false);
          })
          .catch((error) => {
            ElMessage.error(error?.message || "订单修复失败");
          })
          .finally(() => {
            loading.close();
          });
      })
      .catch(() => {
        // 用户取消操作，不做任何提示
      });
  }
};

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

// 格式化秒数为时分秒
const formatSeconds = (seconds: number) => {
  if (!seconds && seconds !== 0) return "-";
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
};
</script>
