<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 { MattressYWAudit, MattressJSAudit, MattressJS2Audit } from "@/api/modules/quote";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.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";

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

const dialogVisible = ref(false);
const vxeTableRef = ref();
const enumMap = ref(new Map());

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_mattress_interfacelist";

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

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

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  if (Number(row.flag) == 0) {
    if (Number(row.xd_flag) == 0) {
      return "vxecol-danger";
    }
    if (Number(row.xd_flag) == 1) {
      return "vxecol-blue";
    }
  }
  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
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.view"),
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);
      // vxeTableRef.value.refresh();
      handleDBlClickTable({ row: curRecords[0] });
    }
  }),
  [
    buttonDefault({
      label: "业务补充",
      power: 79,
      clickFunc: item => {
        routeToEdit(1);
      }
    }),
    buttonDefault({
      label: "业务审核",
      power: 80,
      clickFunc: item => {
        YWAudit(1);
      }
    }),
    buttonDefault({
      label: "业务撤审",
      power: 81,
      clickFunc: item => {
        YWAudit(0);
      }
    })
  ],
  [
    buttonDefault({
      label: "产品补充",
      power: 82,
      clickFunc: item => {
        routeToEdit(2);
      }
    }),
    buttonDefault({
      label: "产品补充审核",
      power: 83,
      clickFunc: item => {
        JSAudit(1);
      }
    }),
    buttonDefault({
      label: "产品补充撤审",
      power: 84,
      clickFunc: item => {
        JSAudit(0);
      }
    })
  ],
  [
    buttonDefault({
      label: "清单补充",
      power: 85,
      clickFunc: item => {
        routeToEdit(3);
      }
    }),
    buttonDefault({
      label: "清单补充审核",
      power: 86,
      clickFunc: item => {
        JS2Audit(1);
      }
    }),
    buttonDefault({
      label: "清单补充撤审",
      power: 87,
      clickFunc: item => {
        JS2Audit(0);
      }
    })
  ],
  [
    buttonDefault({
      label: "生成金蝶清单",
      power: 90,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

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

        toCreateORDelMtrlPf(1, curRecords[curRecords.length - 1].mattressid);
      }
    }),
    buttonDefault({
      label: "删除金蝶清单",
      power: 91,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

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

        toCreateORDelMtrlPf(0, curRecords[curRecords.length - 1].mattressid);
      }
    })
  ]
];

const dataCallback = (data: any) => {
  if (data.tableinfo?.columns) {
    data.tableinfo?.columns.map((item: any) => {
      if (item?.enum) {
        enumMap.value.set(item.field, item.enum);
      }
    });
  }
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const YWAudit = type => {
  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 {
      mattressid: Number(item.mattressid)
    };
  });
  ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
    confirmButtonText: t("common.okText"),
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      MattressYWAudit({ list, type }).then(() => {
        ElMessage.success(`业务${type ? "审核" : "撤审"}成功！`);
        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const JSAudit = type => {
  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 {
      mattressid: Number(item.mattressid)
    };
  });
  ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
    confirmButtonText: t("common.okText"),
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      MattressJSAudit({ list, type }).then(() => {
        ElMessage.success(`产品补充${type ? "审核" : "撤审"}成功！`);
        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const JS2Audit = type => {
  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 {
      mattressid: Number(item.mattressid)
    };
  });
  ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
    confirmButtonText: t("common.okText"),
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      MattressJS2Audit({ list, type }).then(() => {
        ElMessage.success(`清单补充${type ? "审核" : "撤审"}成功！`);
        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const routeToEdit = type => {
  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(`/erpapi/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);
  } else {
    const _cur = curRecords[curRecords.length - 1];
    router.push(`/erpapi/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);
  }
};

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