<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"
      @sort-change="handleSortChange"
    >
      <template #type="scope">
        <el-tag :type="scope.row.type == 1 ? 'warning' : 'success'">
          {{ scope.row.type == 1 ? "管理员" : "普通员工" }}
        </el-tag>
      </template>
      <template #balance="scope">
        <span class="money-text primary">¥ {{ formatMoney(scope.row.balance) }}</span>
      </template>
      <template #totalConsumption="scope">
        <span class="money-text warning">¥ {{ formatMoney(scope.row.totalConsumption) }}</span>
      </template>
      <template #amountOwed="scope">
        <span :class="['money-text', scope.row.amountOwed > 0 ? 'danger' : 'success']">
          ¥ {{ formatMoney(scope.row.amountOwed) }}
        </span>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #type="{ formData }">
        <el-radio-group v-model="formData.type">
          <!--          1 管理员 2普通员工-->
          <el-radio :value="1">管理员</el-radio>
          <el-radio :value="2">普通员工</el-radio>
        </el-radio-group>
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #type="{ formData }">
        <el-radio-group v-model="formData.type">
          <!--          1 管理员 2普通员工-->
          <el-radio :value="1">管理员</el-radio>
          <el-radio :value="2">普通员工</el-radio>
        </el-radio-group>
      </template>
    </page-modal>
  </div>
</template>

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

import UserFirmAPI, { UserFirmForm, UserFirmPageQuery } from "@/api/toBManage/user-firm-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import { useUserStore } from "@/store";

// 三方用户角色编码
const ROLE_SFUSER = "SFUSER";

// 获取用户信息
const userStore = useUserStore();

// 判断是否为三方用户
const isSfUser = computed(() => {
  const roles = userStore.userInfo?.roles;
  return roles && roles.includes(ROLE_SFUSER);
});

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

// 金额格式化函数
const formatMoney = (value: number | undefined | null): string => {
  if (value === null || value === undefined) return "0.00";
  return Math.abs(value).toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  // permPrefix: "business:user-firm",
  formItems: [
    {
      type: "input",
      label: "手机号",
      prop: "phone",
      attrs: {
        placeholder: "手机号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select",
      label: "所属企业",
      prop: "firmId",
      attrs: {
        placeholder: "请选择企业",
        clearable: true,
        filterable: true,
        style: { width: "200px" },
      },
      options: [],
      async initFn(item) {
        try {
          const response = await UserFirmAPI.getFirmList();
          if (Array.isArray(response)) {
            item.options = response.map((firm: any) => ({
              label: firm.name,
              value: firm.id,
            }));
          }
        } catch (error) {
          console.error("Failed to fetch firm list:", error);
        }
      },
    },
    {
      type: "select",
      label: "身份", // 1 管理员 2普通员工
      prop: "type",
      attrs: {
        placeholder: "请选择身份", // 1 管理员 2普通员工
        clearable: true,
        style: { width: "200px" },
      },
      options: [
        {
          label: "管理员",
          value: 1,
        },
        {
          label: "普通员工",
          value: 2,
        },
      ],
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<UserFirmPageQuery> = reactive({
  // 权限前缀
  // permPrefix: "business:user-firm",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: UserFirmAPI.getPage,
  // 删除接口
  deleteAction: UserFirmAPI.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: [
    {
      name: "add",
      text: "新增",
      perm: "add",
      attrs: () => ({
        type: "success",
        icon: "plus",
        disabled: isSfUser.value,
      }),
    },
    {
      name: "delete",
      text: "删除",
      perm: "delete",
      attrs: () => ({
        type: "danger",
        icon: "delete",
        disabled: isSfUser.value,
      }),
    },
  ],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 50, align: "center" },
    { label: "用户ID", prop: "userId" },
    { label: "手机号", prop: "phone" },
    { label: "所属企业", prop: "firmName" },
    {
      label: "身份",
      prop: "type",
      templet: "custom",
    },
    {
      label: "当前余额",
      prop: "balance",
      sortable: "custom",
      templet: "custom",
      slotName: "balance",
    },
    {
      label: "累计消费",
      prop: "totalConsumption",
      sortable: "custom",
      templet: "custom",
      slotName: "totalConsumption",
    },
    {
      label: "欠费情况",
      prop: "amountOwed",
      sortable: "custom",
      templet: "custom",
      slotName: "amountOwed",
    },
    { label: "创建时间", prop: "createTime" },
    {
      label: "操作",
      prop: "operation",
      templet: "tool",
      operat: [
        {
          name: "edit",
          text: "编辑",
          attrs: () => ({
            type: "primary",
            icon: "edit",
            link: true,
            size: "small",
            disabled: isSfUser.value,
          }),
        },
        {
          name: "delete",
          text: "删除",
          attrs: () => ({
            type: "danger",
            icon: "delete",
            link: true,
            size: "small",
            disabled: isSfUser.value,
          }),
        },
      ],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<UserFirmForm> = reactive({
  // 权限前缀
  // permPrefix: "business:user-firm",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "输入手机号",
      },
      label: "手机号",
      prop: "phone",
    },
    {
      type: "select",
      label: "所属企业",
      prop: "firmId",
      attrs: {
        placeholder: "选择所属企业",
        style: {
          width: "200px",
        },
      },
      options: [],
      async initFn(item) {
        try {
          // 调用接口获取充电站数据
          const response = await UserFirmAPI.getFirmList();
          if (Array.isArray(response)) {
            item.options = response.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }
        } catch (error) {
          console.error("Failed to fetch data:", error);
        }
      },
    },
    {
      type: "custom",
      label: "身份", // 1 管理员 2普通员工
      prop: "type",
      rules: [{ required: true, message: "请选择身份", trigger: "change" }],
      attrs: {
        placeholder: "身份", // 1 管理员 2普通员工
      },
    },
  ],
  // 提交函数
  formAction: (data: UserFirmForm) => {
    if (data.id) {
      // 编辑
      return UserFirmAPI.update(data.id as string, data);
    } else {
      // 新增
      return UserFirmAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<UserFirmForm> = reactive({
  // permPrefix: "business:user-firm",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return UserFirmAPI.update(data.id as string, data);
  },
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "手机号",
        disabled: true, // 编辑时禁用手机号输入框
      },
      label: "手机号",
      prop: "phone",
    },
    {
      type: "select",
      label: "所属企业",
      prop: "firmId",
      attrs: {
        placeholder: "选择所属企业",
        style: {
          width: "200px",
        },
      },
      options: [],
      async initFn(item) {
        try {
          // 调用接口获取充电站数据
          const response = await UserFirmAPI.getFirmList();
          if (Array.isArray(response)) {
            item.options = response.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }
        } catch (error) {
          console.error("Failed to fetch data:", error);
        }
      },
    },
    {
      type: "custom",
      label: "身份",
      prop: "type",
      rules: [{ required: true, message: "请选择身份", trigger: "change" }],
      attrs: {
        placeholder: "身份",
      },
    },
  ], // 复用新增的表单项
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      return await UserFirmAPI.getFormData(data.row.id);
    });
  }
};

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

// 排序参数
const sortParams = reactive({
  sortField: "",
  sortOrder: "",
});

// 处理排序变化
const handleSortChange = (data: { prop: string; order: string | null }) => {
  sortParams.sortField = data.prop || "";
  sortParams.sortOrder = data.order || "";
  // 带着排序参数重新查询
  contentRef.value?.fetchPageData({ ...sortParams });
};
</script>

<style scoped>
.money-text {
  font-weight: bold;
  font-size: 13px;
}
.money-text.primary {
  color: #409eff;
}
.money-text.success {
  color: #67c23a;
}
.money-text.danger {
  color: #f56c6c;
}
.money-text.warning {
  color: #e6a23c;
}
</style>
