<template>
  <div class="table-box">
    <LjVxeTable
      ref="vxeTableRef"
      row-key="mattressid"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.semifinprodQuote"
      :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="semifinprodQuote">
import { ref, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { AuditMattressBcp, DeleteMattressBcp } 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/index2";
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, orderStatus } = useHooks();
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);
  newParams.queryParams = _params;
  newParams.dsname = "web_semi_finished_productlist";

  return CommonDynamicSelect(newParams, DwnameEnum.semifinprodQuote);
};

const dataCallback = (data: any) => {
  console.log("data :>> ", data);
  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: `/semifinprodQuote/detail`,
      query: {
        id: row.billid,
        code: row.billcode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // if (currentLayout.value.right.hidden && globalStore.mxFloat?.includes("custCrmDetail")) {
    //   // 弹窗
    //   mainData.value = row;
    //   LjDrawerRef.value.show();
    // } else {
    // 打开新的标签页
    router.push(`/semifinprodQuote/detail?id=${row.billid}&code=${row.billcode}`);
    // }
  }
};

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: 124,
    clickFunc: item => {
      router.push(`/semifinprodQuote/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 = $table.getCurrentRecord() ?? null;
      if (_cur) {
        router.push(`/semifinprodQuote/edit?id=${_cur.billid}&code=${_cur.billcode}`);
      } else {
        const _cur = curRecords[curRecords.length - 1];
        router.push(`/semifinprodQuote/edit?id=${_cur.billid}&code=${_cur.billcode}`);
      }
    }
  }),
  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);
      ElMessageBox.confirm("是否确定要审核单据吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let list = curRecords.map((item: any) => {
            return { billid: Number(item.billid) };
          });
          AuditMattressBcp({ list, type: 1 }).then(() => {
            ElMessage.success("审核成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  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);
      ElMessageBox.confirm("是否确定要撤审单据吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let list = curRecords.map((item: any) => {
            return { billid: Number(item.billid) };
          });
          AuditMattressBcp({ list, type: 0 }).then(() => {
            ElMessage.success("撤审成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 127,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(127)) {
        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 list = curRecords.map((item: any) => {
        return { billid: Number(item.billid) };
      });

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

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

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