<template>
  <div class="table-box">
    <LjVxeTable
      ref="VxeTableRef"
      row-key="softbed_id"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.softbedQuote"
      :table-props="tableProps"
      :table-events="tableEvents"
      :auto-load-layout="false"
      :search-btn-size-extent="[]"
      pagination
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <LjHeaderMenu :action="action" />
      </template>
    </LjVxeTable>
  </div>

  <BedConfigModal
    v-model="isModalVisible"
    v-model:showHeadboard="showHeadboard"
    v-model:showNightstand="showNightstand"
    v-model:showBedframe="showBedframe"
    v-model:partsConfig="partsConfig"
    :configItemOptions="allConfigItemOptions"
    :configValueOptionsMap="configValueOptionsMap"
    @submit="handleConfirm"
  />
</template>

<script setup lang="ts" name="softbedQuote">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { CommonDynamicSelect } from "@/api/modules/common";
import { useHooks } from "./hooks/index";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useI18n } from "vue-i18n";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { formatToDateTime, formatToDate } from "@/utils/dateUtil";
import { cloneDeep } from "lodash-es";
import { useGlobalStore } from "@/stores/modules/global";
import { ElMessage, ElMessageBox } from "element-plus";
import { detailAction } from "@/components/LjDetail/interface";
import { useUserStore } from "@/stores/modules/user";
import { getCurrentRecords } from "@/utils/index";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const { columns, orderStatus, VxeTableRef, initParams, onAudit, onCAudit, onDelete, onShowFormula } = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
const { userInfo } = useUserStore();

const allConfigItemOptions = reactive([
  { pzid: 101, pzname: "颜色" },
  { pzid: 201, pzname: "材质" },
  { pzid: 301, pzname: "款式" },
  { pzid: 401, pzname: "尺寸" },
  { pzid: 501, pzname: "填充物" },
  { pzid: 601, pzname: "靠背调节" }
]);

const configValueOptionsMap = reactive({
  101: [
    { printid: 1, pznamemx: "白色" },
    { printid: 2, pznamemx: "红色" }
  ],
  201: [
    { printid: 1, pznamemx: "皮质" },
    { printid: 2, pznamemx: "布艺" }
  ],
  301: [{ printid: 1, pznamemx: "简约款" }],
  401: [{ printid: 1, pznamemx: "1.8米" }],
  501: [{ printid: 1, pznamemx: "记忆棉" }],
  601: [{ printid: 1, pznamemx: "不可调节" }]
});

// 父组件维护 partsConfig，Modal 每次打开都会使用同一个对象（记忆性）
const partsConfig = reactive({
  headboard: [
    { pzid: 101, selectedValue: "白色" },
    { pzid: 201, selectedValue: "皮质" }
  ],
  nightstand: [
    { pzid: 101, selectedValue: "白色" },
    { pzid: 301, selectedValue: "欧式款" }
  ],
  bedframe: [
    { pzid: 101, selectedValue: "灰色" },
    { pzid: 401, selectedValue: "1.8米" }
  ]
});

const showHeadboard = ref(true);
const showNightstand = ref(true);
const showBedframe = ref(true);

// 控制弹窗的显示状态
const isModalVisible = ref(false);

const getData = (params: any) => {
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  params.orderstr && (newParams.orderstr = params.orderstr);
  delete params.pageNum;
  delete params.pageSize;
  delete params.orderstr;
  let _params = cloneDeep(params);
  newParams.queryParams = _params;
  newParams.dsname = "web_softbed_list";
  return CommonDynamicSelect(newParams, DwnameEnum.softbedQuote);
};

const dataCallback = (data: any) => {
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  //
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/softbedQuote/detail`,
      query: {
        id: row.softbed_id,
        code: row.softbed_code
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // 打开新的标签页
    router.push(`/softbedQuote/detail?id=${row.softbed_id}&code=${row.softbed_code}`);
  }
};

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  return "";
};
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowClassName: rowClsNameFunc,
  exportConfig: {
    filename: t("menu.softbedQuote") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  }
};

// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      VxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 124,
    clickFunc: item => {
      router.push(`/softbedQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 124,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(VxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      const _cur = curRecords[curRecords.length - 1];
      if (_cur.flag == 1) {
        ElMessage.warning("单据已审核，不能修改");
        return;
      }
      router.push(`/softbedQuote/edit?id=${_cur.softbed_id}&code=${_cur.softbed_code}`);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 127,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(127)) {
        return "你没有【报价单-删除】的使用权限";
      }

      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(VxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let list = curRecords.map((item: any) => {
        return { softbed_id: Number(item.softbed_id) };
      });

      onDelete(list);
    }
  }),
  buttonDefault({
    label: t("common.auditText"),
    power: 125,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(125)) {
        return `你没有【报价单-${t("common.auditText")}】的使用权限`;
      }
      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(VxeTableRef.value);
      let list = curRecords.map((item: any) => {
        return { softbed_id: Number(item.softbed_id) };
      });
      onAudit(list, () => {
        VxeTableRef.value.refresh();
      });
    }
  }),
  buttonDefault({
    label: t("common.withdrawAuditText"),
    power: 125,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(125)) {
        return `你没有【报价单-${t("common.withdrawAuditText")}】的使用权限`;
      }
      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(VxeTableRef.value);
      let list = curRecords.map((item: any) => {
        return { softbed_id: Number(item.softbed_id) };
      });
      onCAudit(list),
        () => {
          VxeTableRef.value.refresh();
        };
    }
  }),
  buttonDefault({
    label: t("common.copyQuote"),
    power: 75,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(VxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      const _cur = $table.getCurrentRecord() ?? null;
      if (_cur) {
        router.push(`/softbedQuote/copy?id=${_cur.softbed_id}&code=${_cur.softbed_code}`);
      } else {
        const _cur = curRecords[curRecords.length - 1];
        router.push(`/softbedQuote/copy?id=${_cur.softbed_id}&code=${_cur.softbed_code}`);
      }
    }
  }),
  buttonDefault({
    label: t("common.showFormula"),
    disabledTextCallBack: () => {
      return userInfo.usermode == 1 ? "业务员模式不可以查看！" : "";
    },
    clickFunc: item => {}
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    power: 61,
    clickFunc: item => {}
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 61,
    clickFunc: item => {}
  })
];

const handleConfirm = data => {
  isModalVisible.value = false;
  console.log("showHeadboard :>>", showHeadboard);
  console.log("showNightstand :>>", showNightstand);
  console.log("showBedframe :>>", showBedframe);
  console.log("partsConfig :>>", data);
};
</script>
