<template>
  <LjFoldLayout ref="LjFoldLayoutRef" v-bind="layoutSetting">
    <div class="main-box flx-col">
      <LjVxeTable
        ref="vxeTableRef"
        row-key="bednetid"
        :columns="columns"
        :init-param="initParams"
        :request-api="getData"
        :data-callback="dataCallback"
        :dwname="DwnameEnum.bednetQuote"
        :table-props="tableProps"
        :table-events="tableEvents"
        :auto-load-layout="false"
        :search-btn-size-extent="[]"
        pagination
        @on-mounted-data="autoMonthedData"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <LjHeaderMenu :update="dialogVisible" :action="action" />
          <!-- <el-button-group>
              <el-button @click="toAdd">{{ $t("common.add") }}</el-button>
              <el-button @click="toDel">{{ $t("common.delText") }}</el-button>
              <el-button @click="toA">{{ $t("common.auditFinance") }}</el-button>
              <el-button @click="toAdd">{{ $t("common.copyQuote") }}</el-button>
              <el-button @click="toAdd">{{ $t("common.businessOrder") }}</el-button>
              <el-button @click="toAdd">{{ $t("common.viewHistoricalQuotes") }}</el-button>
            </el-button-group> -->
        </template>
      </LjVxeTable>
    </div>
    <template #right>
      <div class="main-box flx card">
        <LjVxeTable
          ref="vxeTableMxRef"
          row-key="bednetmxid"
          table-cls="overflow-hidden pr-16"
          :columns="columnsMx"
          :init-param="initParamsMx"
          :request-api="getDataMx"
          :data-callback="dataCallbackMx"
          :dwname="DwnameEnum.bednetQuoteMx"
          :table-props="tableProps"
          :table-events="tableEventsMx"
          :auto-load-layout="false"
          :search-btn-size-extent="[]"
          collapseButtons
          :request-auto="false"
        >
          <template #tableHeader>
            <LjHeader class="flx-1" title="床网多网明细" />
          </template>
        </LjVxeTable>
        <div class="flx flx-shrink h-full" style="min-width: 542px">
          <LjVxeTable
            ref="vxeTableMxSpringRef"
            row-key="bednetmx_partid"
            table-cls=""
            :columns="columnsMxSpring"
            :init-param="initParamsMxSpring"
            :request-api="getDataMxSpring"
            :data-callback="dataCallback"
            :dwname="DwnameEnum.bednetQuoteMxSpring"
            :table-props="tableProps"
            :auto-load-layout="false"
            :search-btn-size-extent="[]"
            collapseButtons
            :request-auto="false"
          >
            <template #tableHeader>
              <LjHeader class="flx-1" title="多区袋装明细" />
            </template>
          </LjVxeTable>
        </div>
      </div>
    </template>
  </LjFoldLayout>
</template>

<script setup lang="ts" name="bednetQuote">
import { ref, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { AuditBedNet, DeleteBedNet } 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 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 LjFoldLayout from "@/components/LjFoldLayout/index.vue";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const {
  columns,
  columnsMx,
  columnsMxSpring,
  initParams,
  initParamsMx,
  initParamsMxSpring,
  getData,
  getDataMx,
  getDataMxSpring,
  dataCallback,
  dataCallbackMx
} = useHooks();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const dialogVisible = ref(false);
const vxeTableRef = ref();
const vxeTableMxRef = ref();
const vxeTableMxSpringRef = ref();

const LjFoldLayoutRef = ref();

const layoutSetting = {
  dwname: DwnameEnum.bednetQuote,
  direction: "vertical",
  right: {
    // hidden: true
  }
};

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

const handleClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  initParamsMx.value.arg_bednetid = row.bednetid;
};

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  if (row.flag == "0") {
    return "vxecol-danger";
  }
  return "";
};

const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowClassName: rowClsNameFunc
  // exportConfig: {
  //   filename: t("menu.saletaskmx") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  // }
};

const autoMonthedData = (data: any) => {
  const $table = vxeTableRef.value.element;
  console.log("autoMonthedData 123:>> ", $table);

  if ($table) {
    let { fullData } = $table.getTableData();
    console.log("object :>> ", $table.getTableData());

    if (fullData.length > 0) {
      $table.setCurrentRow(fullData[0]);
      initParamsMx.value.arg_bednetid = fullData[0].bednetid;
    }
  }
};

const handleClickTableMx = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  initParamsMxSpring.value.arg_bednetmxid = row.bednetmxid;
};

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

// 返回绑定的事件
const tableEventsMx = {
  "cell-click": handleClickTableMx
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 62,
    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(`/bednetQuote/new?id=0&deptid=${_deptid}`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 62,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

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

      const _cur = $table.getCurrentRecord() ?? null;
      console.log("_cur!!! :>> ", _cur);
      if (_cur) {
        router.push(`/bednetQuote/edit?id=${_cur.bednetid}&code=${_cur.bednetcode}`);
      } else {
        const _cur = curRecords[curRecords.length - 1];
        router.push(`/bednetQuote/edit?id=${_cur.bednetid}&code=${_cur.bednetcode}`);
      }
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 76,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(76)) {
        return "你没有【报价单-删除】的使用权限";
      }

      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);
      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      ElMessageBox.confirm(`是否确定要删除${curRecords.length}张报价单吗?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let list = curRecords.map((item: any) => {
            return { bednetid: Number(item.bednetid) };
          });
          DeleteBedNet({ list }).then(() => {
            ElMessage.success("删除成功！");
            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  [
    buttonDefault({
      label: t("common.auditText"),
      power: 63,
      disabledTextCallBack: (data: any) => {
        if (!CheckPower(63)) {
          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 { bednetid: Number(item.bednetid) };
            });
            AuditBedNet({ list, type: 1 }).then(() => {
              ElMessage.success("审核成功！");

              vxeTableRef.value.refresh();
            });
          })
          .catch((e: TypeError) => {
            ElMessage({
              type: "info",
              message: "操作取消"
            });
          });
      }
    }),
    buttonDefault({
      label: t("common.withdrawAuditText"),
      power: 64,
      disabledTextCallBack: (data: any) => {
        if (!CheckPower(64)) {
          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 { bednetid: Number(item.bednetid) };
            });
            AuditBedNet({ list, type: 0 }).then(() => {
              ElMessage.success("撤审成功！");

              vxeTableRef.value.refresh();
            });
          })
          .catch((e: TypeError) => {
            ElMessage({
              type: "info",
              message: "操作取消"
            });
          });
      }
    })
  ],
  buttonDefault({
    label: t("common.copyQuote"),
    clickFunc: item => {
      router.push(`/bednetQuote/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: 61,
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.recalculateFromNotFlag"),
    power: 61,
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    power: 61,
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.showQuoteList"),
    power: 61,
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 61,
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  })
];
</script>
