<template>
  <div :class="`${prefixCls}__wrapper`">
    <RenderLjDetail v-bind="currentMould" :data="props.data" />

    <SettingWidget v-if="currentMould" v-bind="currentMould" ref="DetailSettingRef" @confirm="toSetDetailBase" />
    <!-- v-if="toolButton.length && toolButton.indexOf('print') > -1" -->
    <PrintEditor ref="printEditorRef" @closed="toClosedPrintEditor" />
    <PrintTemplateSelector
      ref="printTemplateRef"
      @newtemplate="toEditPrintTemplate"
      @edittemplate="toEditPrintTemplate"
      @preview="toPreviewPrintTemplate"
      @confirm="toPrintPrintTemplate"
      @closed="toGetPrinterState"
    />
  </div>
</template>

<script setup lang="tsx" name="LjDetail">
import { ref, reactive, onMounted, useSlots, nextTick, provide, watch, computed, toRefs, inject } from "vue";
import { Tools, ArrowUpBold, Printer, Setting } from "@element-plus/icons-vue";
import { DetailProp, detailModelItemProp } from "./interface";
import { useDesign } from "@/hooks/useDesign";
import { useI18n } from "vue-i18n";
import Affix from "./components/Affix.vue";
import SettingWidget from "./components/Setting.vue";
import { useLayoutLocalStore } from "@/stores/modules/layoutLocal";
import { getDifference, setDifference, handleProp, streamlineFunc, streamlineAttrFunc, convertStrToObj } from "@/utils";
import { cloneDeep, pick, get, omit, defaultsDeep } from "lodash-es";
import LjHeader from "@/components/LjHeader/index.vue";
import BaseMsgForm from "@/components/BaseMsgForm/index.vue";
import LjFoldLayout from "@/components/LjFoldLayout/index.vue";
import BaseForm from "./components/BaseForm.vue";
import ButtonGroup from "./components/ButtonGroup.vue";
import DropdownList from "./components/DropdownList.vue";
import { ColumnProps, dwnameSaveLayoutAttr } from "@/components/LjVxeTable/interface";
import { useLayoutStore } from "@/stores/modules/layout";
import { useRoute } from "vue-router";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElNotification } from "element-plus";
import { ElMessage } from "element-plus";
import { useTable } from "@/hooks/useTable";
import { useDwLayout } from "@/hooks/useDwLayout";
import {
  TABLE_LAYOUT_ATTR,
  TABLE_LAYOUT_ATTR_DEFINE,
  DETAIL_BASICINFO_FORM_DEFINE,
  DETAIL_LAYOUT_ATTR,
  DETAIL_LAYOUT_DEFINE,
  PRINT_KEY_ATTR,
  TABLE_TYPE_FILTER,
  ALLOW_EDIT_STATE
} from "@/config/index";
import { useGlobalStore } from "@/stores/modules/global";
// import BaseCardTimeline from "./components/BaseCardTimeline.vue";
import { isFunction, isNumber, isArray } from "@/utils/is";
import { usePrint } from "@/hooks/usePrint";
import variables from "@/styles/js.module.scss";
import PrintEditor from "@/components/PrintEditor/index.vue";
import PrintTemplateSelector from "@/components/Selector/PrintTemplate/index.vue";

const { t } = useI18n();
/** 默认使用通用接口，并只读第一条数据作为主表数据 */
const props = withDefaults(defineProps<DetailProp>(), {
  columns: () => [],
  data: () => [],
  rightFixedAction: () => [],
  rightFixedActionPower: () => [],
  requestAuto: true,
  pagination: true,
  initParam: {},
  layoutAttr: () => TABLE_LAYOUT_ATTR,
  layoutAttrDefine: () => TABLE_LAYOUT_ATTR_DEFINE,
  searchCol: () => ({ xs: 2, sm: 4, md: 5, lg: 6, xl: 6 }),
  basicGroupCol: () => ({ xs: 3, sm: 3, md: 6, lg: 6, xl: 6 }),
  autoLoadLayout: false,
  ifFoldLayout: true,
  ifLayoutEditable: true,
  ifBasicEditable: true,
  detailLayoutAttr: () => [
    "scrollspy",
    "sticky",
    "id",
    "props",
    "isHidden",
    "descColumn",
    "size",
    "direction",
    "border",
    "direction",
    "foldleft",
    "foldright",
    "mxprops",
    "originLeft",
    "originTop"
  ],
  editable: false
});
const slots: any = useSlots();
const { prefixCls } = useDesign("detail-layout");
const LjDetailRef = ref();
const LjDetailBaseFormRef = ref();
const LjDetailAffixRef = ref();
const LjFoldLayoutRef = ref();
const headerAffixTop = ref(0);
const headerAffixHeight = ref(0);
const _variables: any = variables;
const layoutLocalStore = useLayoutLocalStore();
// 布局暂存数据
const layoutStore = useLayoutStore();
/**
 * @description 过滤主表基础信息配置项
 */
let infoColumns = ref<ColumnProps[]>([]);
let infoParam = ref<any>({});
/**
 * @description 查询后的主表结果
 */
const mainData_api = ref();
/**
 * @description 查询后的详情结果
 */
const detailData_api = ref();
/**
 * @description 主表数据，影子，只读
 */
// const _mainData = computed(() => tableData.value[0] ?? props.data[0] ?? infoParam.value);
// const _mainData = computed(() => {
//   // console.log("_mainData tableData.value[0] :>> ", tableData.value, tableData.value[0]);
//   // console.log("_mainData props.data.value[0] :>> ", props.data, props.data[0]);
//   // console.log("_mainData infoParam.value[0] :>> ", infoParam.value);
//   // console.log(
//   //   "tableData.value[0] ?? props.data[0] ?? infoParam.value :>> ",
//   //   tableData.value[0] ?? (props.data.length && props.data[0]) ?? infoParam.value,
//   //   tableData.value[0] ?? { ...infoParam.value, ...props.data[0] }
//   // );
//   return tableData.value[0] ?? { ...infoParam.value, ...props.data[0] };
// });
const _mainData = ref<any>({});
/**
 * @description 详情数据，影子，只读
 */
const _detailData = computed(() => detailData_api.value);
const tabsActive = ref();
/**
 * @description 当前页面参数
 */
const currentMould = ref<any>();
const isScrollspy = computed(() => {
  console.log("isScrollspy currentMould.value :>> ", currentMould.value);
  console.log("DETAIL_LAYOUT_DEFINE :>> ", DETAIL_LAYOUT_DEFINE);
  return currentMould.value?.header?.tabsProp?.scrollspy ?? DETAIL_LAYOUT_DEFINE.tabsProp.scrollspy;
});
/**
 * @description 树形化：接收 columns 并设置为响应式
 */
const globalStore = useGlobalStore();
const route = useRoute();
const orderStatus = ref<"edit" | "new" | string>("");
provide("orderStatus", orderStatus);
/**
 * @description 基础信息模块，是否可编辑
 */
const editable = computed(() => {
  return ALLOW_EDIT_STATE.includes(orderStatus.value);
});
provide("editable", editable);
// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { CheckPower, funcFilterPower, funcRightActionPower } = useAuthButtons(t);

const layoutHeader = computed(() => {
  console.log("layoutHeader currentMould.value :>> ", currentMould.value);
  return currentMould.value.header;
});

const currentLayout = inject("currentLayout", ref<any>(null));
console.log("Ljdetail currentLayout :>> ", currentLayout);
/**
 * @description fold布局过滤保留字段
 * @enum string width hidden lastWidth
 */
const FoldLayoutFilterAttr = ["width", "hidden", "lastWidth"];

const emit = defineEmits(["update:orderStatus", "toPinDetail", "afterMounted", "tabsClick"]);

const basicinfoFormDefaultComputed = Object.assign(DETAIL_BASICINFO_FORM_DEFINE, props.basicDefault);

// 表格参数:init
let tableOptions = reactive<dwnameSaveLayoutAttr>({});

console.log("onload!!!tableOptions :>> ", tableOptions);

const loadLayoutCallBack = (data: any) => {
  console.log("loadLayoutCallBack data :>> ", data);
  if (data?.hasOwnProperty("tableprop") && data.tableprop) {
    tableOptions = data.tableprop;

    console.log("loadLayoutCallBack bfff tableOptions :>> ", tableOptions);
    // read
    let _loadBase = cloneDeep(tableOptions.basicinfo ?? {});
    let _oriBase = cloneDeep(basicinfoFormDefaultComputed);
    if (!_oriBase?.basicGroup) _oriBase.basicGroup = [];
    if (!_loadBase?.basicGroup) _loadBase.basicGroup = [];

    console.log("_oriBase :>> ", _oriBase);
    console.log("_loadBase :>> ", _loadBase);
    // 补充默认分组中，差异的部分
    _loadBase.basicGroup.forEach((item: any) => {
      let idx = _oriBase.basicGroup.findIndex((i: any) => i.label === item.label);
      if (idx == -1) {
        _oriBase.basicGroup.push({ label: item.label });
      }
    });
    console.log("aff _oriBase :>> ", _oriBase);

    tableOptions.basicinfo = setDifference(_oriBase, tableOptions.basicinfo, "label");
    console.log("loadLayoutCallBack tableOptions :>> ", tableOptions);
  }
};

// 通用查询接口返回的布局数据，保存
const loadDwLayout = (data: any) => {
  console.log("layout data:>> ", data);
  // 表格结构： {tableprop: string, columns: string}
  // typeof layout.itemvalue == "string" && (layout.itemvalue = JSON.parse(layout.itemvalue.replace(/'/g, '"')));
  // 兼容部分结构直接记录行数据
  if (data.hasOwnProperty("columns") && data.columns) {
    dwLayout.value = data.columns;
  } else {
    dwLayout.value = data;
  }

  console.log("loadDwLayout bff data :>> ", props.dwname, data);
  loadLayoutCallBack(data);
  console.log("loadDwLayout affffffff data :>> ", props.dwname, data);

  props.dwname && layoutStore.setDwLayout(props.dwname, data, t, false);

  console.log("onMounted dwLayout.value :>> ", dwLayout.value);
  loadDwLayoutFunc(dwLayout.value);
  // tableColumns.value = cloneDeep(props.columns);
  console.log("数行化BF，还原个性设置 tableColumns.value :>> ", tableColumns.value);
  // 扁平化，并读取个性设置
  flatColumns.value = flatColumnsFunc(cloneDeep(props.columns), dwFieldMap);
  console.log("读取个性设置 flatColumns.value  loadDwLayout:>> ", flatColumns.value);

  initLayoutColumns();
};

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  totalParam,
  searchInitParam,
  tableLoading,
  getTableList
  // search,
  // reset,
  // handleSizeChange,
  // handleCurrentChange,
  // handlePageChange
} = useTable(
  props.requestApi,
  props.initParam,
  props.pagination,
  props.dataCallback,
  props.requestError,
  props.dwname,
  undefined,
  !props.autoLoadLayout,
  loadDwLayout
);

const flatColumnsCallBack = (col: any) => {
  col.field == "status" && console.log(" flatColumnsCallBack col :>> ", col);
  // 设置 enumMap
  setEnumMap(col);
  // // 设置 表格基础信息-format枚举
  // setBaseEnumMap(col);
  return col;
};

// 主表布局读取与存储
const {
  tableColumns,
  dwLayout,
  dwFieldMap,
  flatColumns,
  loadLayoutFunc,
  loadDwLayoutFunc,
  flatColumnsFunc,
  getDefineAttr,
  loadRenderAttr,
  columnStreamlineFunc,
  getOriColumns
} = useDwLayout(
  "detail",
  t,
  cloneDeep(props.columns),
  props.layoutAttr,
  props.layoutAttrDefine,
  props.autoLoadLayout,
  props.dwname,
  loadLayoutCallBack,
  flatColumnsCallBack
);

/**
 * @description 当前已选列表
 */
const selectRecords = ref<any>();

/**
 * @description 打印前检测状态
 */
const funcBeforePrintCheck = () => {
  let _status = true;

  selectRecords.value = [];
  console.log("funcBeforePrintCheck _mainData.value :>> ", _mainData.value);
  if (_mainData.value && _mainData.value.length) {
    selectRecords.value = [_mainData.value[0]];
  }

  console.log("funcBeforePrintCheck selectRecords.value :>> ", selectRecords.value);
  props.beforePrintCallback && (_status = props.beforePrintCallback(selectRecords.value));
  console.log("beforePrintCallback _status :>> ", _status);

  return _status;
};

const getSelectRecords = () => {
  return selectRecords.value;
};

const {
  printEditorRef,
  printTemplateRef,
  printerListTpDropdownRef,
  activePrint,
  hiprinterStateList,
  hiprinterStateMx,
  printerTpList,
  toGetPrinterState,
  openPrint,
  openPrintPriveiew,
  toPreviewPrintTemplate,
  toPrintPrintTemplate,
  toEditPrintTemplate,
  checkPrintTemplateList
} = usePrint(t, props.dwname, getSelectRecords, funcBeforePrintCheck, props.printDataCallback);

/**
 * 关闭后,是否刷新打印模板列表页
 * @param saved 是否有保存过
 */
const toClosedPrintEditor = (saved: boolean) => {
  saved && printTemplateRef.value?.getData();
};

const handleCheckPrintTemplateList = () => {
  console.log("handleCheckPrintTemplateList 1:>> ");
  checkPrintTemplateList("", () => {
    console.log("handleCheckPrintTemplateList 2:>> printerListTpDropdownRef.value", printerListTpDropdownRef.value);
    printerListTpDropdownRef.value && printerListTpDropdownRef.value.handleOpen();
  });
};

/**
 * @description 获取主表数据
 * @return void
 * */
// const getMainData = async () => {
//   if (!props.mainApi?.requestApi) return;
//   try {
//     // 先把初始化参数和分页参数放到总参数里面
//     // Object.assign(state.totalParam, props.initParam, {});
//     // console.log("state.totalParam :>> ", state.totalParam);
//     // state.tableLoading = true;
//     console.log("props.initParam :>> ", props.mainApi?.initParam);
//     let data = await props.mainApi?.requestApi({ ...props.mainApi?.initParam });
//     props.mainApi?.dataCallback && (data = props.mainApi?.dataCallback(data));
//     // state.tableData = isPageable ? data.list : data;
//     // state.tableLoading = false;
//     console.log("getMainData data :>> ", data);
//     mainData_api.value = data;
//     // state.tableData = data[reqProp];
//   } catch (error) {
//     props.mainApi?.requestError && props.mainApi?.requestError(error);
//     // state.tableLoading = false;
//   }
// };
// // 监听主表 initParam 改化，重新获取表格数据
// watch(() => props.mainApi?.initParam, getMainData, { deep: true });

/**
 * @description 获取详情数据
 * @return void
 * */
// const getDetailData = async () => {
//   nextTick(() => {
//     console.log("getDetailData LjDetailAffixRef.value :>> ", LjDetailAffixRef.value);
//     LjDetailAffixRef.value && LjDetailAffixRef.value.update();
//   });
//   if (!props.detailApi?.requestApi) return;
//   try {
//     // 先把初始化参数和分页参数放到总参数里面
//     // Object.assign(state.totalParam, props.initParam, {});
//     // console.log("state.totalParam :>> ", state.totalParam);
//     // state.tableLoading = true;
//     console.log("props.initParam :>> ", props.detailApi?.initParam);
//     let data = await props.detailApi?.requestApi({ ...props.detailApi?.initParam });
//     props.detailApi?.dataCallback && (data = props.detailApi?.dataCallback(data));
//     // state.tableData = isPageable ? data.list : data;
//     // state.tableLoading = false;
//     console.log("getDetailData data :>> ", data);
//     detailData_api.value = data;
//     // state.tableData = data[reqProp];
//   } catch (error) {
//     props.detailApi?.requestError && props.detailApi?.requestError(error);
//     // state.tableLoading = false;
//   }
// };
// // 监听详情 initParam 改化，重新获取表格数据
// watch(() => props.detailApi?.initParam, getDetailData, { deep: true });

/**
 * @description 打开设置界面
 */
const DetailSettingRef = ref();
const handleShowDetailSetting = () => {
  DetailSettingRef.value.show();
};

const orderBtnGroup = ref([]);
const orderOtherFunc = ref([]);

// 读取个性布局,用Map()储存
// const dwFieldMap = new Map<string, any>();
// const loadDwLayoutFunc = (loadLayout: any) => {
//   console.log("loadLayout.value :>> ", loadLayout);
//   if (JSON.stringify(loadLayout) == "{}") return false;

//   // // 个性布局加顺序号
//   // for (const i in loadLayout) {
//   //   loadLayout[i].colorder = Number(i);
//   // }

//   // 个性布局构建键值Map()
//   dwFieldMap.clear();
//   for (const item of loadLayout) {
//     dwFieldMap.set(item.field, item);
//   }
//   console.log("dwFieldMap :>> ", dwFieldMap);
// };

// // // 扁平化 初始化 columns
// const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
//   columns.forEach(async (col: any) => {
//     if (col._children?.length) flatArr.push(...flatColumnsFunc(col._children));
//     flatArr.push(col);

//     // 给每一项 column 添加默认属性
//     // col.visible = col?.visible == false ? false : props.layoutAttrDefine.visible; // true
//     // col.width = col.width ?? props.layoutAttrDefine.width; // 200
//     // col.align = col.align ?? props.layoutAttrDefine.align; // "center"
//     // col.sortable = col.sortable ?? props.layoutAttrDefine.sortable; // false
//     // col.order = col.order ?? props.layoutAttrDefine.order; // ""
//     // col.fixed = col.fixed ?? props.layoutAttrDefine.fixed; // ""
//     // col.isFilterEnum = col.isFilterEnum ?? true;

//     // 读取个性设置属性
//     if (dwFieldMap.size) {
//       let userStyle = dwFieldMap.get(col.field);
//       if (userStyle) {
//         for (let prop of props.layoutAttr) {
//           if (userStyle.hasOwnProperty(prop) && prop != "title") {
//             col[prop] = userStyle[prop];
//           }
//         }
//         col.colorder = userStyle.colorder;
//         if (userStyle.search && col.search) {
//           col.search.order = userStyle.search.order ?? undefined;
//           col.search.span = userStyle.search.span ?? undefined;
//           col.search.labelPosition = userStyle.search.labelPosition ?? undefined;
//           col.search.labelWidth = userStyle.search.labelWidth ?? undefined;
//         }
//       }
//     }

//     // 搜索栏，读取个性设置属性
//     if (col.basicinfo) {
//       col.basicinfo.labelPosition = col.basicinfo.labelPosition ?? props.basicinfoLayoutAttrDefine.labelPosition; // "top"
//       col.basicinfo.labelWidth = col.basicinfo.labelWidth ?? props.basicinfoLayoutAttrDefine.labelWidth; // 120
//       col.basicinfo.span = col.basicinfo.span ?? props.basicinfoLayoutAttrDefine.span; // 1
//     }

//     // 设置 enumMap
//     setEnumMap(col);
//   });

//   // 读取个性设置后，排序，
//   if (dwFieldMap.size) {
//     flatArr.sort((a, b) => {
//       return a.colorder! - b.colorder!;
//     });
//   }
//   return flatArr.filter(item => !item._children?.length);
// };

// 定义 enumMap 存储 enum 值（避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择）
const enumMap = ref(new Map<string, { [key: string]: any }[]>());

/**
 * @description 当编辑状态不是从route中获取时，需要手动更新
 */
watch(
  () => props.enum,
  (val: any) => {
    val &&
      val.forEach((val: any, key: any) => {
        enumMap.value.set(key, val);
      });
  },
  { immediate: true, deep: true }
);

// if (props.enum) {
//   props.enum.forEach((val: any, key: any) => {
//     enumMap.value.set(key, val);
//   });
// }
provide("mainEnumMap", enumMap);
const setEnumMap = async (col: ColumnProps) => {
  if (!col.enum) return;

  console.log("deftail setEnumMap col :>> ", col);
  // 如果当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
  if (typeof col.enum !== "function") {
    let _enum = col.enum!;
    if (col.enumFilter) {
      _enum = col.enumFilter(totalParam.value, _enum, orderStatus.value);
    }
    return enumMap.value.set(col.field!, _enum);
  }
  const data = await col.enum();
  enumMap.value.set(col.field!, data);
};

/**
 * @description 当前布局
 */
const dwnameLayout = computed(() => {
  return props.dwname + "__layout-detail";
});
// /**
//  * @description 当前基础信息的布展示列field集合
//  */
// const showFields = ref<string[]>([]);

const initLayoutColumns = () => {
  console.log("initLayoutColumns enumMap :>> ", enumMap);
  // 数行化，还原个性设置
  tableColumns.value = loadRenderAttr(flatColumns.value);
  // tableRef.value?.reloadColumn(tableColumns.value);
  console.log("数行化，还原个性设置 tableColumns.value :>> ", tableColumns.value);
  console.log("数行化，还原个性设置 flatColumns.value :>> ", flatColumns.value);

  // /**过滤主表基础信息配置项 */
  // let _showColumns = [];
  // switch (orderStatus.value) {
  //   case "new":
  //     _showColumns = tableColumns.value.filter((item: any) => {
  //       if (item.basicinfo?.el || item.basicinfo?.render) {
  //         return item.basicinfo?.editable ? item.basicinfo?.editable.includes("new") : true;
  //       } else {
  //         return false;
  //       }
  //     });
  //     break;
  //   case "edit":
  //     _showColumns = tableColumns.value.filter((item: any) => {
  //       if (item.basicinfo?.el || item.basicinfo?.render) {
  //         return item.basicinfo?.editable ? item.basicinfo?.editable.includes("edit") : true;
  //       } else {
  //         return false;
  //       }
  //     });
  //     break;
  //   default:
  //     _showColumns = tableColumns.value.filter(
  //       (item: any) => !TABLE_TYPE_FILTER.includes(item.type!) && item.field !== "operation" && item.visible !== false
  //     );
  //     break;
  // }

  // // showFields.value = _showColumns.map((item: any) => item.field);
  // console.log("detail init infoColumns.value :>> ", _showColumns);
  // console.log("detail init tableColumns.value :>> ", tableColumns.value);

  // // if (props.mainDwname) {
  // //   let basicLayout = [];
  // //   console.log("basemsg indexawait layoutStore.getDwLayout(props.dwname) :>> ", await layoutStore.getDwLayout(props.mainDwname));
  // //   let layout = await layoutStore.getDwLayout(props.mainDwname);
  // //   console.log("layout :>> ", layout);
  // //   if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
  // //     typeof layout.itemvalue == "string" && (layout.itemvalue = JSON.parse(layout.itemvalue.replace(/'/g, '"')));
  // //     // 兼容部分结构直接记录行数据
  // //     if (layout.itemvalue.hasOwnProperty("columns") && layout.itemvalue.columns) {
  // //       basicLayout = layout.itemvalue.columns;
  // //     } else {
  // //       basicLayout = layout.itemvalue;
  // //     }
  // //   }
  // //   loadDwLayoutFunc(basicLayout);
  // // }
  // // // 扁平化，并读取个性设置
  // // infoColumns.value = flatColumnsFunc(_showColumns, dwFieldMap);
  // 过滤需要搜索的配置项
  infoColumns.value = flatColumns.value.filter((item: any) => item.field && item.field != "pid");

  console.log("detail init bf  end infoColumns.value :>> ", infoColumns.value, infoParam.value);
  // console.log("detail init 1end infoColumns.value :>> ", infoColumns.value);
  // 设置搜索表单排序默认值 && 设置搜索表单项的默认值
  infoColumns.value.forEach((column, index) => {
    !Object.keys(column).includes("basicinfo") && (column.basicinfo = {});
    column.basicinfo!.order = column.basicinfo!.order ?? index + 2;
    if (column.basicinfo?.defaultValue !== undefined && column.basicinfo?.defaultValue !== null) {
      // searchInitParam.value[column.basicinfo.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue;
      infoParam.value[column.basicinfo.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue;
    } else {
      // 为新增单据的时候赋值
      let defVal: string | number = "";
      column?.basicinfo?.el == "input-number" && (defVal = 0);
      infoParam.value[column?.basicinfo?.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue ?? defVal;
    }
    column.rules = column.basicinfo?.rules ?? undefined;
  });
  console.log("props.defaultColumnsValue :>> ", props.defaultColumnsValue);
  infoParam.value = defaultsDeep(cloneDeep(props.defaultColumnsValue), infoParam.value);
  // // 表格搜索栏,设置缓存搜索信息
  // Object.assign(searchParam.value, queryHabit);
  // 第一次搜索带入参数
  // totalParam.value = searchParam.value;

  /** 赋值初始化搜索表单 */
  if (props.initParam) {
    for (const key in props.initParam) {
      !Object.keys(searchParam.value).includes(key) && (searchParam.value[key] = props.initParam[key]);
    }
  }
  // 第一次搜索带入参数
  totalParam.value = searchParam.value;
  console.log("detail infoParam.value :>> ", infoParam.value);

  // 排序搜索表单项
  infoColumns.value.sort((a, b) => a.basicinfo!.order! - b.basicinfo!.order!);
  console.log("detail init end infoColumns.value :>> ", infoColumns.value);
  // console.log("searchParam.value :>> ", searchParam.value);
};

const init = async () => {
  // 初始化布局
  await loadLayoutFunc();

  initLayoutColumns();

  props.action && (orderBtnGroup.value = funcFilterPower(props.action));
  props.rightAction && (orderOtherFunc.value = funcRightActionPower(props.rightAction));
};

/**
 * @description 读取布局
 */
const getLayout = async () => {
  let res: any = await layoutLocalStore.getLayoutAttr(dwnameLayout.value);
  console.log("LJgetLayout getLayout res :>> ", res);
  console.log("LJgetLayout props :>> ", props);
  let _props = omit(props, ["mainData"]);
  console.log("LJgetLayout _props :>> ", _props);
  let _define = defaultsDeep(_props, { header: DETAIL_LAYOUT_DEFINE });

  console.log("LJgetLayout _define :>> ", _define);
  currentMould.value = setDifference(_define, res);
  console.log("LJgetLayout currentMould.value :>> ", currentMould.value);

  // 加载主表-基础信息布局
  await init();
};

/**
 * @description 页面刷新
 */
const layoutRefresh = inject("layoutRefresh", () => {});

/**
 * @description 悬浮按钮位置变化时，保存悬浮按钮位置
 */
const toSetFloatBtnChange = (id: string, left: number, top: number) => {
  console.log("detail funcFloatBtnChange field, left ,top :>> ", id, left, top);

  let _layout = cloneDeep(currentMould.value);
  let _idx = _layout.header.floatbtn.findIndex((item: any) => item.id == id);
  if (_idx > -1) {
    _layout.header.floatbtn[_idx].originLeft = left;
    _layout.header.floatbtn[_idx].originTop = top;
  } else {
    _layout.header.floatbtn.push({
      id,
      originLeft: left,
      originTop: top
    });
  }
  let _props = pick(props, DETAIL_LAYOUT_ATTR);

  funcSaveDwLayout(_props, _layout, false, false);
};
/**
 * @description 保存当前布局
 */
const toSetDetailBase = (layout: any, callback?: any, toast: boolean = true) => {
  console.log("LJgetLayout props :>> ", props);
  console.log("toSetDetailBase layout :>> ", JSON.stringify(layout));
  let _props = pick(props, DETAIL_LAYOUT_ATTR);
  /** 原布局清空部分属性，为保留该属性下全部属性值；这些属性，需要在传输进来前处理（精简化处理，过滤默认值）*/
  _props.header.foldright = {};
  _props.header.foldleft = {};
  _props.header.mxprops = {};

  // let _layout = pick(layout, DETAIL_LAYOUT_ATTR);
  // console.log("_layout :>> ", _layout);
  // let diff = getDifference(_props, _layout, props.detailLayoutAttr);
  // console.log("toSetDetailBase diff :>> ", diff);

  // let _toast = toast ? t : undefined;

  // // 保存布局
  // layoutLocalStore.setDwLayout(dwnameLayout.value, diff, _toast).then(() => {
  //   if (callback) {
  //     callback();
  //     layoutRefresh();
  //   }
  //   // callback && callback();
  //   currentMould.value = layout;
  // });
  funcSaveDwLayout(_props, layout, callback, toast);
};

const funcSaveDwLayout = (arg_prop: any, layout: any, callback?: any, toast: boolean = true) => {
  let _layout = pick(layout, DETAIL_LAYOUT_ATTR);
  console.log("_layout :>> ", _layout);
  console.log("arg_prop :>> ", arg_prop);
  let diff = getDifference(arg_prop, _layout, props.detailLayoutAttr);
  console.log("toSetDetailBase diff :>> ", diff);

  let _toast = toast ? t : undefined;

  // 保存布局
  layoutLocalStore.setDwLayout(dwnameLayout.value, diff, _toast).then(() => {
    if (callback) {
      callback();
      layoutRefresh();
    }
    // callback && callback();
    currentMould.value = layout;
  });
};

const beforeToSetting = () => {
  if (props.ifFoldLayout && LjFoldLayoutRef.value) {
    console.log("LjFoldLayoutRef.value.currentLayout :>> ", LjFoldLayoutRef.value.currentLayout);
    let _layout = LjFoldLayoutRef.value.currentLayout;
    if (_layout.right.width > 0 && _layout.right.lastWidth == 0) {
      let curWidth = _layout.right.width;
      _layout.right.lastWidth = curWidth;
      _layout.right.width = 0;
      toSaveFoldLayout(_layout, "foldright", "right");
    }
  }
};

const beforeCloseSetting = () => {
  if (props.ifFoldLayout && LjFoldLayoutRef.value) {
    console.log("LjFoldLayoutRef.value.currentLayout :>> ", LjFoldLayoutRef.value.currentLayout);
    let _layout = LjFoldLayoutRef.value.currentLayout;
    if (_layout.right.width == 0 && _layout.right.lastWidth > 0) {
      let curWidth = _layout.right.lastWidth;
      _layout.right.width = curWidth;
      _layout.right.lastWidth = 0;
      toSaveFoldLayout(_layout, "foldright", "right");
    }
  }
};

/**
 * @description 监听框架属性变化
 */
const toSaveFoldLayout = (layout: any, saveAttr: string, readAttr: string) => {
  console.log("toSaveFoldLayout layout :>> ", layout);
  let _layout = cloneDeep(currentMould.value);
  let _define = cloneDeep(_layout.header[saveAttr]);
  _layout.header[saveAttr] = pick({ ..._define, ...layout[readAttr] }, FoldLayoutFilterAttr);
  toSetDetailBase(_layout, false, false);
};

// const columnStreamlineFunc = (column: any, searchColumns: any) => {
//   let saveCol = streamlineFunc(column, props.layoutAttr, props.layoutAttrDefine);
//   console.log("columnStreamlineFunc settingConfirm bf saveCol :>> ", saveCol);

//   // 简化搜索储存字段，以props.basicinfoLayoutAttr为标准
//   let searchMap = streamlineAttrFunc(searchColumns, props.basicinfoLayoutAttr, props.basicinfoLayoutAttrDefine, "basicinfo");
//   // let searchMap = new Map();
//   // for (let item of searchColumns) {
//   //   let saveProp = cloneDeep(props.basicinfoLayoutAttr);
//   //   if (item.basicinfo) {
//   //     for (let key in props.basicinfoLayoutAttrDefine) {
//   //       if (item.basicinfo.hasOwnProperty(key) && props.basicinfoLayoutAttrDefine[key] === item.basicinfo[key]) {
//   //         saveProp.splice(saveProp.indexOf(key), 1);
//   //       }
//   //     }
//   //     searchMap.set(item.field, pick(item.basicinfo, saveProp));
//   //   }
//   // }

//   // 合并
//   if (searchMap.size) {
//     for (let item of saveCol) {
//       let _map = searchMap.get(item.field);
//       if (_map) {
//         item.basicinfo = _map;
//       }
//     }
//   }
//   console.log("columnStreamlineFunc settingConfirm aaaf saveCol :>> ", saveCol);
//   return saveCol;
// };

/**
 * @description 基础设置: 保存基础信息布局方法
 * @param columns 处理后的基础信息布局，[group,....]
 * @param formParams basicinfo参数
 * @param {boolean} online 是否获取线上版本
 * @param {number} empid 员工id
 */
const saveColumnsFunc = async (argColumns: any, formParams: any, online: boolean = false, empid?: number) => {
  let _data = cloneDeep(argColumns);
  let scol: any = [];
  /**还原：一维数组 */
  _data.map((item: any) => {
    let _list = item.list.map((itm: any) => {
      // itm.basicinfo.group = item.label;
      if (item.label) {
        itm.basicinfo.group = item.label;
      } else {
        itm.basicinfo.group = itm.basicinfo.group || itm.basicinfo.group === "" ? "" : undefined;
      }
      itm.basicinfo.visible = itm.basicinfo.visible !== false;
      return itm;
    });
    scol = scol.concat(_list);
  });

  /**记录顺序 */
  scol.forEach((item: any, index: number) => (item.basicinfo.order = index + 1));

  console.log("sort scol dwFieldMap:>> ", scol, JSON.stringify(dwFieldMap.get("typeid")));

  // 获取原始数据列
  let oriColumns = await getOriColumns(false, online, empid);
  // let oriColumns = cloneDeep(flatColumns.value);
  console.log("saveColumnsFunc oriColumns dwFieldMap:>> ", oriColumns, dwFieldMap);
  // loadDwLayoutFunc(oriColumns, true);

  // 仅仅读取详情页的basicinfo部分，其他读取原有
  let loadMaps = new Map();
  for (const sitm of scol) {
    let oriMap = dwFieldMap.get(sitm.field);
    console.log("sitm :>> ", oriMap, sitm);
    if (oriMap) {
      oriMap.basicinfo = sitm.basicinfo ?? oriMap.basicinfo;
    } else {
      oriMap = sitm;
    }
    loadMaps.set(sitm.field, oriMap);
  }
  console.log("after!!! dwFieldMap :>> ", dwFieldMap);
  console.log("after!!! loadMaps :>> ", JSON.stringify(loadMaps));
  console.log("after!!! oriColumns :>> ", JSON.stringify(oriColumns));
  // 扁平化，并读取个性设置
  let _saveCol = flatColumnsFunc(oriColumns.columns, loadMaps);
  console.log("saveBasicSettingFunc _saveCol :>> ", _saveCol);

  // let _save = cloneDeep(tableOptions);
  // _save.basicinfo = formParams;
  let oriOtherParams = omit(oriColumns, ["columns"])?.tableprop ?? tableOptions;
  oriOtherParams.basicinfo = formParams;
  console.log("_save :>> ", oriOtherParams);
  console.log("(props.columns) :>> ", JSON.stringify(props.columns));
  return columnStreamlineFunc(_saveCol, oriOtherParams, props.columns);
};

/**
 * @description 搜索栏，布局保存
 * @param columns 数据列
 * @param formParams basicinfo参数
 * @param callback 完成保存后返回
 */
const saveBasicSettingFunc = async (columns: any, formParams: any, callback: any) => {
  if (!props.dwname) {
    ElMessage.error("LjDetail未设置储存的模版名称，无法保存");
    return false;
  }

  console.log("saveBasicSettingFunc columns :>> ", columns);
  console.log("saveBasicSettingFunc formParams :>> ", JSON.stringify(formParams));
  console.log("saveBasicSettingFunc formParams :>> ", formParams);

  let layout = await saveColumnsFunc(columns, formParams);

  console.log("saveBasicSettingFunc await layout :>> ", layout);
  // 保存布局-主表
  await layoutStore.setDwLayout(props.dwname, layout, t);

  // 复原各属性enum
  layout.columns.forEach((item: any) => {
    if (enumMap.value.has(item.field)) {
      item.enum = enumMap.value.get(item.field);
    }
  });

  loadDwLayoutFunc(layout.columns);
  tableColumns.value = cloneDeep(props.columns);
  console.log("after loadDwLayoutFunc dwFieldMap.value :>> ", tableColumns.value, dwFieldMap);
  // 扁平化，并读取个性设置
  flatColumns.value = flatColumnsFunc(tableColumns.value, dwFieldMap);

  initLayoutColumns();

  loadLayoutCallBack(layout);

  callback && callback();
};

/**
 * @description 基础设置: 保存系统默认模版
 */
const saveDefaultLayout = async (columns: any, formParams: any, callback?: any) => {
  if (!props.dwname) {
    ElMessage.error("LjVextable组件未设置储存的模版名称，无法保存");
    return false;
  }

  let layout = await saveColumnsFunc(columns, formParams, true, -1);

  console.log("saveDefaultLayout layout :>> ", layout);

  await layoutStore.saveDwLayout_online(-1, props.dwname, layout);

  callback && callback();
};

const initLayoutColFunc = (data: any) => {
  console.log("initLayoutColFunc enumMap :>> ", enumMap);
  let result = cloneDeep(data);

  loadRenderAttr(result.columns);
  console.log("result.columns :>> ", JSON.stringify(result.columns));
  // 过滤需要搜索的配置项
  result.columns = result.columns.filter((item: any) => item.field && item.field != "pid");

  console.log("detail init bf  end infoColumns.value :>> ", result.columns);
  // console.log("detail init 1end infoColumns.value :>> ", infoColumns.value);
  // 设置搜索表单排序默认值 && 设置搜索表单项的默认值
  result.columns.forEach((column: any, index: number) => {
    !Object.keys(column).includes("basicinfo") && (column.basicinfo = {});
    column.basicinfo!.order = column.basicinfo!.order ?? index + 2;
    if (column.basicinfo?.defaultValue !== undefined && column.basicinfo?.defaultValue !== null) {
      // searchInitParam.value[column.basicinfo.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue;
      infoParam.value[column.basicinfo.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue;
    } else {
      // 为新增单据的时候赋值
      let defVal: string | number = "";
      column?.basicinfo?.el == "input-number" && (defVal = 0);
      infoParam.value[column?.basicinfo?.key ?? handleProp(column.field!)] = column.basicinfo?.defaultValue ?? defVal;
    }
    column.rules = column.basicinfo?.rules ?? undefined;
  });
  // // 表格搜索栏,设置缓存搜索信息
  // Object.assign(searchParam.value, queryHabit);
  // 第一次搜索带入参数
  // totalParam.value = searchParam.value;
  console.log("detail infoParam.value :>> ", infoParam.value);

  // 排序搜索表单项
  result.columns.sort((a: any, b: any) => a.basicinfo!.order! - b.basicinfo!.order!);
  console.log("initLayoutColFunc detail init end infoColumns.value :>> ", result);
  // console.log("searchParam.value :>> ", searchParam.value);
  return result;
};

/**
 * @description 基础设置: 重置
 */
const resetBasicSettingFunc = async (callback: any) => {
  // 获取原始数据列
  let oriColumns = await getOriColumns(true, true, -1, enumMap.value, props.columns);
  console.log("resetBasicSettingFunc enumMap :>> ", enumMap.value);
  console.log("resetBasicSettingFunc oriColumns -1:>> ", oriColumns);
  oriColumns = initLayoutColFunc(oriColumns);
  callback && callback(oriColumns);
  // if (oriColumns.columns.length) {
  //   callback && callback(oriColumns);
  // } else {
  //   ElMessage.warning(t("sys.layout.empty") + props.dwname);
  //   // 获取原始数据列
  //   oriColumns = await getOriColumns(true);
  //   console.log("resetBasicSettingFunc oriColumns :>> ", oriColumns);
  //   if (oriColumns.columns.length) {
  //     oriColumns = initLayoutColFunc(oriColumns);
  //     callback && callback(oriColumns);
  //   } else {
  //     ElMessage.warning(t("sys.layout.singleEmpty"));
  //     callback && callback({ columns: props.columns, tableprop: { basicinfo: tableOptions.basicinfo } });
  //   }
  // }

  // layoutStore.getDwLayout_online(-1, props.dwname!, 0).then((layout: any) => {
  //   console.log("resetBasicSettingFunc layout :>> ", layout);

  //   if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
  //     let dwLayout: ColumnProps[] = [];
  //     console.log("resetSetting loadLayoutFunc layout :>> ", layout);
  //     if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
  //       // 表格结构： {tableprop: string, columns: string}
  //       typeof layout.itemvalue == "string" && (layout.itemvalue = JSON.parse(layout.itemvalue.replace(/'/g, '"')));
  //       // 兼容部分结构直接记录行数据
  //       if (layout.itemvalue.hasOwnProperty("columns") && layout.itemvalue.columns) {
  //         dwLayout = layout.itemvalue.columns;
  //       } else {
  //         dwLayout = layout.itemvalue;
  //       }
  //     }

  //     // 读取默认属性
  //     loadDwLayoutFunc(props.columns, false);

  //     let prototype = flatColumnsFunc(dwLayout, dwFieldMap);
  //     /**备用（重置）：原始数据列 */
  //     let _oriCol = prototype.filter((item: any) => !TABLE_TYPE_FILTER.includes(item.type!) && item.field !== "operation");

  //     /**只重置basicinfo的属性 */
  //     let _columns = flatColumns.value.map((item: any) => {
  //       let oriItem = _oriCol.find((oriItem: any) => oriItem.field == item.field);
  //       return {
  //         ...item,
  //         basicinfo: oriItem?.basicinfo ?? {}
  //       };
  //     });
  //     _columns = _columns.filter((item: any) => item.field && item.field != "pid");

  //     console.log("resetBasicSettingFunc _columns :>> ", _columns);

  //     callback && callback(_columns);
  //   } else {
  //     ElMessage.warning(t("sys.layout.empty") + props.dwname);
  //     callback && callback([]);
  //   }
  // });
};

/**
 * 检查功能权限
 * @param action detail/edit/add 赋值动作
 * @param power 权限值
 * @param powerFunc 状态判断函数
 * @param errorback 错误返回
 */
const checkPowerFunc = (action: string, power: number | any, errorback: any) => {
  if (power) {
    if (isNumber(power)) {
      if (CheckPower(power)) {
        orderStatus.value = action;
      } else {
        orderStatus.value = "";
        errorback && errorback();
      }
    } else if (isFunction(power)) {
      if (power(_mainData.value)) {
        orderStatus.value = action;
      } else {
        orderStatus.value = "";
        errorback && errorback();
      }
    }
  } else {
    orderStatus.value = action;
  }
};

// const headerStatusList = ref<ColumnProps[]>([]);x
// const getHeaderStatus = () => {
//   if (!props.headerstatus?.length) return;

//   headerStatusList.value = infoColumns.value.filter((item: any) => props.headerstatus!.includes(item.field));
// };

/**
 * @description 点击tabs标题
 */
const handleClickTabs = (data: any) => {
  // 启用foldLayout布局时，点击tabs标题时，若是折叠了，自动恢复
  if (LjFoldLayoutRef.value) {
    let _layout = LjFoldLayoutRef.value.currentLayout;
    if (_layout.right.lastWidth > 0) {
      LjFoldLayoutRef.value.foldRight();
    }
  }
  // 记录当前tabs状态
  if (props.dwname) {
    let _detailtabs = globalStore.detailtabs ?? {};
    _detailtabs[props.dwname] = data.name;
    globalStore.setGlobalState("detailtabs", _detailtabs);
  }

  emit("tabsClick", data);
};

/**
 * @description 表单校验
 * @param formEl
 */
const toValidateForm = async () => {
  const { element } = LjDetailBaseFormRef.value;
  if (!element) return;
  return await element.validate();
};

/**
 * @description 当编辑状态不是从route中获取时，需要手动更新
 */
watch(
  () => props.orderStatus,
  (val: any) => {
    val && (orderStatus.value = val);
  },
  { immediate: true }
);

onMounted(async () => {
  if (route.path.indexOf("new") > -1) {
    checkPowerFunc("new", props.addPower, () => {
      ElNotification({
        title: t("sys.api.operationFailed"),
        message: t("sys.errorLog.notPower") + ":" + props.addPower,
        type: "warning"
      });
    });
    console.log("反向更新订单状态 orderStatus.value :>> ", orderStatus.value);
    // 反向更新订单状态
    emit("update:orderStatus", orderStatus.value);
  } else if (route.path.indexOf("edit") > -1) {
    checkPowerFunc("edit", props.editPower, () => {
      ElNotification({
        title: t("sys.api.operationFailed"),
        message: t("sys.errorLog.notPower") + ":" + props.editPower,
        type: "warning"
      });
    });
    // 反向更新订单状态
    emit("update:orderStatus", orderStatus.value);
  } else if (route.path.indexOf("copy") > -1) {
    checkPowerFunc("copy", props.editPower, () => {
      ElNotification({
        title: t("sys.api.operationFailed"),
        message: t("sys.errorLog.notPower") + ":" + props.editPower,
        type: "warning"
      });
    });
    // 反向更新订单状态
    emit("update:orderStatus", orderStatus.value);
  }
  console.log("反向更新订单状态 orderStatus.value :>> ", orderStatus.value, props.orderStatus);

  // 读取布局记录
  await getLayout().then(() => {
    nextTick(() => {
      let element = document.getElementById(prefixCls);
      headerAffixTop.value = element?.getBoundingClientRect().top ?? 0;

      headerAffixHeight.value = document.querySelector("." + prefixCls + "__header")?.clientHeight ?? 0;

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

    // if (orderStatus.value != "new") {
    // props.mainApi?.requestAuto && getMainData();
    // props.detailApi?.requestAuto && getDetailData();
    // }
  });

  if (props.requestAuto) {
    getTableList().then(() => {
      console.log("getTableList orderStatus.value :>> ", orderStatus.value, tableData.value);
      if (props.requestApi && !tableData.value.length && orderStatus.value != "new") {
        ElNotification({
          title: t("sys.api.selectFailed"),
          message: t("sys.api.selectFailedMessage"),
          type: "warning"
        });
      } else {
        emit("afterMounted", _mainData.value);
      }
    });
  } else {
    console.log("onMounted detail end!!!! :>> ");
    emit("afterMounted", _mainData.value);
  }
});

const toPinDetailClick = () => {
  emit("toPinDetail");
};

/**
 * @description render 右侧固定菜单(print printMx)，下拉Item
 */
const RenderPrinterTpItem = (item: any) => {
  return (
    <el-dropdown-item class="flx-justify-between" onClick={() => openPrintPriveiew("", item, Boolean(item.printer))}>
      {item.aliase || item.printid}
      {item.printer && (
        <el-tooltip
          effect="dark"
          content={t("sys.print.directPrint")}
          placement="top"
          show-after={200}
          enterable={false}
          hide-after={0}
        >
          <i class="iconfont iconflash ml-8" style={{ color: _variables.colorPolarGreen4 }}></i>
        </el-tooltip>
      )}
    </el-dropdown-item>
  );
};

/**
 * @description 过滤表格按钮权限
 * @param type 按钮类型
 */
const getRightActionPower = (type: string) => {
  let _idx = props.rightFixedAction.indexOf(type);

  if (_idx > -1) {
    if (
      props.rightFixedActionPower.length &&
      _idx < props.rightFixedActionPower.length &&
      props.rightFixedActionPower[_idx] != 0
    ) {
      return CheckPower(props.rightFixedActionPower[_idx]);
    } else {
      return true;
    }
  }
  return false;
};

/**
 * @description 打印模板下拉列表
 */
const getRenderRightFixedAction = () => {
  let _render: any = [];
  console.log("getRenderRightFixedAction :>> ", props.rightFixedAction);
  if (!props.rightFixedAction.length) return _render;

  props.rightFixedAction.map((itemAction: any) => {
    console.log("itemAction :>> ", itemAction, getRightActionPower(itemAction));
    switch (itemAction) {
      case "print":
        if (printerTpList.value.length) {
          console.log("printerTpList.value :>> ", printerTpList.value);
          printerTpList.value.map((item: any) => {
            _render.push(RenderPrinterTpItem(item));
          });
        }
        console.log("_render_dd_item :>> ", _render);
        break;
      case "printMx":
        // 明细打印

        break;

      default:
        break;
    }
  });
  console.log("_render.length, _render :>> ", _render.length, _render);
  return _render;
};

/**
 * @deascription 渲染：默认头部render
 * @param rProp prop
 */
const RenderHeaderDefault = (rProp: any) => {
  console.log("RenderHeaderDefault rProp :>> ", rProp);
  console.log("RenderHeaderDefault _mainData.value :>> ", _mainData.value);
  let nameValue = convertStrToObj(_mainData.value, props.header.fieldNames?.name);
  let _params =
    orderStatus.value == "new" ? infoParam.value : orderStatus.value == "edit" ? reactive(_mainData.value) : _mainData.value;
  let _assemblySize = globalStore.assemblySize == "small" ? "default" : "large";
  let _height = globalStore.assemblySize == "small" ? "32px" : "40px";
  let pinBtnSlot = {
    icon: () => {
      return (
        <i
          class={{
            iconfont: true,
            "iconpin-02": currentLayout.value?.right.hidden,
            "iconpin-01": !currentLayout.value?.right.hidden
          }}
        ></i>
      );
    }
  };

  let allowPowerAction = orderBtnGroup.value;

  /**
   * @description 折叠的单据功能菜单
   */
  let _render_right_action: any = [];
  let hasRightAction = rProp?.rightAction && rProp.rightAction.length;
  if (hasRightAction) {
    orderOtherFunc.value.map((item: any) => {
      _render_right_action.push(
        <DropdownList
          update={nameValue}
          target="detail-button-group"
          buttons={item}
          data={_params}
          assemblySize={_assemblySize}
        />
      );
    });
  }

  /**
   * @description 右侧固定下拉菜单
   */
  let _render_right_fixed_action: any = [];
  let hasRightFixedAction = rProp?.rightFixedAction && rProp.rightFixedAction.length;
  if (hasRightFixedAction) {
    rProp.rightFixedAction.map((itemAction: any) => {
      if (!getRightActionPower(itemAction)) return;

      switch (itemAction) {
        case "print":
          // 订单打印
          let _render_dd_item = getRenderRightFixedAction();
          let hasPrinterList = Boolean(printerTpList.value.length);
          let _slotsRightFixedAction = {
            dropdown: () => {
              return (
                <>
                  <el-dropdown-menu>
                    <>
                      {hasPrinterList && _render_dd_item}
                      <el-dropdown-item divided={hasPrinterList} onClick={() => openPrint("")}>
                        <div class="flx-center">
                          <el-icon>
                            <Setting />
                          </el-icon>
                          {t("common.setText")}
                        </div>
                      </el-dropdown-item>
                    </>
                  </el-dropdown-menu>
                </>
              );
            }
          };

          _render_right_fixed_action.push(
            <el-dropdown
              trigger="contextmenu"
              placement="bottom-end"
              ref={printerListTpDropdownRef}
              v-slots={_slotsRightFixedAction}
            >
              <el-button icon={Printer} circle onClick={handleCheckPrintTemplateList}></el-button>
            </el-dropdown>
          );
          break;
        case "printMx":
          // 明细打印

          break;
        default:
          break;
      }
    });
  }

  return (
    <>
      {allowPowerAction.length > 0 && (
        <div class={["flx w-full flx-justify-between", `${prefixCls}__header-inner`]} style={{ height: _height }}>
          <div class="flx-start flx-1" id="detail-button-group">
            <ButtonGroup
              update={nameValue}
              target="detail-button-group"
              buttons={allowPowerAction}
              data={_params}
              assemblySize={_assemblySize}
            ></ButtonGroup>
          </div>
          <div class="flx-end flx-shrink mr-12">
            {nameValue && (
              <>
                <span class={["text-h4-r", "text-disable", hasRightAction ? "mr-8" : ""]}>{nameValue}</span>
              </>
            )}
            {_render_right_action}
            {_render_right_fixed_action}
            {(nameValue || hasRightAction) && <el-divider direction="vertical" />}
            <div class="setting-part">
              {rProp.ifLayoutEditable && <el-button circle icon={Tools} onClick={handleShowDetailSetting}></el-button>}
              {currentLayout.value && (
                <el-button class="tag-item" circle onClick={toPinDetailClick} v-slots={pinBtnSlot}></el-button>
              )}
              {slots.rightBtn && slots.rightBtn?.({ data: _mainData.value })}
            </div>
          </div>
        </div>
      )}
    </>
  );
};

const RenderDetailHeader = (rProp: any) => {
  console.log("route.meta.icon :>> ", route.meta.icon);
  let iconRender = [];
  // if (rProp.header?.icon) {
  // switch (typeof rProp?.header.icon) {
  //   case "object":
  //     iconRender.push(<el-icon>{rProp.header.icon.render()}</el-icon>);
  //     break;
  //   case "function":
  //     iconRender.push(rProp.header.icon());
  //     break;
  //   case "string":
  //     iconRender.push(<i class={["iconfont", rProp.header.icon]} />);
  //     break;
  // default:
  iconRender.push(<i class={["iconfont", route.meta.icon]} />);
  //     break;
  // }
  // }
  console.log("iconRender :>> ", iconRender);
  let codeValue = convertStrToObj(_mainData.value, props.header.fieldNames?.code);

  // console.log("rProp.headerstatus :>> ", props.headerstatus);
  // let statusRender: any = [];
  // if (props.headerstatus?.length) {
  //   let headerStatusList = infoColumns.value.filter((item: any) => props.headerstatus!.includes(item.field));
  //   headerStatusList.map((item: any) => {
  //     console.log("headerStatusList item :>> ", item);
  //     if (!item.render) {
  //       /** 复选框 */
  //       if (item?.datatype == "checkbox") {
  //         // item.render = (scope: any) => {
  //         //   let _keys = Object.keys(scope);
  //         //   let _data = _keys.includes("row") ? scope.row : _keys.includes("searchParam") ? scope.searchParam : scope;
  //         //   let _field = scope?.column.field ?? "";
  //         switch (Number(_mainData.value[item.field])) {
  //           case 1:
  //             statusRender.push(<el-checkbox class={"el-checkbox__disabled-checked"} checked={true} disabled={true} />);
  //           default: // 0
  //             let bool = false;
  //             statusRender.push(<el-checkbox v-model={bool} disabled={true} />);
  //         }
  //       }

  //       // }
  //       // /**普通：enum,数值转文本 */
  //       // if (item.enum && item.enum.length) {
  //       //   item.render = (scope: any) => {
  //       //     let _keys = Object.keys(scope);
  //       //     let _data: any = _keys.includes("row") ? scope.row : _keys.includes("searchParam") ? scope.searchParam : scope;
  //       //     let _field = scope?.column.field ?? "";
  //       //     let _item: any = {};
  //       //     scope.enum && (_item = scope.enum.find((item: any) => item.value == Number(_data[_field])));
  //       //     return _item?.label ?? "";
  //       //   };
  //       // }
  //     } else {
  //       statusRender.push(item.render({ scope: _mainData.value[0], column: item, enum: item.enum }));
  //     }
  //   });
  // }
  // console.log("statusRender :>> ", statusRender);

  const childrenSlot = {
    template: () => {
      return (
        <>
          <el-skeleton-item variant="caption" />
          <el-skeleton-item variant="text" style="width: 50%;" />
        </>
      );
    }
  };

  return (
    <>
      {/* <div class={["flx w-full flx-start", `${prefixCls}__header-inner`]}> */}
      <div class={`flx-start  ${prefixCls}__detail-header`}>
        <div class={`${prefixCls}__header-icon flx-center mr-8`}>{iconRender}</div>
        <div class="text-h4-m flx-col">
          <el-skeleton style="width: 220px;height:50px" animated loading={!codeValue} v-slots={childrenSlot}>
            {convertStrToObj(_mainData.value, props.header.fieldNames?.name)}
            {codeValue && (
              <span class="text-body-m text-secondary-text">
                {(props.header.fieldNames?.codeLabel ? props.header.fieldNames.codeLabel : "") + codeValue}
              </span>
            )}
          </el-skeleton>
        </div>
        {/* {codeValue && (
          <span class="text-h4-r text-secondary-text">
            {(props.header.fieldNames?.codeLabel ? props.header.fieldNames.codeLabel : "") + codeValue}
          </span>
        )} */}
        {/* <div class="setting-part">{statusRender}</div> */}
      </div>
      {/* </div> */}
    </>
  );
};

const tasItemRender = (data: detailModelItemProp, renderFnc: any, header = true, disabled = false) => {
  let val = _detailData.value && _detailData.value[data.id];
  // console.log(" _detailData.value :>> ", _detailData.value, data.id);
  let vanSlot: any = {};
  if (slots[data.id + "__tabtitle"]) {
    vanSlot.title = () => {
      return <>{slots[data.id + "__tabtitle"]?.({ data: val, props: data })}</>;
    };
  }
  if (isScrollspy.value && slots[data.id + "_header"]) {
    vanSlot[data.id + "_header"] = () => {
      if (slots[data.id + "_header"]) {
        return slots[data.id + "_header"]?.({ data: val, props: data });
      } else if (header) {
        return <LjHeader title={data.label}></LjHeader>;
      }
    };
  }
  vanSlot.default = () => renderFnc();
  return <van-tab name={data.id} title={data.label} disabled={disabled} v-slots={vanSlot}></van-tab>;
  // return (
  //   <van-tab name={data.id} title={data.label} v-slots={vanSlot}>
  //     <>
  //       {isScrollspy.value &&
  //         (slots[data.id + "_header"]
  //           ? slots[data.id + "_header"]?.({ data: val, props: data })
  //           : header && <LjHeader title={data.label}></LjHeader>)}
  //     </>
  //     {renderFnc()}
  //   </van-tab>
  // );
};

/**
 * @deascription 渲染：van-tabs主体
 * @param rProp prop
 */
const RenderTabs = (rProps: DetailProp) => {
  console.log("RenderTabs. :>> ", rProps, _mainData.value);
  let tabRender: any = [];
  let _sticky = rProps.header?.tabsProp?.sticky ?? DETAIL_LAYOUT_DEFINE.tabsProp.sticky;

  // console.log("rProps.mould :>> ", rProps.mould);
  // console.log("RenderTabs infoColumns.value :>> ", infoColumns.value);
  // console.log('["new", "edit"].includes(orderStatus.value) :>> ', ["new", "edit"].includes(orderStatus.value));
  // console.log("orderStatus.value :>> ", orderStatus.value);

  // let _params =
  //   orderStatus.value == "new" ? infoParam.value : orderStatus.value == "edit" ? reactive(_mainData.value) : _mainData.value;

  if (rProps?.mould && rProps.mould.length > 0) {
    let _dftabs = undefined;
    if (globalStore?.detailtabs && Object.keys(globalStore?.detailtabs).includes(rProps.dwname)) {
      _dftabs = globalStore.detailtabs[rProps.dwname];
      rProps.mould
        .map(item => {
          let _limited = isFunction(item?.limited) ? item.limited(detailParams) : item?.limited ?? false;
          if (_limited || !item.isHidden) return false;
          return item;
        })
        .filter(o => o)
        .find((o: any) => o?.id == _dftabs);
    }
    _dftabs = _dftabs ?? rProps.mould[0].id;
    tabsActive.value = _dftabs;

    // let bacsCardRender: any = [];
    // if (rProps.header?.baseCard) {
    //   switch (rProps.header?.baseCard.type) {
    //     case "timeline":
    //       bacsCardRender.push(<BaseCardTimeline data={_mainData.value} />);
    //       break;

    //     default:
    //       break;
    //   }
    // }

    console.log("RenderTabs rProps.mould :>> ", rProps.mould);

    tabRender = rProps.mould
      .map((item: detailModelItemProp) => {
        // console.log("tasItemRender item :>> ", item);
        // let _limited = isFunction(item?.limited) ? item.limited(_mainData.value) : item?.limited ?? false;
        let _limited = isFunction(item?.limited) ? item.limited(detailParams) : item?.limited ?? false;
        // if (_limited) return false;
        let _disabled = _limited;
        if (!item.isHidden) {
          if (slots[item.id]) {
            return tasItemRender(
              item,
              () => {
                let val = _detailData.value && _detailData.value[item.id];
                return slots[item.id]?.({
                  data: _mainData.value,
                  props: item,
                  orderStatus: orderStatus.value,
                  isScrollspy: isScrollspy.value,
                  layout: currentMould.value.header
                });
              },
              true,
              _disabled
            );
          } else if (item.render) {
            return tasItemRender(
              item,
              () => {
                let val = _detailData.value && _detailData.value[item.id];
                return item.render && item.render(val);
              },
              true,
              _disabled
            );
          } else {
            return tasItemRender(
              item,
              () => {
                // if (item.type == "base") {c
                //   console.log("item.id!!! :>> ", item);
                //   return (
                //     <>
                //       <div class="flx">
                //         <div class="flx-1">
                //           {slots[item.id] ? (
                //             slots[item.id]?.({ data: _mainData.value, props: infoColumns.value, orderStatus: orderStatus.value })
                //           ) : (
                //             <BaseForm
                //               columns={infoColumns.value}
                //               searchParam={_params}
                //               searchCol={{ xs: 2, sm: 4, md: 5, lg: 6, xl: 6 }}
                //               {...item.props}
                //               formProps={tableOptions.basicinfo ?? {}}
                //               layoutAttrDefine={basicinfoFormDefaultComputed}
                //               onConfirm={saveBasicSettingFunc}
                //               onReset={resetBasicSettingFunc}
                //               onSaveDefault={saveDefaultLayout}
                //             />
                //           )}
                //         </div>
                //         {slots.headerAside ? (
                //           <div class="flx-shrink ml-12 enter-x">
                //             {slots.headerAside({ data: _mainData.value, props: infoColumns.value })}
                //           </div>
                //         ) : (
                //           ""
                //         )}
                //       </div>
                //     </>
                //   );
                // } else {
                return item.label;
                // }
              },
              false,
              _disabled
            );
          }
        }
      })
      .filter(Boolean);

    // if (!tabRender.length) return;
    // } else {
    //   return;
  }

  let tabsSlot: any = {};
  if (slots.tabNavRight) {
    tabsSlot["nav-right"] = () => {
      return slots.tabNavRight?.({ active: tabsActive.value });
    };
  }
  console.log("RenderTabs tabRender :>> ", tabsActive.value, tabRender);

  return (
    <>
      {tabRender.length > 0 && (
        <van-tabs
          class={`${prefixCls}__tabs ${isScrollspy.value ? "scrollspy" : ""}`}
          v-model:active={tabsActive.value}
          scrollspy={isScrollspy.value}
          sticky={isScrollspy.value ? _sticky : false}
          shrink={true}
          offsetTop={headerAffixTop.value + headerAffixHeight.value}
          lazy-render={false}
          onClickTab={handleClickTabs}
          v-slots={tabsSlot}
        >
          {tabRender}
        </van-tabs>
      )}
    </>
  );
};

let detailParams = reactive<any>({});

// watch(
//   () => _mainData.value,
//   val => {
//     // detailParams = editable.value ? reactive(val) : val;
//     for (const key in val) {
//       detailParams[key] = val[key];
//     }
//     detailParams.bednetname = "32123123";
//     console.log("detailParams _mainData val :>> ", val, detailParams);
//   },
//   {
//     immediate: true,
//     deep: true
//   }
// );

/**
 * @description 模块：基础信息
 */
const basicinfoRender = (rProps: any) => {
  let soltinfo = "basicinfo";
  // let _params =
  //   orderStatus.value == "new" ? infoParam.value : orderStatus.value == "edit" ? reactive(_mainData.value) : _mainData.value;
  let _params = editable.value ? reactive(_mainData.value) : _mainData.value;
  detailParams = editable.value ? reactive(_mainData.value) : _mainData.value;

  console.log("basicinfoRender rProps :>> ", rProps);
  console.log("basicinfoRender _params :>> ", editable.value, _params);
  console.log("basicinfoRender _mainData.value :>> ", _mainData.value);
  console.log("basicinfoRender infoColumns.value :>> ", infoParam.value);
  console.log("basicinfoRender searchParam.value :>> ", searchParam.value);
  // let codeValue = orderStatus.value == "new" ? true : convertStrToObj(_mainData.value, props.header.fieldNames?.code);
  return (
    <>
      <div class="flx basicinfo-container">
        <div class="flx-1">
          {slots[soltinfo] ? (
            slots[soltinfo]?.({ data: _mainData.value, props: infoColumns.value, orderStatus: orderStatus.value })
          ) : (
            <BaseForm
              loading={orderStatus.value != "new" && tableLoading.value}
              ref={LjDetailBaseFormRef}
              columns={infoColumns.value}
              searchParam={detailParams}
              searchCol={rProps.searchCol}
              basicGroupCol={rProps.basicGroupCol}
              formProps={tableOptions.basicinfo ?? {}}
              layoutAttrDefine={basicinfoFormDefaultComputed}
              ifLayoutEditable={rProps.ifBasicEditable}
              onConfirm={saveBasicSettingFunc}
              onReset={resetBasicSettingFunc}
              onSaveDefault={saveDefaultLayout}
              onToSetting={beforeToSetting}
              onBeforeClose={beforeCloseSetting}
            />
          )}
        </div>
        {slots.headerSuffix ? (
          <div class="flx-shrink ml-12">{slots.headerSuffix({ data: _mainData.value, props: infoColumns.value })}</div>
        ) : (
          <></>
        )}
      </div>
    </>
  );
};

/**
 * @description 渲染：主体
 * @param rProps prop
 */
const RenderLjDetail = (rProps: DetailProp) => {
  // console.log("RenderLjDetail rProps :>> ", JSON.stringify(rProps));
  // console.log("isScrollspy.value :>> ", isScrollspy.value);
  if (isScrollspy.value) {
    // 滚动模式
    return (
      <>
        <div ref="LjDetailRef" class={`${prefixCls} ${globalStore.assemblySize}`} id={prefixCls}>
          {slots.header ? (
            slots.header?.()
          ) : (
            <Affix class={`${prefixCls}__header`} ref="LjDetailAffixRef" offset={headerAffixTop.value}>
              <RenderHeaderDefault {...rProps} />
            </Affix>
          )}
          {/* {orderStatus.value != "new" && RenderDetailHeader(rProps)} */}
          {basicinfoRender(rProps)}
          {RenderTabs(rProps)}
          {slots.default?.()}
          <el-backtop target={`.lj-main-body`} right={20} bottom={80}>
            <el-icon>
              <ArrowUpBold />
            </el-icon>
          </el-backtop>
        </div>
      </>
    );
  } else {
    let _foldLayout: any = {
      direction: rProps?.header?.direction ?? DETAIL_LAYOUT_DEFINE.direction,
      right: {
        width: rProps?.header?.foldright?.width ?? DETAIL_LAYOUT_DEFINE.foldright.width,
        minWidth: rProps?.header?.foldright?.minWidth ?? DETAIL_LAYOUT_DEFINE.foldright.minWidth,
        lastWidth: rProps?.header?.foldright?.lastWidth ?? DETAIL_LAYOUT_DEFINE.foldright.lastWidth,
        hidden: rProps?.header?.foldright?.hidden ?? DETAIL_LAYOUT_DEFINE.foldright.hidden
      }
    };
    console.log("_foldLayout :>> ", _foldLayout);
    let foldSlot = {
      right: () => {
        return RenderTabs(rProps);
      }
    };
    return (
      <>
        <div ref="LjDetailRef" class={`${prefixCls} ${globalStore.assemblySize} fold-vertical`} id={prefixCls}>
          {rProps.ifFoldLayout ? (
            <LjFoldLayout
              ref={LjFoldLayoutRef}
              v-slots={foldSlot}
              {..._foldLayout}
              onFoldRight={layout => toSaveFoldLayout(layout, "foldright", "right")}
            >
              {slots.header ? (
                slots.header?.()
              ) : (
                <Affix class={`${prefixCls}__header`} ref="LjDetailAffixRef" offset={headerAffixTop.value}>
                  <RenderHeaderDefault {...rProps} />
                </Affix>
              )}
              {basicinfoRender(rProps)}
            </LjFoldLayout>
          ) : (
            <>
              {slots.header ? (
                slots.header?.()
              ) : (
                <Affix class={`${prefixCls}__header`} ref="LjDetailAffixRef" offset={headerAffixTop.value}>
                  <RenderHeaderDefault {...rProps} />
                </Affix>
              )}
              {basicinfoRender(rProps)}
              {RenderTabs(rProps)}
            </>
          )}

          {slots.default?.()}
          <el-backtop target={`.lj-main-body`} right={20} bottom={80}>
            <el-icon>
              <ArrowUpBold />
            </el-icon>
          </el-backtop>
        </div>
      </>
    );
  }
};

watch(
  () => props.data,
  val => {
    if (val.length > 0) {
      _mainData.value = { ...infoParam.value, ...val[0] };
    } else {
      _mainData.value = { ...infoParam.value };
    }
  },
  { immediate: true, deep: true }
);
watch(
  () => tableData.value,
  val => {
    _mainData.value = val[0] ?? { ...infoParam.value, ...props.data[0] };
  }
);

defineExpose({
  element: LjDetailRef,
  baseformRef: LjDetailBaseFormRef,
  infoParam,
  totalParam,
  mainData_api,
  detailData_api,
  _mainData,
  layoutHeader,
  enumMap,
  currentMould,
  tabsActive,
  toSaveFoldLayout,
  toSetFloatBtnChange,
  refresh: layoutRefresh,
  toValidateForm
});
</script>

<style lang="scss">
@import "./index.scss";
</style>
