<template>
  <LjDetail
    ref="LjDetailRef"
    name="rpMustPayCrmDetail"
    v-bind="detailProps"
    :request-api="getData"
    :data-callback="dataCallback"
    :init-param="initParams"
    v-model:order-status="orderStatus"
    :action="!props.onlyView ? orderDefaultAction : []"
    @after-mounted="funcAfterMound"
    :if-layout-editable="false"
    :default-columns-value="defaultColumnsValue"
  >
    <template #headerSuffix>
      <Statistic :data="cmpFormulaReplace" :precision="2" @click="gotoShowFormula" />
    </template>
    <template #bednetMx>
      <div class="main-box flx">
        <div class="h-full flx-3 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
          class="flx-1 h-full overflow-hidden pl-16"
          style="min-width: 542px"
          v-if="bednetMxData.length && Number(LjDetailRef._mainData.bednettypeid) == 11 && Number(bednetMxData[0].if_part)"
        >
          <!-- v-if="bednetMxSpringData.length" -->
          <LjVxeTable
            ref="vxeTableMxSpringRef"
            row-key="bednetmx_partid"
            table-cls="h-full"
            :columns="columnsMxSpring"
            :data="bednetMxSpringData"
            :dwname="DwnameEnum.bednetQuoteMxSpring"
            :table-props="tableProps_spring"
            :auto-load-layout="false"
            :tool-button="[]"
            :search-btn-size-extent="[]"
            collapseButtons
            :footer-sum-attrs="['springname', 'spring_qty_length']"
            :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>
    </template>
  </LjDetail>

  <MtrldefDialog ref="MtrldefDialogRef" v-bind="MtrldefDialogProps" />
  <SpringDialog ref="SpringDialogRef" v-bind="SpringDialogProps" />
  <AllFormula ref="AllFormulaRef" />
</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";
import AllFormula from "./components/AllFormula.vue";
import Statistic from "./components/Statistic.vue";

interface DetailProps {
  deptid?: number | string;
  bednetid?: number;
  state?: string;
  /**
   * @description 床垫宽度
   */
  mattressWidth?: number;
  /**
   * @description 床垫长度
   */
  mattressLength?: number;
  /**
   * @description 床网大单类型
   */
  dannum_type?: number;
  /**
   * @description 是否只读
   */
  onlyView?: boolean;
}

const props = withDefaults(defineProps<DetailProps>(), {
  // deptid: 0,
  // bednetid: 0,
  // state: ""
  onlyView: false
});

const emit = defineEmits(["aftersave", "aftercancel"]);

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

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, autoFocus: true },
  editRules: {
    bednet_height: [
      { required: true, message: "请输入" },
      {
        validator({ cellValue }) {
          if (Number(cellValue) <= 0) {
            return new Error("请输入正数");
          }
        }
      }
    ],
    spring_qty_width: [
      { required: true, message: "请输入" },
      {
        validator({ cellValue }) {
          if (Number(cellValue) <= 0) {
            return new Error("请输入正数");
          }
        }
      }
    ],
    spring_qty_length: [
      { required: true, message: "请输入" },
      {
        validator({ cellValue }) {
          if (Number(cellValue) <= 0) {
            return new Error("请输入正数");
          }
        }
      }
    ],
    springname: [
      {
        validator({ cellValue, row }) {
          console.log("springname cellValue :>> ", cellValue, cellValue == "", Number(row.if_part) == 0, row);
          if (cellValue == "" && Number(row.if_part) == 0) {
            return new Error("请选择弹簧");
          }
        }
      }
    ]
  },
  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 tableProps_spring = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "300px",
  editConfig: { trigger: "click", mode: "row", enabled: false, autoFocus: true },
  editRules: {
    springname: [
      {
        validator({ cellValue, row }) {
          console.log("springname cellValue :>> ", cellValue, row);
          if (cellValue == "" && Number(row.spring_qty_length) > 0) {
            return new Error("请选择弹簧");
          }
        }
      }
    ]
  },
  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 => {
      if (typeof props.bednetid != "undefined") {
        emit("aftercancel");
      } else {
        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();

        const $table = vxeTableMxRef.value.element;
        console.log("vxeTableMxRef $table :>> ", $table);
        if ($table) {
          const errMap = await $table.validate(true);
          console.log("vxeTableMxRef errMap :>> ", errMap);
          if (errMap) {
            // VxeUI.modal.message({ status: 'error', content: '校验不通过！' })
            return false;
          }
        }

        const $tableSpring = vxeTableMxSpringRef.value?.element;
        console.log("vxeTableMxRef $tableSpring :>> ", $tableSpring);
        if ($tableSpring) {
          const errMap = await $tableSpring.validate(true);
          console.log("vxeTableMxRef errMap :>> ", errMap);
          if (errMap) {
            // VxeUI.modal.message({ status: 'error', content: '校验不通过！' })
            return false;
          }
        }

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

        let bednet = LjDetailRef.value._mainData;

        let bednetMx = vxeTableMxRef.value?.element.getTableData().fullData;
        console.log("bednetMx :>> ", bednetMx, vxeTableMxRef.value?.element.getTableData().fullData);
        bednetMx[0].if_side_iron = Number(bednetMx[0].if_side_iron);
        bednetMx[0].if_part = Number(bednetMx[0].if_part);
        bednetMx[0].if_15strip = Number(bednetMx[0].if_15strip);
        bednetMx[0].if_pocket_around = Number(bednetMx[0].if_pocket_around);
        bednetMx[0].if_hard_around = Number(bednetMx[0].if_hard_around);

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

        if (!["卷包", "不压不卷"].includes(bednet.packtype)) {
          bednet.packmtrl = "";
        }

        if (orderStatus.value == "copy") {
          bednet.copy_id = bednet.bednetid;
        }

        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 (typeof props.bednetid != "undefined") {
                emit("aftersave", res);
              } else {
                if (res.bednet.bednetid) {
                  tabRemove(route.fullPath);
                  router.replace(`/bednetQuote/detail?id=${res.bednet.bednetid}`);
                } else {
                  router.replace("/bednetQuote");
                }
              }
              setTimeout(() => {
                if (res.message) {
                  ElNotification({
                    title: "计算失败",
                    message: res.message,
                    type: "warning"
                  });
                }
              }, 100);
            })
            .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&deptid=${LjDetailRef.value._mainData?.deptid ?? 0}`);
    }
  }),
  buttonDefault({
    power: 72,
    label: t("common.editText"),
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: data => {
      if (data.flag == 1) {
        return "单据已审核，不能修改";
      }
      return "";
    },
    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;
    },
    clickFunc: () => gotoShowFormula()
  }),
  // 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 });
  //   }
  // }),
  buttonDefault({
    label: t("common.back"),
    limited: () => {
      // 业务员模式
      return typeof props?.bednetid != "undefined";
    },
    clickFunc: item => {
      router.push("/bednetQuote");
    }
  })
];

onMounted(async () => {
  console.log("onMounted bednet route.query :>> ", route.query, props);
  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;
      initParamsMx.value.arg_deptid = route.query?.deptid;
    }
  }
  console.log('typeof props?.bednetid != "undefined" :>> ', typeof props?.bednetid != "undefined", props);
  if (typeof props?.bednetid != "undefined") {
    // 直接读取
    orderStatus.value = props.state;
    initParams.value.arg_bednetid = props.bednetid;
    initParamsMx.value.arg_deptid = props?.deptid;
    initParamsMx.value.arg_bednetid = props.bednetid;
    defaultColumnsValue.value.deptid = props?.deptid;
    dannum_type.value = props?.dannum_type;

    defaultColumnsValue.value.mattress_width = props?.mattressWidth;
    defaultColumnsValue.value.mattress_length = props?.mattressLength;
  }

  console.log("initParams.value :>> ", initParams.value);
});

/**
 * @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) {
    // 详情页
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = true;
    tableProps_spring.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") {
    console.log("reload_dw2 data :>> ", data);
    await reload_dw2(data, (params: any) => {
      const { mx, spring } = params;
      console.log("reload_dw2 22result :>> ", params);
      bednetMxData.value = mx.list;
      bednetMxSpringData.value = spring.list;
    });

    nextTick(() => {
      gotoSummy(8000);
    });
  }
};

const gotoShowFormula = () => {
  AllFormulaRef.value.open(cmpFormulas.value, cmpFormulaReplace.value);
};
</script>
