<template>
  <LjDetail
    name="softbedQuoteDetail"
    ref="LjDetailRef"
    v-bind="detailProps"
    :data="softBed"
    :dwname="DwnameEnum.softbedQuote"
    v-model:order-status="orderStatus"
    :action="orderDefaultAction"
    @after-mounted="funcAfterMound"
    :if-layout-editable="false"
    :request-auto="false"
    :auto-load-layout="true"
  >
    <template #HeadBoard>
      <LjVxeTable
        ref="VxeTableHeadBoardMxRef"
        row-key="key"
        table-cls="h-full"
        :data="headBoardMx"
        :columns="columnsMx"
        :dwname="DwnameEnum.softbedQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        :request-auto="false"
      >
        <template #tableHeader>
          <el-space wrap v-if="orderStatus">
            <el-button type="primary" @click="toAddMx(VxeTableHeadBoardMxRef)">{{ t("common.addText") }}</el-button>
            <el-button type="danger" @click="toDelMx(VxeTableHeadBoardMxRef)">{{ t("common.delText") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>
    <template #NightStand>
      <LjVxeTable
        ref="VxeTableNightStandMxRef"
        row-key="key"
        table-cls="h-full"
        :data="nightStandMx"
        :columns="columnsMx"
        :dwname="DwnameEnum.softbedQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        :request-auto="false"
      >
        <template #tableHeader>
          <el-space wrap v-if="orderStatus">
            <el-button type="primary" @click="toAddMx(VxeTableNightStandMxRef)">{{ t("common.addText") }}</el-button>
            <el-button type="danger" @click="toDelMx(VxeTableNightStandMxRef)">{{ t("common.delText") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>
    <template #BedFrame>
      <LjVxeTable
        ref="VxeTableBedFrameMxRef"
        row-key="key"
        table-cls="h-full"
        :data="bedFrameMx"
        :columns="columnsMx"
        :dwname="DwnameEnum.softbedQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        :request-auto="false"
      >
        <template #tableHeader>
          <el-space wrap v-if="orderStatus">
            <el-button type="primary" @click="toAddMx(VxeTableBedFrameMxRef)">{{ t("common.addText") }}</el-button>
            <el-button type="danger" @click="toDelMx(VxeTableBedFrameMxRef)">{{ t("common.delText") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>
    <template #Other>
      <LjVxeTable
        ref="VxeTableOtherMxRef"
        row-key="key"
        table-cls="h-full"
        :data="otherMx"
        :columns="columnsMxOther"
        :dwname="DwnameEnum.softbedQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        :request-auto="false"
      >
        <template #tableHeader>
          <el-space wrap v-if="orderStatus">
            <el-button type="primary" @click="toAddMx(VxeTableOtherMxRef)">{{ t("common.addText") }}</el-button>
            <el-button type="danger" @click="toDelMx(VxeTableOtherMxRef)">{{ t("common.delText") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>
  </LjDetail>
  <BedConfigModal
    v-model="isModalVisible"
    v-model:showHeadboard="showHeadboard"
    v-model:showNightstand="showNightstand"
    v-model:showBedframe="showBedframe"
    v-model:partsConfig="partsConfig"
    :headboardConfigOptions="headboardConfigOptions"
    :nightstandConfigOptions="nightstandConfigOptions"
    :bedframeConfigOptions="bedframeConfigOptions"
    :configValueOptionsMap="configValueOptionsMap"
    @submit="onConfirmConfigureDialog"
    @cancel="isModalVisible = false"
  />
  <ErpMtrlPriceDialog ref="ErpMtrlPriceDialogRef" v-bind="ErpMtrlPriceDialogProps" />
  <SoftBedTemplateDialog ref="SoftBedTemplateDialogRef" v-bind="SoftBedTemplateDialogProps" />
  <!-- <FormulaEditorDialog ref="formulaEditorRef" @confirm="handleFormulaConfirm" /> -->
  <FormulaEditor ref="sharedFormulaEditorRef" @confirm="handleFormulaConfirm" />
</template>

<script setup lang="tsx" name="softBedQuoteDetail">
import { ref, watch, reactive, inject, onMounted } 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 { useRoute, useRouter } from "vue-router";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { useHooks } from "./hooks/index";
import { useUserStore } from "@/stores/modules/user";
import BedConfigModal from "./components/BedConfigModal.vue";
import ErpMtrlPriceDialog from "@/views/system/selector/erpMtrlPrice/index.vue";
import SoftBedTemplateDialog from "@/views/system/selector/softbedTemplate/index.vue";
import FormulaEditorDialog from "@/views/system/formula-editor/index.vue";
import FormulaEditor from "@/views/system/formula-editor/index.vue";
import { usePageRouter } from "@/hooks/usePageRouter";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const {
  orderStatus,
  LjDetailRef,
  VxeTableHeadBoardMxRef,
  VxeTableNightStandMxRef,
  VxeTableBedFrameMxRef,
  formulaEditorRef,
  sharedFormulaEditorRef,
  columns,
  columnsMx,
  columnsMxOther,
  softBed,
  headBoardMx,
  nightStandMx,
  bedFrameMx,
  otherMx,
  VxeTableOtherMxRef,
  isModalVisible,
  showHeadboard,
  showBedframe,
  showNightstand,
  headboardConfigOptions,
  nightstandConfigOptions,
  bedframeConfigOptions,
  configValueOptionsMap,
  ErpMtrlPriceDialogProps,
  ErpMtrlPriceDialogRef,
  SoftBedTemplateDialogRef,
  SoftBedTemplateDialogProps,
  partsConfig,
  loadingStatus,
  detail_getData,
  toAddMx,
  toDelMx,
  onSave,
  onAudit,
  onCAudit,
  onDelete,
  onConfirmConfigureDialog,
  GetSoftBedFormulaMapper,
  GetSoftBedAccessoryMapper,
  openSharedFormulaEditor,
  handleFormulaConfirm
} = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
const { pageRefresh } = usePageRouter();

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

// const partsConfig = reactive({
//   headboard: [],
//   nightstand: [],
//   bedframe: []
// });

const tabRemove: Function = inject("tabRemove") as Function;
const { userInfo } = useUserStore();
/**
 * @description 明细表格组件基础配置
 */
const tableProps = 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
  }
});

/**
 * @description 明细表格组件基础配置
 */
const tableProps_mx = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "100px",
  editConfig: { trigger: "click", mode: "row", enabled: false, autoClear: 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);
    }
  },
  mouseConfig: {
    selected: true
  },
  cellClick: (data: any) => {
    console.log(data);
  }
});

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.softbedQuote,
  columns: columns,
  basicDefault: {},
  header: {
    fieldNames: {
      code: "softbed_code",
      codeLabel: "核价编码：",
      name: "name"
    }
  },
  mould: [
    {
      id: "HeadBoard",
      type: "table",
      label: "床头",
      limited: (params: any) => {
        if (!params) return true;
        return params?.has_headboard === 0;
      }
    },
    {
      id: "NightStand",
      type: "table",
      label: "床头柜",
      limited: (params: any) => {
        if (!params) return true;
        return params?.has_nightstand === 0;
      }
    },
    {
      id: "BedFrame",
      type: "table",
      label: "床架",
      limited: (params: any) => {
        if (!params) return true;
        return params?.has_bedframe === 0;
      }
    },
    {
      id: "Other",
      type: "table",
      label: "其他"
    }
  ]
});

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);
      // } else {
      // router.replace(
      //   `/softbedQuote/detail?id=${LjDetailRef.value._mainData.softbed_id}&code=${LjDetailRef.value._mainData.softbed_code}`
      // );
      pageRefresh({
        name: "softbedQuoteDetail",
        params: {
          id: LjDetailRef.value._mainData.softbed_id,
          code: LjDetailRef.value._mainData.softbed_code
        },
        query: {
          id: LjDetailRef.value._mainData.softbed_id,
          code: LjDetailRef.value._mainData.softbed_code
        }
      });
      // }
    }
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    loading: () => loadingStatus.value.save,
    limited: () => !orderStatus.value,
    disabledTextCallBack: data => {
      if (data.flag > 0) {
        return "单据已审核,无法保存!";
      }
      return "";
    },
    clickFunc: () => {
      onSave(res => {
        if (res.softbed.softbed_id) {
          pageRefresh({
            name: "softbedQuoteDetail",
            params: {
              id: res.softbed.softbed_id,
              code: res.softbed.softbed_code
            },
            query: {
              id: res.softbed.softbed_id,
              code: res.softbed.softbed_code,
              fromCopySave: orderStatus.value == "copy"
            }
          });
        } else {
          router.replace("/softbedQuote/index");
        }
      });
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 152,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      router.push(`/softbedQuote/new?id=0`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 152,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: data => {
      if (data.flag == 1) {
        return "单据已审核，不能修改";
      }
      return "";
    },
    clickFunc: item => {
      pageRefresh({
        name: "softbedQuoteEdit",
        params: {
          id: LjDetailRef.value._mainData.softbed_id,
          code: LjDetailRef.value._mainData.softbed_code
        },
        query: {
          id: LjDetailRef.value._mainData.softbed_id,
          code: LjDetailRef.value._mainData.softbed_code
        }
      });
      // router.replace(
      //   `/softbedQuote/edit?id=${LjDetailRef.value._mainData.softbed_id}&code=${LjDetailRef.value._mainData.softbed_code}`
      // );
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 155,
    loading: () => loadingStatus.value.delete,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(155)) {
        return "你没有【报价单-删除】的使用权限";
      }
      return "";
    },
    clickFunc: item => {
      const list = [{ softbed_id: LjDetailRef.value._mainData.softbed_id }];
      onDelete(list, () => {
        tabRemove(route.fullPath);
        router.replace("/softbedQuote");
      });
    }
  }),
  buttonDefault({
    label: t("common.auditText"),
    power: 153,
    loading: () => loadingStatus.value.audit,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(153)) {
        return `你没有【报价单-${t("common.auditText")}】的使用权限`;
      }
      if (+data.flag === 1) {
        return "已审核";
      }
      return "";
    },
    clickFunc: item => {
      const list = [{ softbed_id: LjDetailRef.value._mainData.softbed_id }];
      onAudit(list, () => {
        LjDetailRef.value.refresh();
      });
    }
  }),
  buttonDefault({
    label: t("common.withdrawAuditText"),
    power: 154,
    loading: () => loadingStatus.value.caudit,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(154)) {
        return `你没有【报价单-${t("common.withdrawAuditText")}】的使用权限`;
      }
      if (+data.flag === 0) {
        return "未审核";
      }
      return "";
    },
    clickFunc: item => {
      const list = [{ softbed_id: LjDetailRef.value._mainData.softbed_id }];
      onCAudit(list, () => {
        LjDetailRef.value.refresh();
      });
    }
  }),
  buttonDefault({
    label: t("common.showFormula"),
    disabledTextCallBack: () => {
      return userInfo.usermode == 1 ? "业务员模式不可以查看！" : "";
    },
    clickFunc: () => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    clickFunc: () => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.back"),
    clickFunc: item => {
      router.push("/softbedQuote/index");
    }
  })
];

/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async (data: any) => {
  // console.log("onMounted detail start!!!! :>> ", orderStatus.value, data, route, router);
  if (!orderStatus.value) {
    // 详情页
  } else {
    // 新增/编辑
    tableProps.value.editConfig.enabled = true;
    tableProps_mx.value.editConfig.enabled = true;
  }

  if (orderStatus.value != "new") {
    initParams.value.billid = Number(route.query.id);
    detail_getData(initParams.value);
  }
};

onMounted(() => {
  GetSoftBedFormulaMapper();
  GetSoftBedAccessoryMapper();
});

// 返回绑定的事件
const tableEvents = {};
</script>
<style lang="scss">
.select-text-right {
  .el-select__wrapper {
    text-align: right;
  }
}
</style>
