<template>
  <LjDetail
    name="semifinprodQuoteDetail"
    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"
    :search-col="{ xs: 3, sm: 3, md: 3, lg: 3, xl: 3 }"
    :basic-group-col="{ xs: 3, sm: 3, md: 3, lg: 3, xl: 3 }"
  >
    <template #fabricMx>
      <LjVxeTable
        ref="VxeTableMxRef"
        row-key="key"
        table-cls=""
        :data="fabricMxTab"
        :columns="columnsMx"
        :dwname="DwnameEnum.semifinprodQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
        :request-auto="false"
      >
      </LjVxeTable>
    </template>
  </LjDetail>

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

<script setup lang="tsx" name="semifinprodQuoteDetail">
import { ref, watch, reactive, inject, onMounted } from "vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { SaveMattressBcp, AuditMattressBcp, DeleteMattressBcp } from "@/api/modules/quote";
import LjDetail from "@/components/LjDetail/index.vue";
import { DetailProp } from "@/components/LjDetail/interface";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { useHooks } from "./hooks/index2";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ElMessage, ElMessageBox } from "element-plus";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import MtrldefDialog from "@/views/system/selector/mtrldefNoPrice/index.vue";
import { formatToDate } from "@/utils/dateUtil";

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

const props = withDefaults(defineProps<detailProp>(), {});
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const {
  orderStatus,
  LjDetailRef,
  VxeTableMxRef,
  fabricMxTab,
  oriMxData,
  MtrldefDialogRef,
  MtrldefDialogProps,
  columns,
  columnsMx,
  getFormulakindEnum,
  funcChaifenTab
} = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const tabRemove: Function = inject("tabRemove") as Function;

const mainData = ref([{}]);
const initParams = ref({ billid: 0 as Number });

/**
 * @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 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);
};

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.billid}&code=${LjDetailRef.value._mainData.billcode}`
        );
      }
    }
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    limited: () => {
      return !orderStatus.value;
    },
    clickFunc: async () => {
      console.log("save LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
      const { fullData } = VxeTableMxRef.value?.element.getTableData();
      console.log("mattressMx all :>> ", fullData);
      const mattress = LjDetailRef.value._mainData;
      mattress.mxlist = fullData;

      for (let key in mattress) {
        if (key === "billdate") {
          mattress[key] = formatToDate(mattress[key]);
          break;
        }
      }

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

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

/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async () => {
  console.log("onMounted detail sale start!!!! :>> ");
  if (!orderStatus.value) {
    // 详情页
    // gotoSummy(8000);
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = 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();
  }
};

const getData_mx = (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_productmxlist";
  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuoteMx);
  // return [];
};

const dataCallback = (data: any) => {
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

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.billid = Number(route.query?.id);
    console.log("detail onMounted initParams.value :>> ", initParams.value);
  }

  getFormulakindEnum();
});
</script>
