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

<script setup lang="ts" name="mattressQuote">
import { ref, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { SaveMattressAuditing, DelMattress } from "@/api/modules/quote";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
// import PriceListDetail from "./detail.vue";
import { useHooks } from "./hooks/index";
import { useHooksCpQuote } from "./hooks/cpQuote";
import LjDialog from "@/components/LjDialog/index.vue";
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 mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import { getCurrentRecords } from "@/utils/index";
import * as Exceljs from "exceljs";
import { saveAs } from "file-saver";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const { columns, dataCallback } = useHooks();
const { toExcelQuote } = useHooksCpQuote();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const initParams = ref({});
const dialogVisible = ref(false);
const vxeTableRef = ref();

const getData = (params: any) => {
  console.log("getData mattress params :>> ", params);
  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);
  switch (_params.status_flag) {
    case "1": // 待下单
      _params.arg_xd_flag = 0;
      break;
    case "2": // 已下单
      _params.arg_xd_flag = 1;
      break;
    case "3": // 待财务审核
      _params.arg_cp_flag = 1;
      _params.arg_flag = 0;
      break;
    case "4": // 已财务审核
      _params.arg_flag = 1;
      break;
    default:
      break;
  }
  newParams.queryParams = _params;
  newParams.dsname = "web_mattress";

  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuote);
  // return [];
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/mattressQuote/detail`,
      query: {
        id: row.mattressid,
        code: row.mattresscode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // if (currentLayout.value.right.hidden && globalStore.mxFloat?.includes("custCrmDetail")) {
    //   // 弹窗
    //   mainData.value = row;
    //   LjDrawerRef.value.show();
    // } else {
    // 打开新的标签页
    router.push(`/mattressQuote/detail?id=${row.mattressid}&code=${row.mattresscode}`);
    // }
  }
};

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

// 返回绑定的事件
const tableEvents = {
  // "checkbox-change": handleCheckboxChange,
  // "checkbox-all": handleCheckboxChange,
  // "checkbox-range-change": handleCheckboxChange,
  // "current-change": handleCurrentChanged
  "cell-dblclick": handleDBlClickTable
  // "cell-click": handleClickTable
};

onMounted(() => {
  dialogVisible.value = true;
});

/**
 * @description 业务下单或财务审核操作
 * @param params 对象，入参
 */
const toAuditing = (params: any, message: string) => {
  const { curRecords } = getCurrentRecords(vxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

  ElMessageBox.confirm(`是否确定要对${curRecords.length}张床垫报价单进行操作`, "询问", {
    confirmButtonText: message,
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      let _params = {
        ...params,
        mattressids: _mattressids
      };
      SaveMattressAuditing(_params).then(() => {
        ElMessage.success(t("sys.api.operationSuccess"));

        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 72,
    clickFunc: item => {
      console.log("inewss   nitParams.value :>> ", vxeTableRef.value.searchParam);
      let _deptid = 0;
      if (Object.keys(vxeTableRef.value.searchParam).includes("arg_deptid")) {
        _deptid = vxeTableRef.value.searchParam.arg_deptid;
      }
      router.push(`/mattressQuote/new?id=0&deptid=${_deptid}`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 72,
    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(`/mattressQuote/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
      } else {
        const _cur = curRecords[curRecords.length - 1];
        router.push(`/mattressQuote/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
      }
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 77,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(77)) {
        return "你没有【报价单-删除】的使用权限";
      }

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

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

      ElMessageBox.confirm(`是否确定要删除${curRecords.length}张床垫报价单吗?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          DelMattress({ mattressids: _mattressids }).then(() => {
            ElMessage.success("删除成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.copyQuote"),
    power: 75,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  [
    buttonDefault({
      label: t("common.businessOrder"),
      power: 94,
      clickFunc: item => {
        toAuditing({ xd_flag: 1 }, t("common.businessOrder"));
      }
    }),
    buttonDefault({
      label: t("common.businessOrderCancel"),
      power: 95,
      clickFunc: item => {
        toAuditing({ xd_flag: 0 }, t("common.businessOrder"));
      }
    })
  ],
  [
    buttonDefault({
      label: t("common.auditFinance"),
      power: 73,
      clickFunc: item => {
        toAuditing({ flag: 1 }, t("common.auditFinance"));
      }
    }),
    buttonDefault({
      label: t("common.withdrawAuditFinance"),
      power: 74,
      clickFunc: item => {
        toAuditing({ flag: 0 }, t("common.withdrawAuditFinance"));
      }
    })
  ],
  buttonDefault({
    label: t("common.copyFromMulitFlag"),
    power: 72,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.recalculateFromNotFlag"),
    power: 72,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    power: 72,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.showQuoteList"),
    power: 72,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 72,
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.businessSupplement"),
    power: 72,
    clickFunc: item => {
      toExcelQuote(vxeTableRef.value, "aces测试");
    }
  }),
  buttonDefault({
    label: t("common.recalculateERPCost"),
    power: 72,
    clickFunc: item => {
      const $table = vxeTableRef.value.element;

      // 自定义内容
      const customContent = [
        ["公司名称", "XX科技有限公司"],
        ["地址", "XX市XX区XX路XX号"],
        ["联系方式", "000-0000000"]
      ];
      // 导出表格数据
      $table.exportData({
        filename: "导出的文件",
        sheetName: "Sheet1",
        type: "csv",
        data: vxeTableRef.value._mainData,
        original: false,
        columnFilterMethod({ column }) {
          // 可以在这里过滤不需要导出的列
          return true;
        },
        getCellFormat({ cellValue, cellColumn }) {
          // 可以在这里自定义单元格格式
          return cellValue;
        },
        footerFilterMethod() {
          // 返回自定义的底部内容
          return customContent;
        }
      });
    }
  })
];

/**
 * @description 监听框架属性变化
 */
mittBus.on(MittEnum.MattressList, () => {
  vxeTableRef.value.refresh();
});
</script>
