<template>
  <LjDetail
    name="rpMustPayCrmDetail"
    ref="LjDetailRef"
    v-bind="detailProps"
    :request-api="getData"
    :data-callback="dataCallback"
    :init-param="initParams"
    v-model:order-status="orderStatus"
    :action="orderDefaultAction"
    :after-mound="funcAfterMound"
    :if-layout-editable="false"
    :default-columns-value="defaultColumnsValue"
  >
    <template #bednetMx>
      <div class="main-box flx">
        <div
          class="flx flx-shrink h-full pr-16"
          style="min-width: 542px"
          v-if="bednetMxData.length && Number(LjDetailRef._mainData.bednettypeid) == 11 && Number(bednetMxData[0].if_part)"
        >
          <!-- v-if="bednetMxSprintData.length" -->
          <LjVxeTable
            ref="vxeTableMxSpringRef"
            row-key="bednetmx_partid"
            table-cls=""
            :columns="columnsMxSpring"
            :data="bednetMxSprintData"
            :dwname="DwnameEnum.bednetQuoteMxSpring"
            :table-props="tableProps_mx"
            :auto-load-layout="false"
            :tool-button="[]"
            :search-btn-size-extent="[]"
            collapseButtons
            :request-auto="false"
          >
            <template #tableHeader>
              <!-- <div class="flx"> -->
              <LjHeader class="flx-shrink" title="多区袋装明细" />
              <!-- <div class="flx-1 flx-end pb-8" v-if="AreaList.length">
                  <span class="text-secondary-text">比例设置</span>
                  <el-select v-model="currentArea" class="pl-4 pr-4" style="width: 80px" @change="setMxSpringLength">
                    <el-option
                      v-for="item in AreaList"
                      :key="item.areaname"
                      :label="item.areaname"
                      :value="item.areaname"
                    ></el-option>
                  </el-select>
                </div> -->
              <!-- </div> -->
            </template>
          </LjVxeTable>
        </div>
        <div class="h-full flx-1 overflow-hidden">
          <LjVxeTable
            v-if="bednetMxData.length"
            ref="vxeTableMxRef"
            row-key="bednetmxid"
            table-cls="h-full"
            :columns="columnsMx"
            :data="bednetMxData"
            :dwname="DwnameEnum.bednetQuoteMx"
            :table-props="tableProps_mx"
            :auto-load-layout="false"
            :search-btn-size-extent="[]"
            :request-auto="false"
            collapseButtons
          >
            <template #tableHeader>
              <LjHeader class="flx-1" title="床网多网明细" />
            </template>
          </LjVxeTable>
        </div>
      </div>
    </template>
  </LjDetail>

  <MtrldefDialog ref="MtrldefDialogRef" v-bind="MtrldefDialogProps" />
  <SpringDialog ref="SpringDialogRef" v-bind="SpringDialogProps" />
</template>

<script setup lang="ts" name="bednetQuoteDetail">
import { ref, watch, reactive, inject, nextTick, computed, onMounted, getCurrentInstance } from "vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import LjDetail from "@/components/LjDetail/index.vue";
import { DetailProp, detailAction } from "@/components/LjDetail/interface";
import { useI18n } from "vue-i18n";
import { useHooks } from "./hooks/index";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
// import { cloneDeep } from "lodash-es";
import { useRoute, useRouter } from "vue-router";
import { CommonDynamicSelect, GetFormulaCompute } from "@/api/modules/common";
import { SaveBedNet, AuditBedNet, DeleteBedNet } from "@/api/modules/quote";
// import ToastFormula from "@/components/ToastWidget/Formula/index.vue";
import { TYPE, useToast, POSITION } from "vue-toastification";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
// import { ArrowDown } from "@element-plus/icons-vue";
// import { calculateFormula } from "@/utils/index";
import MtrldefDialog from "@/views/system/selector/mtrldef/index.vue";
import SpringDialog from "@/views/system/selector/spring/index.vue";
// import LjDrawerQuoteList from "./components/QuoteList.vue";
// import mittBus from "@/utils/mittBus";
// import { MittEnum } from "@/enums/mittEnum";
// import { getCurrentRecords } from "@/utils/index";
import { useUserStore } from "@/stores/modules/user";
import { getBedNetAreaList } from "@/api/modules/basicinfo";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { userInfo } = useUserStore();
const {
  LjDetailRef,
  columns,
  columnsMx,
  columnsMxSpring,
  initParams,
  initParamsMx,
  initParamsMxSpring,
  orderStatus,
  bednetMxData,
  bednetMxSprintData,
  vxeTableMxRef,
  vxeTableMxSpringRef,
  MtrldefDialogRef,
  MtrldefDialogProps,
  SpringDialogRef,
  SpringDialogProps,
  currentArea,
  AreaList,
  dw_bednet_mx_spring,
  reload_dw2,
  getData,
  getDataMxAdd,
  getDataMxSpring,
  dataCallback,
  dataCallbackMx,
  wf_cmp_cb,
  setMxSpringLength
} = useHooks();

const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
// const toast = useToast();

// const orderStatus = ref("");
// const mainData = ref([]);
const tabRemove: Function = inject("tabRemove") as Function;

const defaultColumnsValue = ref<any>({});

/**
 * @description 明细表格组件基础配置
 */
const tableProps_mx = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "300px",
  editConfig: { trigger: "click", mode: "row", enabled: false },
  keyboardConfig: {
    isEdit: true,
    isArrow: true,
    isEnter: true,
    isTab: true,
    isDel: true,
    isBack: true,
    isEsc: true,
    editMethod({ $table, row, column }) {
      // 先清空原先的值
      row[column.field] = "";
      // 再激活编辑状态并输入新值
      $table.setEditCell(row, column);
    }
  },
  rowConfig: { isCurrent: false },
  mouseConfig: {
    selected: true
  }
});

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.bednetQuote,
  columns: columns,
  // headerstatus: ["status", "ifamt_ok"],
  basicDefault: {},
  header: {
    fieldNames: {
      code: "sptcode",
      codeLabel: t("table.u_spt.sptcode") + "：",
      name: "name"
    }
    // icon: "iconclipboard",
    // tabsProp: {
    //   scrollspy: true,
    //   sticky: true
    // }
    // floatbtn: [
    //   {
    //     id: "oaFlow",
    //     originLeft: 100,
    //     originTop: 50
    //   }
    // ]
  },
  mould: [
    {
      id: "bednetMx",
      type: "table",
      label: t("business.detail.bednetMxTitle")
    }
  ]
});

const loadingStatus = reactive({
  save: false
});

const orderDefaultAction: detailAction[] = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left",
    limited: () => {
      return !orderStatus.value;
    },
    clickFunc: item => {
      tabRemove(route.fullPath);
      if (route.path.indexOf("/new") > -1) {
        router.replace("/bednetQuote");
      } else {
        router.replace(
          `/bednetQuote/detail?id=${LjDetailRef.value._mainData.bednetid}&code=${LjDetailRef.value._mainData.bednetcode}`
        );
      }
    }
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    // loading: () => loadingStatus.save,
    limited: () => !orderStatus.value,
    clickFunc: async () => {
      console.log("save LjDetailRef.value :>> ", LjDetailRef.value);
      console.log("save LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
      console.log("save LjDetailRef.value.pp :>> ", LjDetailRef.value.infoParam);

      try {
        await LjDetailRef.value.toValidateForm();

        if (!(await wf_cmp_cb())) return;

        let bednet = LjDetailRef.value._mainData;
        bednet.ifsaleout = Number(bednet.ifsaleout);

        let bednetMx = vxeTableMxRef.value?.element.getTableData().fullData;

        let spring = vxeTableMxSpringRef.value?.element.getTableData().fullData ?? [];

        let _param_mf = {
          bednet,
          bednetMx,
          spring
        };
        try {
          console.log("综合 _param_mf :>> ", _param_mf);
          await SaveBedNet(_param_mf)
            .then(res => {
              ElNotification({
                title: "温馨提示",
                message: t("sys.api.sueccessToSave"),
                type: "success"
              });
              if (res.bednet.bednetid) {
                tabRemove(route.fullPath);
                router.replace(`/bednetQuote/detail?id=${res.bednet.bednetid}`);
              } else {
                router.replace("/bednetQuote");
              }
            })
            .catch(error => {
              console.log("error !! :>> ", error);
            });
        } catch (error) {
          ElMessage.error(t("sys.api.operationFailed"));
        }
      } catch (e) {
        ElMessage({
          type: "error",
          message: e.message
        });
      }
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 62,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      router.push(`/bednetQuote/new?id=0`);
    }
  }),
  buttonDefault({
    power: 72,
    label: t("common.editText"),
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      tabRemove(route.fullPath);
      router.replace(`/bednetQuote/edit?id=${LjDetailRef.value._mainData.bednetid}`);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 76,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(76)) {
        return "你没有【报价单-删除】的使用权限";
      }

      return "";
    },
    clickFunc: item => {
      ElMessageBox.confirm(`是否确定要删除该报价单吗?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let list = [LjDetailRef.value._mainData];

          DeleteBedNet({ list }).then(() => {
            ElMessage.success("删除成功！");

            LjDetailRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  [
    buttonDefault({
      label: t("common.auditText"),
      power: 63,
      limited: () => {
        return !!orderStatus.value;
      },
      disabledTextCallBack: (data: any) => {
        if (!CheckPower(63)) {
          return `你没有【报价单-${t("common.auditText")}】的使用权限`;
        }
        return "";
      },
      clickFunc: item => {
        ElMessageBox.confirm("是否确定要审核单据吗?", "询问", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning"
        })
          .then(() => {
            let list = [LjDetailRef.value._mainData];
            AuditBedNet({ list, type: 1 }).then(() => {
              ElMessage.success("审核成功！");

              LjDetailRef.value.refresh();
            });
          })
          .catch((e: TypeError) => {
            ElMessage({
              type: "info",
              message: "操作取消"
            });
          });
      }
    }),
    buttonDefault({
      label: t("common.withdrawAuditText"),
      power: 64,
      limited: () => {
        return !!orderStatus.value;
      },
      disabledTextCallBack: (data: any) => {
        if (!CheckPower(64)) {
          return `你没有【报价单-${t("common.withdrawAuditText")}】的使用权限`;
        }
        return "";
      },
      clickFunc: item => {
        ElMessageBox.confirm("是否确定要撤审单据吗?", "询问", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning"
        })
          .then(() => {
            let list = [LjDetailRef.value._mainData];
            AuditBedNet({ list, type: 0 }).then(() => {
              ElMessage.success("撤审成功！");

              LjDetailRef.value.refresh();
            });
          })
          .catch((e: TypeError) => {
            ElMessage({
              type: "info",
              message: "操作取消"
            });
          });
      }
    })
  ],
  buttonDefault({
    label: t("common.showQuoteDetail"),
    limited: () => {
      // 业务员模式
      return userInfo.usermode == 1;
    }
  }),
  buttonDefault({
    label: t("common.copyQuote")
  }),
  // buttonDefault({
  //   label: t("common.showFormula")
  //   // clickFunc: item => gotoSummy()
  // }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    clickFunc: () => {
      console.log("LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
      // gotoHisprice(0, { id: LjDetailRef.value._mainData.mattressid, typeid: 1 });
    }
  })
];

onMounted(async () => {
  initParams.value.arg_bednetid = Number(route.query?.id ?? 0);
  initParamsMx.value.arg_bednetid = Number(route.query?.id ?? 0);
  if (!Number(route.query?.id)) {
    if (route.query?.deptid) {
      defaultColumnsValue.value.deptid = route.query?.deptid;
    }
  }
  defaultColumnsValue.value.sponge_mtrlid = 0;
  console.log(
    "donMounted efaultColumnsValue.value :>> ",
    defaultColumnsValue.value,
    Object.keys(route.query).includes("id"),
    route.query?.id
  );
});

/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async (data: any) => {
  console.log("onMounted detail sale start!!!! :>> ", !orderStatus.value, data);
  // console.log("LjDetailRef.value.currentMould :>> ", LjDetailRef.value.currentMould);
  // console.log(
  //   "Boolean(Number(CheckOption(sysOptionEnum.sys_option_043))) :>> ",
  //   Boolean(Number(CheckOption(sysOptionEnum.sys_option_043)))
  // );
  // // 流转状况
  // if (Boolean(Number(CheckOption(sysOptionEnum.sys_option_043))) && LjDetailRef.value.currentMould.header.floatbtn) {
  // let _oaflowbtn = LjDetailRef.value.currentMould.header.floatbtn.find((itm: any) => itm.id == "oaFlow");
  // if (_oaflowbtn) {
  //   _oaflowbtn.originLeft && (oaFlowFloadProp.value.originLeft = _oaflowbtn.originLeft);
  //   _oaflowbtn.originTop && (oaFlowFloadProp.value.originTop = _oaflowbtn.originTop);
  // }
  // oaFlowFloadProp.value.change = LjDetailRef.value.toSetFloatBtnChange;

  //   if (!ALLOW_EDIT_STATE.includes(orderStatus.value)) {
  //     // 非新增、修改时执行
  //     getOaFlowList(initParams.value.scid, initParams.value.taskid).then(() => {
  //       if (oaFlowList.value.length) {
  //         gotoSummy();
  //       }
  //     });
  //   }
  // }

  // if (ALLOW_EDIT_STATE.includes(orderStatus.value)) {
  //   saleTaskMx_tableProps.value.editConfig.enabled = true;
  // }
  // if (orderStatus.value == "new") {
  //   nextTick(async () => {
  //     console.log("SaletaskmxListRef.value onmound new:>> ", SaletaskmxListRef.value);
  //     if (SaletaskmxListRef.value) {
  //       const $table = SaletaskmxListRef.value.element;
  //       if ($table) {
  //         const record = {};
  //         const { row: newRow } = await $table.insertAt(record, null);
  //         await $table.setEditCell(newRow, "mtrlcode");
  //         console.log("onMounted saletask finish :>> ", $table);
  //       }
  //     }
  //   });
  // }
  if (!orderStatus.value) {
    // 详情页
    // gotoSummy(8000);
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = true;

    let res = await getBedNetAreaList({});

    if (res.datatable.length) {
      AreaList.value = res.datatable;
    }
  }
  // ifAfterMound.value = true;

  console.log(
    "onMounted detail sale start LjDetailRef.value.mainData :>> ",
    AreaList.value,
    tableProps_mx.value,
    LjDetailRef.value
  );

  if (orderStatus.value != "new") {
    // const { enumMap, _mainData } = LjDetailRef.value;
    // console.log("enumMap :>> ", enumMap, _mainData);
    // let _enum = enumMap.get("mattresstypeid");
    // console.log("_enum :>> ", _enum);
    // if (_enum) {
    //   mattresstypeEnum.value = _enum.find(t => t.value == _mainData.mattresstypeid);
    //   console.log("mattresstypeEnum :>> ", mattresstypeEnum);
    // }

    // let itmshow = fabricMxTabList.value.find(t => t.visible());
    // fabricMxTabs.value = itmshow.name;

    // let res = await getData_mx(initParams.value);
    // oriMxData.value = dataCallback(res);
    // oriMxData.value.list = oriMxData.value.list.map(t => {
    //   t.formulakind = Number(t.formulakind);
    //   t.thickness = Number(t.thickness);
    //   return t;
    // });

    // getMattressType();

    // let res = await getDataMxAdd(initParamsMx.value);
    // let result = dataCallbackMx(res);
    // columnsMx.value = result.tableinfo.columns;
    // bednetMxData.value = result.list;

    // res = await getDataMxSpring(initParamsMx.value);
    // result = dataCallbackMx(res);
    // columnsMxSpring.value = result.tableinfo.columns;
    // bednetMxSprintData.value = result.list;

    reload_dw2(data, (params: any) => {
      const { mx, spring } = params;
      console.log("reload_dw2 22result :>> ", params);
      bednetMxData.value = mx.list;
      bednetMxSprintData.value = spring.list;

      // vxeTableMxSpringRef.value.refresh();
    });
    // bednetMxData.value = bednetMxData.value.map(t => {
    //   // t.formulakind = Number(t.formulakind);
    //   // t.thickness = Number(t.thickness);
    //   // t.qty = Number(t.qty);
    //   return t;
    // });

    // console.log("bednetMxData after:>> ", bednetMxData.value, orderStatus.value, vxeTableMxRef.value.tableColumns);
    // nextTick(() => {
    //   vxeTableMxRef.value.refresh();
    // });

    // res = await getDataMxSpring(initParams.value);

    // funcChaifenTab();
    // funcGetFabricMxShowData(itmshow.name);
    // console.log("funcAfterMound resData :>> ", fabricMxData.value);
  }
};
</script>
