"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
require("../../../../../node_modules/element-plus/es/index.js");
;/* empty css                                                             */
;/* empty css                                                                  */
;/* empty css                                                                */
const Vue = require("vue");
const vxeTable = require("vxe-table");
const index$2 = require("../../../../../node_modules/@element-plus/icons-vue/dist/index.js");
const parseFilterConfig = require("../../utils/parseFilterConfig.js");
const common = require("../../utils/common.js");
;/* empty css                                                                 */
;/* empty css                                                                   */
;/* empty css                                                                   */
;/* empty css                                                                   */
;/* empty css                                                                  */
require("../../utils/formulajs/functionCore.js");
const eventFlowHandler = require("../../utils/eventFlow/eventFlowHandler.js");
;/* empty css                            */
const _pluginVue_exportHelper = require("../../../../../_virtual/_plugin-vue_export-helper.js");
;/* empty css                                                  */
;/* empty css                                                        */
;/* empty css                                                   */
;/* empty css                                                  */
;/* empty css                                                     */
;/* empty css                                                    */
;/* empty css                                                               */
;/* empty css                                                     */
;/* empty css                                                   */
;/* empty css                                                    */
;/* empty css                                                                 */
;/* empty css                                                                       */
const decimal = require("../../../../../node_modules/decimal.js/decimal.js");
;/* empty css                  */
const index = require("../../../../../node_modules/element-plus/es/components/link/index.js");
const index$1 = require("../../../../../node_modules/element-plus/es/components/icon/index.js");
const index$3 = require("../../../../../node_modules/element-plus/es/components/button/index.js");
const index$4 = require("../../../../../node_modules/element-plus/es/components/message/index.js");
const _hoisted_1 = { class: "table-column-manager" };
const _hoisted_2 = {
  key: 0,
  class: "prefix-content"
};
const _hoisted_3 = {
  key: 3,
  class: "suffix-content"
};
const _sfc_main = {
  __name: "TableColumn",
  props: {
    fieldsData: {
      type: Array,
      default: () => []
    },
    showIndex: {
      type: Boolean,
      default: false
    },
    selectMode: {
      type: String,
      default: "none",
      validator: (value) => ["none", "single", "multiple"].includes(value)
    },
    isOptBtns: {
      type: Boolean,
      default: false
    },
    optBtns: {
      type: Array,
      default: () => []
    },
    modeKey: {
      type: String,
      default: ""
    },
    modes: {
      type: Array,
      default: () => []
    },
    // 数据源加载的选项数据：{ dataSourceId: options }
    dataSourceOptions: {
      type: Object,
      default: () => ({})
    },
    // 字典加载的选项数据：{ dictionaryKey: options }
    dictionaryOptions: {
      type: Object,
      default: () => ({})
    },
    localConfig: {
      type: Object,
      default: () => {
      }
    },
    // 表格组件引用（用于表格刷新等操作）
    tableRef: {
      type: Object,
      default: null
    },
    // 表格数据
    tableData: {
      type: Array,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: false
    },
    isDialog: {
      type: Boolean,
      default: false
    },
    hiddenFormData: {
      type: Object,
      default: {}
    },
    btnRollbackEvent: {
      type: Object,
      default: {}
    }
  },
  setup(__props) {
    const props = __props;
    const instance = Vue.getCurrentInstance();
    const visibleFields = Vue.computed(() => {
      let fields = props.fieldsData.filter((field) => field.isShow);
      if (props.modeKey && props.modes.length) {
        const currentMode = props.modes.find((m) => m.key === props.modeKey);
        if (currentMode && currentMode.showFields && currentMode.showFields.length) {
          fields = fields.filter(
            (field) => currentMode.showFields.includes(field.id)
          );
        }
      }
      return fields;
    });
    const getColumnWidth = (field) => {
      if (field.widthMode === "auto") {
        return void 0;
      }
      return field.width;
    };
    const formatCellValue = (row, field) => {
      const value = row[field.fieldName];
      if (value === null || value === void 0) return "";
      switch (field.fieldType) {
        case "number":
          let numValue = Number(value);
          if (isNaN(numValue)) return value;
          switch (field.format) {
            case "wan":
              numValue = new decimal.Decimal(numValue).div(new decimal.Decimal(1e4)).toNumber();
              break;
            case "million":
              numValue = new decimal.Decimal(numValue).div(new decimal.Decimal(1e6)).toNumber();
              break;
            case "percentage":
              numValue = new decimal.Decimal(numValue).mul(new decimal.Decimal(100)).toNumber();
              break;
            case "permillage":
              numValue = new decimal.Decimal(numValue).mul(new decimal.Decimal(1e3)).toNumber();
              break;
            case "permillion":
              numValue = new decimal.Decimal(numValue).mul(new decimal.Decimal(1e4)).toNumber();
              break;
          }
          if (field.hasDecimalPlaces && field.decimalPlaces !== void 0) {
            numValue = Number(numValue.toFixed(field.decimalPlaces));
          }
          if (field.format == "yuan" || field.format == "wan" || field.format == "million") {
            const formatted = numValue.toLocaleString("en-US", {
              minimumFractionDigits: field.hasDecimalPlaces && field.decimalPlaces !== void 0 ? field.decimalPlaces : 0,
              maximumFractionDigits: field.hasDecimalPlaces && field.decimalPlaces !== void 0 ? field.decimalPlaces : 20
            });
            return formatted;
          }
          return numValue;
        case "select":
        case "multipleSelection":
          if (field.optionConfig) {
            let options = [];
            let displayField = "label";
            let valueField = "value";
            if (field.optionConfig.optionSource === "custom" && field.optionConfig.options) {
              options = field.optionConfig.options;
              displayField = "label";
              valueField = "value";
            } else if (field.optionConfig.optionSource === "dataSource" && field.optionConfig.dataSourceValue) {
              options = props.dataSourceOptions[field.optionConfig.dataSourceValue] || [];
              displayField = field.optionConfig.displayField || "label";
              valueField = field.optionConfig.valueField || "value";
            } else if (field.optionConfig.optionSource === "dictionary" && field.optionConfig.dictionaryValue) {
              options = props.dictionaryOptions[field.optionConfig.dictionaryValue] || [];
              displayField = "optName";
              valueField = "optCode";
            }
            if (typeof value === "string" && value.includes("|")) {
              const values = value.split("|");
              const displayValues = values.map((val) => {
                const option2 = options.find((opt) => opt[valueField] == val);
                return option2 ? option2[displayField] : val;
              });
              return displayValues.join(", ");
            }
            const option = options.find((opt) => opt[valueField] == value);
            return option ? option[displayField] : value;
          }
          return value;
        case "date":
          return formatDate(value, field.dateType);
        case "switch":
          return value ? "是" : "否";
        default:
          return value;
      }
    };
    const formatDate = (value, type) => {
      if (!value) return "";
      let date;
      if (typeof value === "string" && /^\d{8}$/.test(value)) {
        const year2 = value.substring(0, 4);
        const month2 = value.substring(4, 6);
        const day2 = value.substring(6, 8);
        date = /* @__PURE__ */ new Date(`${year2}-${month2}-${day2}`);
      } else {
        date = new Date(value);
      }
      if (isNaN(date.getTime())) return value;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      const getWeekNumber = (d) => {
        const oneJan = new Date(d.getFullYear(), 0, 1);
        const numberOfDays = Math.floor((d - oneJan) / (24 * 60 * 60 * 1e3));
        return Math.ceil((d.getDay() + 1 + numberOfDays) / 7);
      };
      const week = getWeekNumber(date);
      const formatMap = {
        date: `${year}-${month}-${day}`,
        "datetime-minute": `${year}-${month}-${day} ${hours}:${minutes}`,
        datetime: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
        time: `${hours}:${minutes}:${seconds}`,
        year: `${year}`,
        month: `${year}-${month}`,
        week: `${year}-${week}`,
        dates: `${year}-${month}-${day}`
      };
      return formatMap[type] || formatMap.date;
    };
    const handleCopy = (row, field) => {
      const value = row[field.fieldName];
      navigator.clipboard.writeText(value).then(() => {
        index$4.ElMessage.success("复制成功");
      });
    };
    const getVisibleOptBtns = (row) => {
      const btnList = props.optBtns.filter((item) => {
        if (!item.showCondition) return true;
        return parseFilterConfig.checkFilterMatch(item.showCondition, row, props.fieldsData);
      });
      return btnList.filter((item) => {
        return hasPerm(item.permission);
      });
    };
    function hasPerm(permission) {
      if (permission === true || permission === void 0 || permission === "") {
        return true;
      }
      let btnFlag = false;
      const myBtns = window.$store.getters.funcAuthList;
      for (let i in myBtns) {
        if (myBtns[i] == permission) {
          btnFlag = true;
          break;
        }
      }
      return btnFlag;
    }
    const shouldShowOptColumn = Vue.computed(() => {
      if (!props.isOptBtns || !props.optBtns.length) return false;
      if (!props.tableData || props.tableData.length === 0) return true;
      return props.tableData.some((row) => getVisibleOptBtns(row).length > 0);
    });
    const isBtnDisabled = (row, item) => {
      if (!item.disableCondition) return false;
      const { operator, conditions, groups } = item.disableCondition;
      if ((!conditions || conditions.length == 0) && (!groups || groups.length == 0)) {
        return false;
      }
      return parseFilterConfig.checkFilterMatch(item.disableCondition, row, props.fieldsData);
    };
    const optColumnWidth = Vue.computed(() => {
      const padding = 12;
      const labelWidth = 14;
      const labelMargin = 18;
      if (!props.tableData || props.tableData.length === 0) {
        let labelLength = 0;
        props.optBtns.forEach((btn) => {
          labelLength += btn.label.length;
        });
        if (labelLength > 0) {
          return labelLength * labelWidth + (props.optBtns.length - 1) * labelMargin + padding * 2 + 6;
        }
        return 0;
      }
      let maxBtnLength = 0;
      const maxVisibleBtns = Math.max(
        ...props.tableData.map((row) => {
          const btnList = getVisibleOptBtns(row);
          if (btnList.length > maxBtnLength) {
            maxBtnLength = btnList.length;
          }
          let labelLength = 0;
          btnList.forEach((btn) => {
            labelLength += btn.label.length;
          });
          return labelLength;
        })
      );
      const maxLength = Math.max(maxVisibleBtns, 1);
      return maxLength * labelWidth + (maxBtnLength - 1) * labelMargin + padding * 2 + 6;
    });
    const { handleEvent } = eventFlowHandler.useEventFlow({
      fields: props.fieldsData,
      instance,
      localConfig: props.localConfig,
      components: {
        table: props.tableRef
      }
    });
    async function handleButtonClick(row, btn, eventConfig) {
      await handleEvent(
        { ...row, ...common.removeEmptyValues(props.hiddenFormData) },
        btn,
        eventConfig == null ? void 0 : eventConfig.find((item) => item.name == "Click")
      );
      const handleFunc = props.btnRollbackEvent[btn.id];
      if (handleFunc && typeof handleFunc == "function") {
        handleFunc();
      }
    }
    return (_ctx, _cache) => {
      const _component_el_link = index.ElLink;
      const _component_el_icon = index$1.ElIcon;
      const _component_el_button = index$3.ElButton;
      return Vue.openBlock(), Vue.createElementBlock("div", _hoisted_1, [
        !__props.readonly && __props.selectMode === "multiple" ? (Vue.openBlock(), Vue.createBlock(Vue.unref(vxeTable.VxeColumn), {
          key: 0,
          type: "checkbox",
          width: 50,
          fixed: "left",
          align: "center"
        })) : Vue.createCommentVNode("", true),
        !__props.readonly && __props.selectMode === "single" ? (Vue.openBlock(), Vue.createBlock(Vue.unref(vxeTable.VxeColumn), {
          key: 1,
          type: "radio",
          width: 50,
          align: "center",
          fixed: "left"
        })) : Vue.createCommentVNode("", true),
        __props.showIndex ? (Vue.openBlock(), Vue.createBlock(Vue.unref(vxeTable.VxeColumn), {
          key: 2,
          type: "seq",
          title: "序号",
          width: 60,
          align: "center",
          fixed: "left"
        })) : Vue.createCommentVNode("", true),
        (Vue.openBlock(true), Vue.createElementBlock(Vue.Fragment, null, Vue.renderList(visibleFields.value, (field) => {
          return Vue.openBlock(), Vue.createBlock(Vue.unref(vxeTable.VxeColumn), {
            key: field.id,
            field: field.fieldName,
            title: field.label,
            width: getColumnWidth(field),
            "min-width": field.minWidth,
            fixed: field.isFixed ? "left" : void 0,
            align: field.align,
            "header-align": field.headerAlign,
            sortable: field.sortRule && field.sortRule != "none",
            resizable: false,
            "show-header-overflow": "",
            "show-footer-overflow": "",
            "show-overflow": field.isOverflowWrap ? false : "title",
            "header-class-name": field.sortRule == "server" ? "serverSort" : ""
          }, {
            default: Vue.withCtx(({ row }) => [
              Vue.renderSlot(_ctx.$slots, `cell-${field.fieldName}`, {
                row,
                field
              }, () => [
                field.prefix ? (Vue.openBlock(), Vue.createElementBlock("span", _hoisted_2, Vue.toDisplayString(field.prefix), 1)) : Vue.createCommentVNode("", true),
                field.isLink ? (Vue.openBlock(), Vue.createBlock(_component_el_link, {
                  key: 1,
                  type: "primary",
                  underline: "never",
                  onClick: ($event) => handleButtonClick(row, field, field.linkConfig)
                }, {
                  default: Vue.withCtx(() => [
                    Vue.createTextVNode(Vue.toDisplayString(formatCellValue(row, field)), 1)
                  ]),
                  _: 2
                }, 1032, ["onClick"])) : (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 2 }, [
                  Vue.createTextVNode(Vue.toDisplayString(formatCellValue(row, field)), 1)
                ], 64)),
                field.suffix ? (Vue.openBlock(), Vue.createElementBlock("span", _hoisted_3, Vue.toDisplayString(field.suffix), 1)) : Vue.createCommentVNode("", true),
                field.canCopy ? (Vue.openBlock(), Vue.createBlock(_component_el_icon, {
                  key: 4,
                  class: "copy-icon",
                  onClick: ($event) => handleCopy(row, field)
                }, {
                  default: Vue.withCtx(() => [
                    Vue.createVNode(Vue.unref(index$2.CopyDocument))
                  ]),
                  _: 2
                }, 1032, ["onClick"])) : Vue.createCommentVNode("", true)
              ], true)
            ]),
            _: 2
          }, 1032, ["field", "title", "width", "min-width", "fixed", "align", "header-align", "sortable", "show-overflow", "header-class-name"]);
        }), 128)),
        !__props.readonly && shouldShowOptColumn.value ? (Vue.openBlock(), Vue.createBlock(Vue.unref(vxeTable.VxeColumn), {
          key: 3,
          title: "操作",
          width: optColumnWidth.value,
          fixed: "right",
          align: "center"
        }, {
          default: Vue.withCtx(({ row }) => [
            (Vue.openBlock(true), Vue.createElementBlock(Vue.Fragment, null, Vue.renderList(getVisibleOptBtns(row), (btn) => {
              return Vue.openBlock(), Vue.createBlock(_component_el_button, {
                key: btn.id,
                type: "primary",
                link: "",
                disabled: isBtnDisabled(row, btn),
                onClick: ($event) => handleButtonClick(row, btn, btn.eventConfig)
              }, {
                default: Vue.withCtx(() => [
                  Vue.createTextVNode(Vue.toDisplayString(btn.label), 1)
                ]),
                _: 2
              }, 1032, ["disabled", "onClick"]);
            }), 128))
          ]),
          _: 1
        }, 8, ["width"])) : Vue.createCommentVNode("", true)
      ]);
    };
  }
};
const TableColumn = /* @__PURE__ */ _pluginVue_exportHelper.default(_sfc_main, [["__scopeId", "data-v-5eaca99e"]]);
exports.default = TableColumn;
