<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-mounted="funcAfterMound"
    :if-layout-editable="false"
  >
    <template #fabricMx>
      <LjVxeTable
        ref="fabricMxTab8Ref"
        row-key="key"
        table-cls=""
        :data="fabricMxTab8"
        :columns="columnsMx"
        :dwname="DwnameEnum.semifinprodQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
      >
      </LjVxeTable>
    </template>
  </LjDetail>

  <MtrldefDialog ref="MtrldefDialogRef" v-bind="MtrldefDialogProps" />
  <!-- <LjDrawerQuoteList
    ref="QuoteListDrawerRef"
    :data="LjDetailRef && LjDetailRef._mainData"
    :mxdata="isQuoteListMxData"
    :enumMap="LjDetailRef && LjDetailRef.enumMap"
    :fabricMx="fabricMxTabList"
    :formulakindenum="formulaKindEnum"
  /> -->
</template>

<script setup lang="ts" name="semifinprodQuoteDetail">
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 } 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 { SaveMattress, SaveMattressAuditing, DelMattress } from "@/api/modules/quote";
// import ToastFormula from "@/components/ToastWidget/Formula/index.vue";
import { TYPE, useToast, POSITION } from "vue-toastification";
import { ElMessage, ElMessageBox } 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 LjDrawerQuoteList from "./components/QuoteList.vue";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import { getCurrentRecords } from "@/utils/index";

interface detailProp {
  /**
   * @argument any 页面数据
   */
  data1?: any;
  /**
   * @argument string 请求数据的api ==> 非必传
   */
  requestApi?: (params: any) => Promise<any>;
  /**
   * @argument any 基础信息，表格展示数据
   */
  // columns?: any;
  /**
   * @description 是否可编辑
   */
  status: "edit" | "new" | string;
}

const props = withDefaults(defineProps<detailProp>(), {});
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { columns, columnsMx, LjDetailRef, MtrldefDialogRef, MtrldefDialogProps, orderStatus, initParams } = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
// const toast = useToast();

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

/**
 * @description 明细表格组件基础配置
 */
const tableProps_mx = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "300px",
  editConfig: { trigger: "click", mode: "cell", enabled: false },
  // exportConfig: {
  //   filename: t("menu.saleTaskCrmDetail") + formatToDate(new Date(), "YYYY-MM-DDHH:mm:ss")
  // }
  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);
    }
  },
  mouseConfig: {
    selected: true
  }
});

const keyboardConfig = ref<any>({
  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);
  }
});

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.semifinprodQuote,
  columns: columns,
  // headerstatus: ["status", "ifamt_ok"],
  basicDefault: {},
  header: {
    fieldNames: {
      code: "sptcode",
      codeLabel: t("table.u_spt.sptcode") + "：",
      name: "name"
    }
  },
  mould: [
    {
      id: "fabricMx",
      type: "table",
      label: t("business.detail.fabric")
    }
  ]
});

const getData = (params: any) => {
  console.log("getData params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  console.log("params :>> ", params);
  newParams.dsname = "web_semi_finished_productlist";
  return CommonDynamicSelect(newParams, DwnameEnum.semifinprodQuote);
  // return [];
};

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

      let mattressMx = [];
      // fabricMxTabList.value.map(t => {
      //   if (t.ref) {
      //     console.log("t.ref?.value :>> ", t.ref, dynamicRef(t.ref));
      //     if (dynamicRef(t.ref)) {
      //       const { fullData } = dynamicRef(t.ref)?.element.getTableData();
      //       console.log("fullData :>> ", fullData);
      //       mattressMx = mattressMx.concat(fullData);
      //     }
      //   }
      // });

      console.log("mattressMx all :>> ", mattressMx);

      let _param_mf = {
        mattress: LjDetailRef.value._mainData,
        mattressMx: mattressMx
      };
      try {
        await SaveMattress(_param_mf);
      } catch (error) {
        ElMessage.error(t("sys.api.operationFailed"));
      }
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 72,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      router.push(`/semifinprodQuote/new?id=0`);
    }
  }),
  buttonDefault({
    power: 72,
    label: t("common.editText"),
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      router.replace(
        `/semifinprodQuote/edit?id=${LjDetailRef.value._mainData.mattressid}&code=${LjDetailRef.value._mainData.mattresscode}`
      );
    }
  }),
  buttonDefault({
    power: 77,
    label: t("common.delText"),
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(77)) {
        return "你没有【报价单-删除】的使用权限";
      }
      return "";
    },
    clickFunc: item => {
      console.log("dellll clickFunc item :>> ", LjDetailRef.value);
      ElMessageBox.confirm("是否确定要删除床垫报价单吗?", "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "error"
      })
        .then(() => {
          DelMattress({ mattressids: [Number(LjDetailRef.value._mainData.mattressid)] }).then(() => {
            ElMessage.success("删除成功！");

            tabRemove(route.fullPath);
            router.replace("/semifinprodQuote");
            mittBus.emit(MittEnum.MattressList);
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  })
];

onMounted(async () => {
  console.log("route onMounted:>> ", route);
  console.log("route onMounted:>> ", route.params);
  console.log("route onMounted:>> ", route.params.id);

  if (route.query?.id) {
    // 刷新数据
    initParams.value.arg_mattressid = Number(route.query?.id);
    console.log("detail onMounted initParams.value :>> ", initParams.value);
  }

  // getFormulakindEnum();
});

/**
 * @description 详情页是否加载完成
 */
const ifAfterMound = ref(false);
/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async () => {
  console.log("onMounted detail sale start!!!! :>> ");
  if (!orderStatus.value) {
    // 详情页
    gotoSummy(8000);
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = true;
  }
  ifAfterMound.value = true;

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

  if (orderStatus.value != "new") {
    getMattressType();

    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);
      t.qty = Number(t.qty);
      return t;
    });

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

const handleSelFabricMxNewMtrlGroup = (target: string, item: any) => {
  console.log("handleSelFabricMxNewMtrlGroup target :>> ", target, item, fabricMxTab10.value);
  if (target == "tabpage_10") {
    let hasSame = fabricMxTab10.value.findIndex(t => t.sortcode == item.label);
    if (hasSame > -1) {
      ElMessage.error(item.label + "已存在");
      return false;
    }

    const $table = fabricMxTab10Ref.value.element;
    if ($table) {
      let _arr = [];
      fabricMxTab10.value.map(t => {
        if (t.sortcode == "普通大侧") {
          _arr.push(t);
        }
      });
      $table.remove(_arr);
    }

    let _params = {
      arg_array_formulakind: [2, 42, 52, 62, 72, 82],
      arg_array_formulatype: [0, 1, 2, 3]
    };
    funcAddMxSide(_params, item, fabricMxTab10Ref.value);
  } else if (target == "tabpage_11") {
    let hasSame = fabricMxTab11.value.findIndex(t => t.sortcode == item.label);
    if (hasSame > -1) {
      ElMessage.error(item.label + "已存在");
      return false;
    }

    const $table = fabricMxTab11Ref.value.element;
    if ($table) {
      let _arr = [];
      fabricMxTab11.value.map(t => {
        if (t.sortcode == "小侧1") {
          _arr.push(t);
        }
      });
      $table.remove(_arr);
    }

    let _params = {
      arg_array_formulakind: [3, 83, 43, 53, 63, 73],
      arg_array_formulatype: [0, 1, 2, 3]
    };
    funcAddMxSide(_params, item, fabricMxTab11Ref.value);
  }
};

const handleDelFabricMxNewMtrlGroup = (target: string) => {
  let sameMx = [];
  let $table = null;
  if (target == "tabpage_10") {
    $table = fabricMxTab10Ref.value.element;
  } else if (target == "tabpage_11") {
    $table = fabricMxTab11Ref.value.element;
  }

  if ($table) {
    const curRow = $table.getCurrentRecord();

    if (!curRow) {
      ElMessage.warning("请先选择要删除的行");
      return;
    }

    sameMx = fabricMxTab10.value.filter(t => t.sortcode == curRow.sortcode);
  }

  ElMessageBox.confirm(`是否确定要删除${sameMx.length}条明细吗?`, "询问：" + sameMx[0].sortcode, {
    confirmButtonText: t("common.delText"),
    cancelButtonText: "否",
    type: "error"
  })
    .then(() => {
      if (target == "tabpage_10") {
        let _arr = [];
        let _idx = [];
        fabricMxTab10.value.map((t, idx) => {
          if (t.sortcode == sameMx[0].sortcode) {
            _arr.push(t);
            _idx.push(idx);
          }
        });
        $table.remove(_arr);

        fabricMxTab10.value = fabricMxTab10.value.filter((t, idx) => !_idx.includes(idx));
      } else if (target == "tabpage_11") {
        let _arr = [];
        let _idx = [];
        fabricMxTab11.value.map((t, idx) => {
          if (t.sortcode == sameMx[0].sortcode) {
            _arr.push(t);
            _idx.push(idx);
          }
        });
        $table.remove(_arr);

        fabricMxTab11.value = fabricMxTab11.value.filter((t, idx) => !_idx.includes(idx));
      }
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};
</script>

<style lang="scss">
.select-text-right {
  .el-select__wrapper {
    text-align: right;
  }
}
</style>
