<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>
</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";
import { usePageRouter } from "@/hooks/usePageRouter";

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

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

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: 152,
    clickFunc: item => {
      router.push(`/softbedQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 152,
    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;
      }
      pageOpen({
        name: "softbedQuoteEdit",
        params: {
          id: _cur.softbed_id,
          code: _cur.softbed_code
        },
        query: {
          id: _cur.softbed_id,
          code: _cur.softbed_code
        }
      });
      // router.push(`/softbedQuote/edit?id=${_cur.softbed_id}&code=${_cur.softbed_code}`);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 155,
    loading: () => loadingStatus.value.delete,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(155)) {
        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: 153,
    loading: () => loadingStatus.value.audit,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(153)) {
        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: 154,
    loading: () => loadingStatus.value.caudit,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(154)) {
        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 => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 61,
    clickFunc: item => {
      alert("功能维护中!");
    }
  })
];
</script>
