<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 #status="scope">
        <el-tag :type="scope.row.status == 0 ? 'warning' : 'success'">
          {{ scope.row.status == 0 ? "已下线" : "上线中" }}
        </el-tag>
      </template>
      <template #firmType="scope">
        <el-tag :type="scope.row.firmType === 1 ? 'primary' : 'info'">
          {{ scope.row.firmType === 1 ? "企业" : "渠道" }}
        </el-tag>
      </template>
      <template #balance="scope">
        <span class="money-text primary">¥ {{ formatMoney(scope.row.balance) }}</span>
      </template>
      <template #totalRecharge="scope">
        <span class="money-text success">¥ {{ formatMoney(scope.row.totalRecharge) }}</span>
      </template>
      <template #currentProfit="scope">
        <span :class="['money-text', scope.row.currentProfit >= 0 ? 'success' : 'danger']">
          {{ scope.row.currentProfit >= 0 ? "+" : "" }}¥ {{ formatMoney(scope.row.currentProfit) }}
        </span>
      </template>
      <template #totalProfit="scope">
        <span :class="['money-text', scope.row.totalProfit >= 0 ? 'success' : 'danger']">
          {{ scope.row.totalProfit >= 0 ? "+" : "" }}¥ {{ formatMoney(scope.row.totalProfit) }}
        </span>
      </template>
    </page-content>

    <!-- 新增 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增"
      width="500px"
      draggable
      @close="handleAddDialogClose"
    >
      <el-form ref="addFormRef" :model="addFormData" :rules="addFormRules" label-width="100px">
        <el-form-item label="类型" prop="firmType">
          <el-radio-group v-model="addFormData.firmType" @change="handleFirmTypeChange">
            <el-radio :value="1">企业</el-radio>
            <el-radio :value="2">渠道</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="deptId">
          <el-tree-select
            v-model="addFormData.deptId"
            :data="availableDeptOptions"
            :props="{ label: 'label', value: 'value', children: 'children' }"
            placeholder="请选择部门"
            check-strictly
            filterable
            clearable
            style="width: 100%"
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addFormData.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="handleAddSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    ></page-modal>
    <el-dialog v-model="dialogTableVisible" title="查看邀请码" width="500px">
      <div class="relative">
        <div>
          <el-image :src="qrCode_bg" fit="cover" style="width: 100%; height: 100%" />
        </div>
        <div class="absolute top-1.42/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
          <qr-code
            :value="'https://cd.api.zswlgz.com/deviceid?frimId=' + firmId"
            width="170"
            :color="{ dark: '#1D6AEC' }"
            margin="3"
          />
        </div>
      </div>
      <template #footer>
        <el-button type="primary" :loading="downloadLoading" @click="dowloadQrCode">下载</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 上账/下账弹窗 -->
    <el-dialog
      v-model="balanceDialogVisible"
      :title="balanceDialogType === 1 ? '上账（充值）' : '下账（扣款）'"
      width="500px"
    >
      <el-form
        ref="balanceFormRef"
        :model="balanceForm"
        :rules="balanceFormRules"
        label-width="100px"
      >
        <el-form-item label="企业名称">
          <el-input v-model="balanceForm.firmName" disabled />
        </el-form-item>
        <el-form-item label="当前余额">
          <el-input v-model="balanceForm.currentBalance" disabled>
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="balanceDialogType === 1 ? '上账金额' : '下账金额'" prop="amount">
          <el-input-number
            v-model="balanceForm.amount"
            :min="0.01"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="balanceForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="balanceDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="balanceLoading" @click="handleBalanceSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "FirmInfo" });
import qrCode_bg from "@/assets/images/qrCode_bg.jpg";
import qrCode from "vue-qrcode";
import FirmInfoAPI, { FirmInfoForm, FirmInfoPageQuery } from "@/api/toBManage/firm-info-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import html2canvas from "html2canvas";
import { ElMessage } from "element-plus";
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);
});

// 可用部门选项
const availableDeptOptions = ref<OptionType[]>([]);

// 加载可用部门选项
const loadAvailableDeptOptions = async (excludeId?: number) => {
  try {
    availableDeptOptions.value = await FirmInfoAPI.getAvailableDeptOptions(excludeId);
  } catch (error) {
    console.error("加载部门选项失败:", error);
  }
};

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

// 新增弹窗相关
const addDialogVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref();
const addFormData = reactive<FirmInfoForm>({
  firmType: 1,
  deptId: undefined,
  name: "",
  status: 1,
});
const addFormRules = {
  firmType: [{ required: true, message: "请选择类型", trigger: "change" }],
  deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
};

// 点击新增按钮
const handleAddClick = async () => {
  // 重置表单
  addFormData.firmType = 1;
  addFormData.deptId = undefined;
  addFormData.name = "";
  addFormData.status = 1;
  // 加载可用部门
  await loadAvailableDeptOptions();
  addDialogVisible.value = true;
};

// 关闭新增弹窗
const handleAddDialogClose = () => {
  addFormRef.value?.resetFields();
};

// 类型变化时重新加载部门选项
const handleFirmTypeChange = () => {
  addFormData.deptId = undefined;
  addFormData.name = "";
};

// 部门选择变化
const handleDeptChange = (deptId: number) => {
  // 查找选中的部门名称
  const findDeptName = (options: OptionType[], id: number): string | undefined => {
    for (const opt of options) {
      if (opt.value === id) {
        return opt.label;
      }
      if (opt.children && opt.children.length > 0) {
        const found = findDeptName(opt.children, id);
        if (found) return found;
      }
    }
    return undefined;
  };
  const deptName = findDeptName(availableDeptOptions.value, deptId);
  addFormData.name = deptName || "";
};

// 提交新增
const handleAddSubmit = async () => {
  if (!addFormRef.value) return;
  await addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      addLoading.value = true;
      try {
        await FirmInfoAPI.create(addFormData);
        ElMessage.success("新增成功");
        addDialogVisible.value = false;
        handleQueryClick();
      } catch (error) {
        console.error("新增失败:", error);
      } finally {
        addLoading.value = false;
      }
    }
  });
};

// 金额格式化函数
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:firm-info",
  formItems: [
    {
      type: "select",
      label: "类型",
      prop: "firmType",
      attrs: {
        placeholder: "请选择类型",
        clearable: true,
        style: { width: "150px" },
      },
      options: [
        { label: "企业", value: 1 },
        { label: "渠道", value: 2 },
      ],
    },
    {
      type: "input",
      label: "名称",
      prop: "name",
      attrs: {
        placeholder: "企业/渠道名称",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select",
      label: "状态", // 0 已下线  1 上线中
      prop: "status",
      attrs: {
        placeholder: "请输入状态",
        clearable: true,
        style: { width: "200px" },
      },
      options: [
        { label: "已下线", value: 0 },
        { label: "上线中", value: 1 },
      ],
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<FirmInfoPageQuery> = reactive({
  // 权限前缀
  // permPrefix: "business:firm-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: FirmInfoAPI.getPage,
  // 删除接口
  deleteAction: FirmInfoAPI.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: "customAdd",
      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: 55, align: "center" },
    {
      label: "类型",
      prop: "firmType",
      width: 80,
      templet: "custom",
      slotName: "firmType",
    },
    { label: "名称", prop: "name" },
    { label: "员工数", prop: "empNum", width: 80 },
    {
      label: "当前余额",
      prop: "balance",
      width: 120,
      templet: "custom",
      slotName: "balance",
    },
    {
      label: "累计充值",
      prop: "totalRecharge",
      width: 120,
      templet: "custom",
      slotName: "totalRecharge",
    },
    {
      label: "当前盈利",
      prop: "currentProfit",
      width: 120,
      templet: "custom",
      slotName: "currentProfit",
    },
    {
      label: "累计盈利",
      prop: "totalProfit",
      width: 120,
      templet: "custom",
      slotName: "totalProfit",
    },
    {
      label: "状态", // 0 已下线  1 上线中
      prop: "status",
      width: 90,
      templet: "custom",
    },
    { label: "创建时间", prop: "createTime", width: 170 },
    {
      label: "操作",
      prop: "operation",
      width: 280,
      templet: "tool",
      operat: [
        {
          name: "recharge",
          text: "上账",
          attrs: () => ({
            type: "success",
            icon: "Plus",
            link: true,
            size: "small",
            disabled: isSfUser.value,
          }),
        },
        {
          name: "deduct",
          text: "下账",
          attrs: () => ({
            type: "warning",
            icon: "Minus",
            link: true,
            size: "small",
            disabled: isSfUser.value,
          }),
        },
        {
          name: "qrCode",
          text: "邀请码",
          attrs: () => ({
            type: "primary",
            icon: "Setting",
            link: true,
            size: "small",
            disabled: isSfUser.value,
          }),
          show: (row: any) => row.firmType === 1, // 仅企业类型显示邀请码
        },
        {
          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<FirmInfoForm> = reactive({
  // 权限前缀
  // permPrefix: "business:firm-info",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "radio",
      label: "类型",
      prop: "firmType",
      initialValue: 1,
      options: [
        { label: "企业", value: 1 },
        { label: "渠道", value: 2 },
      ],
    },
    {
      type: "input",
      attrs: {
        placeholder: "名称",
      },
      label: "名称",
      prop: "name",
    },
    {
      type: "switch",
      attrs: {
        activeValue: 1,
        inactiveValue: 0,
      },
      initialValue: 1,
      label: "状态", // 0 已下线  1 上线中
      prop: "status",
    },
  ],
  // 提交函数
  formAction: (data: FirmInfoForm) => {
    if (data.id) {
      // 编辑
      return FirmInfoAPI.update(data.id as string, data);
    } else {
      // 新增
      return FirmInfoAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<FirmInfoForm> = reactive({
  // permPrefix: "business:firm-info",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return FirmInfoAPI.update(data.id as string, data);
  },
  formItems: addModalConfig.formItems, // 复用新增的表单项
});

// 处理操作按钮点击
const dialogTableVisible = ref(false);
const firmId = ref();
const firmName = ref();

// 上账/下账相关
const balanceDialogVisible = ref(false);
const balanceDialogType = ref(1); // 1-上账 2-下账
const balanceLoading = ref(false);
const balanceFormRef = ref();
const balanceForm = reactive({
  firmId: 0,
  firmName: "",
  currentBalance: 0,
  amount: 0,
  remark: "",
});
const balanceFormRules = {
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
};

const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      return await FirmInfoAPI.getFormData(data.row.id);
    });
  }
  if (data.name === "qrCode") {
    dialogTableVisible.value = true;
    firmId.value = parseInt(data.row.id);
    firmName.value = data.row.name;
  }
  if (data.name === "recharge") {
    balanceDialogType.value = 1;
    balanceForm.firmId = data.row.id;
    balanceForm.firmName = data.row.name;
    balanceForm.currentBalance = data.row.balance || 0;
    balanceForm.amount = 0;
    balanceForm.remark = "";
    balanceDialogVisible.value = true;
  }
  if (data.name === "deduct") {
    balanceDialogType.value = 2;
    balanceForm.firmId = data.row.id;
    balanceForm.firmName = data.row.name;
    balanceForm.currentBalance = data.row.balance || 0;
    balanceForm.amount = 0;
    balanceForm.remark = "";
    balanceDialogVisible.value = true;
  }
};

// 提交上账/下账
const handleBalanceSubmit = async () => {
  if (!balanceFormRef.value) return;
  await balanceFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      balanceLoading.value = true;
      try {
        if (balanceDialogType.value === 1) {
          await FirmInfoAPI.recharge(balanceForm.firmId, balanceForm.amount, balanceForm.remark);
          ElMessage.success("上账成功");
        } else {
          await FirmInfoAPI.deduct(balanceForm.firmId, balanceForm.amount, balanceForm.remark);
          ElMessage.success("下账成功");
        }
        balanceDialogVisible.value = false;
        // 刷新列表
        handleQueryClick();
      } catch (error) {
        console.error("操作失败:", error);
      } finally {
        balanceLoading.value = false;
      }
    }
  });
};

// 二维码海报下载
const downloadLoading = ref(false);
const dowloadQrCode = () => {
  downloadLoading.value = true;
  const qrCodeElement = document.querySelector(".relative") as HTMLElement;
  if (qrCodeElement) {
    html2canvas(qrCodeElement)
      .then((canvas) => {
        const link = document.createElement("a");
        link.download = `${firmName.value}_${firmId.value}.png`;
        link.href = canvas.toDataURL("image/png");
        link.click();
        downloadLoading.value = false;
        ElMessage.success("下载成功！");
      })
      .catch((error) => {
        downloadLoading.value = false;
        ElMessage.error("下载失败，请重试！");
        console.error("下载失败:", error);
      });
  } else {
    downloadLoading.value = false;
    ElMessage.error("未找到二维码元素！");
  }
};

// 处理工具栏按钮点击（删除等）
const handleToolbarClick = (name: string) => {
  if (name === "customAdd") {
    handleAddClick();
  }
};
</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>
