<template>
  <el-dialog
    custom-class="dialog-style list-dialog table-column-config-dialog"
    :title="i18nt('designer.setting.tableColEdit')"
    :visible.sync="showDialog"
    :modal="false"
    :show-close="!0"
    :close-on-click-modal="!1"
    :close-on-press-escape="!1"
    :destroy-on-close="false"
    top="5vh"
    width="1220px"
    v-dialog-drag
    :before-close="closeHandle"
  >
    <div
      class="cont table-column-dialog-cont"
      v-loading="!tableReady"
      element-loading-background="rgba(0, 0, 0, 0)"
      element-loading-text="数据正在加载中"
      element-loading-spinner="el-icon-loading"
    >
      <el-table
        v-if="tableReady"
        ref="singleTable"
        width="100%"
        :data="tableData"
        height="500"
        border=""
        row-key="columnId"
        stripe=""
        :tree-props="{ children: 'children' }"
        :default-expand-all="shouldExpandAllTable"
      >
        <el-table-column label="" width="80" fixed="left">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="" width="35" fixed="left"
          ><i class="el-icon-s-operation drag-option"></i>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.columnLabel')"
          width="150"
          prop="label"
          fixed="left"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.label"
              @change="changeRowLabel(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.columnName')"
          width="150"
          prop="prop"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.prop"
              @change="changeRowProp(scope.row)"
              :disabled="'editAttachment' == scope.row.formatS"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.columnWidth')"
          width="100"
          prop="width"
        >
          <template #default="scope">
            <el-input v-model="scope.row.width"></el-input>
          </template>
        </el-table-column>

        <el-table-column :label="i18nt('必填')" width="70" prop="required">
          <template #default="scope">
            <el-switch
              v-model="scope.row.required"
              @change="changeRowRequired(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.fixedColumn')"
          width="100"
          prop="fixed"
        >
          <template #default="scope">
            <el-select v-model="scope.row.fixed" clearable>
              <el-option value="left">left</el-option>
              <el-option value="right">right</el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.formatOfColumn')"
          width="200"
          prop="formatS"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.formatS"
              @change="changeFormatS(scope.row, false)"
              clearable
            >
              <el-option-group
                :label="i18nt('designer.setting.customRenderGroup')"
              >
                <el-option value="render" label="render"></el-option>
              </el-option-group>
              <el-option-group v-for="t in op" :key="t.label" :label="t.label">
                <el-option
                  v-for="e in t.options"
                  :key="e.value"
                  :value="e.value"
                  :label="e.label"
                ></el-option>
              </el-option-group>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="格式化配置" width="90" align="center">
          <template #default="scope">
            <el-button
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="openFormatConfigDialog(scope.row, scope.$index)"
              :disabled="
                !columnFormatMap[scope.row.formatS] &&
                'widgetRender' !== scope.row.formatS &&
                'editTreeButtonGroup' !== scope.row.formatS
              "
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.renderFunction')"
          width="70"
          align="center"
        >
          <template #default="scope">
            <el-button
              :disabled="'render' !== scope.row.formatS"
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="showRenderDialog(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.visibleColumn')"
          width="70"
          prop="show"
        >
          <template #default="scope">
            <el-switch v-model="scope.row.show"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.sortableColumn')"
          width="70"
          prop="sortable"
        >
          <template #default="scope">
            <el-switch v-model="scope.row.sortable"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="显示筛选" width="70" prop="filterable">
          <template #default="scope">
            <el-switch v-model="scope.row.filterable"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="UTC时差转换" width="90" align="center">
          <template #default="scope">
            <el-switch
              v-if="isUtcTransformColumn(scope.row)"
              v-model="scope.row.utcTransformEnabled"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="编辑更多属性"
          width="100"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="openRowEditDialog(scope.row, scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot="header">
            <el-tooltip
              :hide-after="500"
              class="item"
              effect="dark"
              content="添加根节点"
              placement="top"
            >
              <el-button
                size="mini"
                type=""
                circle=""
                icon="el-icon-plus"
                @click="onAddRoot"
              />
            </el-tooltip>
          </template>
          <template #default="{ row, $index }">
            <el-tooltip
              :hide-after="hideAfter"
              :open-delay="openDelay"
              effect="dark"
              content="添加兄弟节点"
              placement="top"
            >
              <el-button
                size="mini"
                type=""
                circle=""
                icon="el-icon-plus"
                @click="onAddSibling(row, $index)"
              />
            </el-tooltip>

            <el-tooltip
              :hide-after="hideAfter"
              :open-delay="openDelay"
              effect="dark"
              content="添加子节点"
              placement="top"
            >
              <el-button
                size="mini"
                type=""
                circle=""
                icon="el-icon-circle-plus-outline"
                @click="onAddChild(row, $index)"
              />
            </el-tooltip>
            <el-tooltip
              :hide-after="hideAfter"
              :open-delay="openDelay"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                size="mini"
                type=""
                circle=""
                icon="el-icon-delete"
                @click="onDelete(row, $index)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <columnRenderDialog
        :column="currentTableColumn"
        :sourceData="sourceData"
        v-if="showColumnRenderDialog"
        :visiable.sync="showColumnRenderDialog"
        @confirm="confirmWidgetRenderDialog"
      ></columnRenderDialog>
      <editTreeButtonGroupConfigDialog
        v-if="showEditTreeButtonGroupConfigDialog && editTreeButtonGroupRowData"
        :visible.sync="showEditTreeButtonGroupConfigDialog"
        :row="editTreeButtonGroupRowData"
        @confirm="confirmEditTreeButtonGroupConfig"
      />
    </div>
    <div class="dialog-footer" slot="footer">
      <el-button @click="closeHandle" class="button-sty" icon="el-icon-close">
        {{ i18nt("designer.hint.cancel") }}
      </el-button>
      <el-button
        type="primary"
        @click="colSubmit"
        class="button-sty"
        icon="el-icon-check"
      >
        {{ i18nt("designer.hint.confirm") }}
      </el-button>
    </div>
    <el-dialog
      v-if="showRenderDialogFlag"
      :title="i18nt('designer.setting.renderFunction')"
      :visible.sync="showRenderDialogFlag"
      :modal="false"
      :show-close="!0"
      custom-class="dialog-style list-dialog"
      :close-on-click-modal="!1"
      :close-on-press-escape="!1"
      :destroy-on-close="!0"
      v-dialog-drag
      top="7vh"
      :append-to-body="true"
    >
      <el-alert
        type="info"
        :closable="!1"
        title="function customRender(params,h) {"
      />
      <code-editor
        ref="dsResultEditor"
        mode="javascript"
        :readonly="!1"
        v-model="renderJson"
      ></code-editor>
      <el-alert type="info" :closable="!1" title="}" />
      <div class="dialog-footer" slot="footer">
        <el-button
          @click="showRenderDialogFlag = !1"
          class="button-sty"
          icon="el-icon-close"
        >
          {{ i18nt("designer.hint.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="saveColumnRender"
          class="button-sty"
          icon="el-icon-check"
        >
          {{ i18nt("designer.hint.confirm") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="tableColumnConfigTitle"
      :visible.sync="showTableColumnConfigDialog"
      v-if="showTableColumnConfigDialog"
      :show-close="true"
      custom-class="dialog-style list-dialog"
      v-dialog-drag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :append-to-body="true"
      :modal-append-to-body="true"
      top="5vh"
    >
      <div class="cont">
        <el-alert
          type="info"
          :closable="false"
          :title="tableColumnConfigHeader"
        ></el-alert>
        <code-editor
          :mode="'javascript'"
          :readonly="false"
          v-model="tableColumnConfigCode"
          ref="ecEditor"
        ></code-editor>
        <el-alert type="info" :closable="false" title="}"></el-alert>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="showTableColumnConfigDialog = false"
          class="button-sty"
          icon="el-icon-close"
        >
          {{ i18nt("designer.hint.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="saveTableColumnConfigDialog"
          class="button-sty"
          icon="el-icon-check"
        >
          {{ i18nt("designer.hint.confirm") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="i18nt('designer.setting.editFormEventHandler')"
      :visible.sync="showFormEventDialogFlag"
      v-if="showFormEventDialogFlag"
      :show-close="true"
      custom-class="dialog-style list-dialog"
      v-dialog-drag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :append-to-body="true"
      :modal-append-to-body="true"
      top="5vh"
    >
      <div class="cont">
        <el-alert
          type="info"
          :closable="false"
          :title="'form.' + eventParamsMap[curEventName]"
        ></el-alert>
        <code-editor
          :mode="'javascript'"
          :readonly="false"
          v-model="formEventHandlerCode"
          ref="ecEditor"
        ></code-editor>
        <el-alert type="info" :closable="false" title="}"></el-alert>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="showFormEventDialogFlag = false"
          class="button-sty"
          icon="el-icon-close"
        >
          {{ i18nt("designer.hint.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="saveFormEventHandler"
          class="button-sty"
          icon="el-icon-check"
        >
          {{ i18nt("designer.hint.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      custom-class="dialog-style list-dialog table-column-row-edit-dialog"
      :title="i18nt('designer.setting.tableColEdit')"
      :visible.sync="showRowEditDialog"
      v-if="showRowEditDialog"
      :modal="false"
      :show-close="!0"
      :close-on-click-modal="!1"
      :close-on-press-escape="!1"
      :destroy-on-close="!0"
      :append-to-body="true"
      :modal-append-to-body="true"
      top="5vh"
      width="480px"
      v-dialog-drag
    >
      <div class="cont table-column-row-edit-cont">
        <el-form :model="rowData" class="form-m2" label-position="top">
          <el-form-item :label="i18nt('designer.setting.columnLabel')">
            <el-input
              v-model="rowData.label"
              @change="changeRowLabel(rowData)"
            ></el-input>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.columnName')">
            <el-input
              v-model="rowData.prop"
              @change="changeRowProp(rowData)"
              :disabled="'editAttachment' == rowData.formatS"
            ></el-input>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.columnWidth')">
            <el-input v-model="rowData.width"></el-input>
          </el-form-item>
          <el-form-item :label="i18nt('必填')">
            <el-switch
              v-model="rowData.required"
              @change="changeRowRequired(rowData)"
            ></el-switch>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.fixedColumn')">
            <el-select v-model="rowData.fixed" clearable>
              <el-option value="left">left</el-option>
              <el-option value="right">right</el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.formatOfColumn')">
            <el-select
              v-model="rowData.formatS"
              @change="changeFormatS(rowData, false)"
              clearable
            >
              <el-option-group
                :label="i18nt('designer.setting.customRenderGroup')"
              >
                <el-option value="render" label="render"></el-option>
              </el-option-group>
              <el-option-group v-for="t in op" :key="t.label" :label="t.label">
                <el-option
                  v-for="e in t.options"
                  :key="e.value"
                  :value="e.value"
                  :label="e.label"
                ></el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="格式化配置">
            <el-button
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="openFormatConfigDialog(rowData, rowDataIndex)"
              :disabled="
                !columnFormatMap[rowData.formatS] &&
                'widgetRender' !== rowData.formatS &&
                'editTreeButtonGroup' !== rowData.formatS
              "
            ></el-button>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.renderFunction')">
            <el-button
              :disabled="'render' !== rowData.formatS"
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="showRenderDialog(rowData)"
            ></el-button>
          </el-form-item>
          <el-form-item
            v-if="isUtcTransformColumn(rowData)"
            label="UTC时差转换"
          >
            <el-switch v-model="rowData.utcTransformEnabled"></el-switch>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.visibleColumn')">
            <el-switch v-model="rowData.show"></el-switch>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.sortableColumn')">
            <el-switch v-model="rowData.sortable"></el-switch>
          </el-form-item>
          <el-form-item label="显示筛选">
            <el-switch v-model="rowData.filterable"></el-switch>
          </el-form-item>
          <el-form-item :label="i18nt('明细行')">
            <el-switch v-model="rowData.isItemLine"></el-switch>
          </el-form-item>

          <el-form-item :label="i18nt('下拉列')">
            <el-switch v-model="rowData.treeNode"></el-switch>
          </el-form-item>
          <el-form-item :label="i18nt('自定义表格列配置')">
            <a
              href="javascript:void(0);"
              class="a-link link-oneLind"
              @click="openTableColumnConfigDialog(rowData, rowDataIndex)"
            >
              <span>{{ rowData.tableColumnConfig }}</span>
              <i class="el-icon-edit"></i>
            </a>
          </el-form-item>
          <el-form-item :label="i18nt('编辑插槽类型')">
            <el-select
              v-model="rowData.editFormatS"
              @change="changeFormatS(rowData, true)"
              clearable
            >
              <el-option
                v-for="e in editOp"
                :key="e.value"
                :value="e.value"
                :label="e.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="编辑插槽配置">
            <el-button
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="openEditFormatConfigDialog(rowData, rowDataIndex)"
              :disabled="!rowData.editFormatS"
            ></el-button>
          </el-form-item>
          <el-form-item :label="i18nt('导出类型')">
            <el-select v-model="rowData.exportType" clearable>
              <el-option value="Image2" label="图片"></el-option>
              <el-option value="Number" label="数值"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="i18nt('表尾统计行类型')">
            <el-select v-model="rowData.footerDataType" clearable>
              <el-option value="1" label="合计"></el-option>
              <el-option value="2" label="平均"></el-option>
              <el-option value="3" label="自定义"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表尾统计行配置">
            <el-button
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="
                editFormEventHandler(rowData, rowDataIndex, 'footerMethodConfg')
              "
              :disabled="rowData.footerDataType !== '3'"
            ></el-button>
          </el-form-item>
          <el-form-item :label="i18nt('显示名称颜色')">
            <el-select v-model="rowData.labelColor" clearable>
              <el-option value="#e6a23c" label="橙"></el-option>
              <el-option value="#2a6494" label="蓝"></el-option>
              <el-option value="#30b08f" label="绿"></el-option>
              <el-option value="#909399" label="灰"></el-option>
              <el-option value="#ea5353" label="红"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label-width="0" class="form-item-full">
            <el-divider class="custom-divider">{{
              i18nt("designer.setting.customLabelIcon")
            }}</el-divider>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.labelIconClass')">
            <icon-picker v-model="rowData.labelIconClass"></icon-picker>
          </el-form-item>
          <el-form-item :label="i18nt('designer.setting.labelIconPosition')">
            <el-select
              v-model="rowData.labelIconPosition"
              clearable
              placeholder="默认后面"
            >
              <el-option label="前面" value="front"></el-option>
              <el-option label="后面" value="rear"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="i18nt('designer.setting.labelTooltip')"
            class="form-item-full"
          >
            <el-input
              type="text"
              v-model="rowData.labelTooltip"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button
          @click="closeRowEditDialog"
          class="button-sty"
          icon="el-icon-close"
        >
          {{ i18nt("designer.hint.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="submitRowEditDialog"
          class="button-sty"
          icon="el-icon-check"
        >
          {{ i18nt("designer.hint.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import i18n from "../../../../../../components/xform/utils/i18n";
import Sortable from "sortablejs";
import {
  generateId,
  loopHandleWidget,
  deepClone,
  columnFormatMap,
} from "../../../../../../components/xform/utils/util";
import columnRenderDialog from "./columnRenderDialog.vue";
import editTreeButtonGroupConfigDialog from "./edit-tree-button-group-config-dialog.vue";
import IconPicker from "@base/components/xform/icon-picker/index.vue";

let businessOptions = [
  {
    value: "_createBy",
    label: "创建人",
  },
  {
    value: "_modifyBy",
    label: "更新人",
  },
  {
    value: "create_date",
    label: "创建时间",
  },
  {
    value: "modify_date",
    label: "更新时间",
  },
];
let userFields = ["_createBy", "_modifyBy", "create_date", "modify_date"];

export default {
  mixins: [i18n],
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object,
    visiable: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    columnRenderDialog,
    editTreeButtonGroupConfigDialog,
    IconPicker,
  },
  inject: ["openWidgetPropertyDialog"],
  data() {
    return {
      tableReady: false,
      tableColumnConfigTitle: null,
      showTableColumnConfigDialog: false,
      tableColumnConfigHeader: null,
      tableColumnConfigCode: null,
      showEditTreeButtonGroupConfigDialog: false,
      currentEditTreeButtonGroupRow: null,
      editTreeButtonGroupRowData: null,
      alignOptions: [
        {
          value: "left",
          label: "left",
        },
        {
          value: "center",
          label: "center",
        },
        {
          value: "right",
          label: "right",
        },
      ],
      businessOptions,
      userFields,
      op: [
        {
          label: "edit Format",
          options: [
            {
              value: "editInput",
              label: "文本输入框",
            },
            {
              value: "editNumber",
              label: "数字输入框",
            },
            {
              value: "editDate",
              label: "日期输入框",
            },
            {
              value: "textarea",
              label: "多行文本输入框",
            },
            {
              value: "editSelect",
              label: "下拉框",
            },
            {
              value: "checkbox",
              label: "复选框",
            },
            {
              value: "radio",
              label: "单选框",
            },
            {
              value: "editAttachment",
              label: "附件",
            },
            {
              value: "editSearch",
              label: "搜索框",
            },
            {
              value: "editStatus",
              label: "状态",
            },
            {
              value: "text",
              label: "文本",
            },
            {
              value: "aText",
              label: "超链接文本",
            },
            {
              value: "widgetRender",
              label: "自定义组件",
            },
          ],
        },
        {
          label: "按钮控件",
          options: [
            {
              value: "dropdown",
              label: "下拉按钮",
            },
            {
              value: "editDelete",
              label: "删除按钮",
            },
            {
              value: "editButton",
              label: "查看按钮",
            },
            {
              value: "aLink",
              label: "超链接按钮",
            },
            {
              value: "button",
              label: "按钮",
            },
            {
              value: "editTreeButtonGroup",
              label: "编辑行按钮组",
            },
          ],
        },
        {
          label: "树控件",
          options: [
            {
              value: "addSiblingEditRow",
              label: "新增兄弟节点",
            },
            {
              value: "addChildTreeRow",
              label: "新增子节点",
            },
            {
              value: "moveUpRow",
              label: "上移",
            },
            {
              value: "moveDownRow",
              label: "下移",
            },
            {
              value: "removeTreeRow",
              label: "删除树节点",
            },
          ],
        },

        {
          label: "业务模块",
          options: businessOptions,
        },
        {
          label: "日期格式化",
          options: [
            {
              value: "d1",
              label: "yyyy-MM-dd",
            },
            {
              value: "d2",
              label: "yyyy/MM/dd",
            },
            {
              value: "d3",
              label: "yyyy年MM月dd日",
            },
            {
              value: "d4",
              label: "yyyy-MM-dd HH:mm:ss",
            },
            {
              value: "d5",
              label: "yyyy-MM-dd hh:mm:ss",
            },
          ],
        },
        {
          label: "数字格式化",
          options: [
            {
              value: "n1",
              label: "###,###,###,##0.######",
            },
            {
              value: "n2",
              label: "###,###,###,##0.00####",
            },
            {
              value: "n3",
              label: "###,###,###,##0.000000",
            },
            {
              value: "n4",
              label: "###,###,###,##0.000",
            },
            {
              value: "n5",
              label: "###,###,###,##0.00",
            },
            {
              value: "n6",
              label: "###,###,###,##0",
            },
            {
              value: "n7",
              label: "###,##0.00##%",
            },
          ],
        },
      ],
      editOp: [
        {
          value: "editInput",
          label: "文本输入框",
        },
        {
          value: "editNumber",
          label: "数字输入框",
        },
        {
          value: "editDate",
          label: "日期输入框",
        },
        {
          value: "editSelect",
          label: "下拉框",
        },
        {
          value: "editAttachment",
          label: "附件",
        },
        {
          value: "editSearch",
          label: "搜索框",
        },
      ],
      showRenderDialogFlag: !1,
      renderJson: "",
      currentTableColumn: null,
      sourceData: null,

      hideAfter: 1500,
      openDelay: 500,
      tableData: [], //树形结构数据转的数组
      tableDataArray: [],
      dragSort: null,
      columnFormatMap,

      showFormEventDialogFlag: false,
      formEventHandlerCode: "",
      curEventName: "",
      curEventRow: null,

      eventParamsMap: {
        footerMethodConfg: "footerMethodConfg(dataId,formCode,param) {",
      },

      showColumnRenderDialog: false,

      editRowData: null,
      rowData: null,
      rowDataIndex: 0,
      showRowEditDialog: false,
      sourceTableColumnsSnapshot: null,
    };
  },
  beforeDestroy() {
    if (this.dragSort) this.dragSort.destroy();
  },
  computed: {
    showDialog: {
      get() {
        return this.visiable;
      },
      set(val) {
        this.$emit("update:visiable", val);
      },
    },
    shouldExpandAllTable() {
      return this.countTreeRows(this.tableData) <= 30;
    },
  },
  watch: {
    visiable(val) {
      if (val) {
        this.onDialogOpen();
      } else {
        this.onDialogClose();
      }
    },
  },
  created() {},
  mounted() {
    if (this.visiable) {
      this.onDialogOpen();
    }
  },
  methods: {
    countTreeRows(rows) {
      if (!Array.isArray(rows) || !rows.length) {
        return 0;
      }
      let count = 0;
      const walk = (list) => {
        list.forEach((item) => {
          count += 1;
          if (item.children && item.children.length) {
            walk(item.children);
          }
        });
      };
      walk(rows);
      return count;
    },
    cloneTableColumnsForEdit(columns) {
      if (!Array.isArray(columns)) {
        return [];
      }
      const refKeys = ["widget", "editWidget", "widgetList"];
      const cloneRow = (row) => {
        if (!row || typeof row !== "object") {
          return row;
        }
        const cloned = {};
        Object.keys(row).forEach((key) => {
          const val = row[key];
          if (key === "children" && Array.isArray(val) && val.length) {
            cloned.children = val.map(cloneRow);
            return;
          }
          if (refKeys.includes(key)) {
            cloned[key] = val;
            return;
          }
          if (key === "columnOption") {
            if (!row.widget) {
              cloned.columnOption =
                val !== null && typeof val === "object" ? deepClone(val) : val;
            }
            return;
          }
          if (key === "editColumnOption") {
            if (!row.editWidget) {
              cloned.editColumnOption =
                val !== null && typeof val === "object" ? deepClone(val) : val;
            }
            return;
          }
          if (val !== null && typeof val === "object") {
            try {
              cloned[key] = deepClone(val);
            } catch (e) {
              cloned[key] = val;
            }
            return;
          }
          cloned[key] = val;
        });
        if (row.widget && !cloned.widget) {
          cloned.widget = row.widget;
        }
        if (row.editWidget && !cloned.editWidget) {
          cloned.editWidget = row.editWidget;
        }
        return cloned;
      };
      return columns.map(cloneRow);
    },
    buildColumnWidgetMap(columns, map = {}) {
      if (!Array.isArray(columns)) {
        return map;
      }
      columns.forEach((col) => {
        if (col && col.columnId) {
          map[col.columnId] = col;
        }
        if (col.children && col.children.length) {
          this.buildColumnWidgetMap(col.children, map);
        }
      });
      return map;
    },
    restoreColumnWidgetRefs(columns, widgetMap) {
      if (!Array.isArray(columns)) {
        return [];
      }
      return columns.map((row) => {
        const next = Object.assign({}, row);
        const orig = widgetMap[next.columnId];
        if (orig) {
          if (!next.widget && orig.widget) {
            next.widget = orig.widget;
          }
          if (!next.editWidget && orig.editWidget) {
            next.editWidget = orig.editWidget;
          }
          if (
            (!next.widgetList || !next.widgetList.length) &&
            orig.widgetList &&
            orig.widgetList.length
          ) {
            next.widgetList = orig.widgetList;
          }
        }
        if (next.children && next.children.length) {
          next.children = this.restoreColumnWidgetRefs(
            next.children,
            widgetMap
          );
        }
        return next;
      });
    },
    editFormEventHandler(row, index, eventName) {
      this.curEventRow = row;
      this.curEventName = eventName;
      this.curEventIndex = index;
      this.formEventHandlerCode = row[eventName];
      this.showFormEventDialogFlag = true;
    },

    saveFormEventHandler() {
      const codeHints = this.$refs.ecEditor.getEditorAnnotations();
      let syntaxErrorFlag = false;
      if (!!codeHints && codeHints.length > 0) {
        codeHints.forEach((chItem) => {
          if (chItem.type === "error") {
            syntaxErrorFlag = true;
          }
        });

        if (syntaxErrorFlag) {
          this.$message.error(
            this.i18nt("designer.setting.syntaxCheckWarning")
          );
          return;
        }
      }
      this.curEventRow[this.curEventName] = this.formEventHandlerCode;
      this.showFormEventDialogFlag = false;
    },
    onDialogClose() {
      this.tableReady = false;
      this.sourceTableColumnsSnapshot = null;
      if (this.dragSort) {
        this.dragSort.destroy();
        this.dragSort = null;
      }
    },
    onDialogOpen() {
      this.tableReady = false;
      if (this.dragSort) {
        this.dragSort.destroy();
        this.dragSort = null;
      }
      this.$nextTick(() => {
        const load = () => {
          this.loadTableData();
          this.tableReady = true;
          this.$nextTick(() => {
            requestAnimationFrame(() => {
              this.rowDrop();
            });
          });
        };
        if (typeof requestIdleCallback === "function") {
          requestIdleCallback(load, { timeout: 80 });
        } else {
          setTimeout(load, 0);
        }
      });
    },
    loadTableData() {
      const source = this.optionModel.tableColumns || [];
      this.sourceTableColumnsSnapshot = source;
      this.tableData = this.cloneTableColumnsForEdit(source);
    },
    colSubmit() {
      this.dialogVisible = !1;
      const widgetMap = this.buildColumnWidgetMap(
        this.sourceTableColumnsSnapshot || []
      );
      this.optionModel.tableColumns = this.restoreColumnWidgetRefs(
        this.tableData,
        widgetMap
      );
      this.sourceTableColumnsSnapshot = null;
      this.closeHandle();
    },
    openWidgetRenderDialog(row, sourceData) {
      this.currentTableColumn = row;
      this.sourceData = sourceData;

      // this.widgetList =

      // this.designer.widgetList

      this.showColumnRenderDialog = true;
    },
    confirmWidgetRenderDialog(widgetList) {
      this.currentTableColumn.widgetList = widgetList;
      this.showColumnRenderDialog = false;
    },
    showRenderDialog: function (e) {
      /*if(e.formatS == 'widgetRender'){
        this.openWidgetRenderDialog(e);
        return
      }*/

      (this.currentTableColumn = e),
        (this.renderJson = e.render || ""),
        (this.showRenderDialogFlag = !0);
    },
    saveColumnRender: function () {
      this.$set(this.currentTableColumn, "render", this.renderJson),
        (this.showRenderDialogFlag = !1);
    },
    closeHandle() {
      this.$emit("update:visiable", false);
      this.$emit("close");
    },
    // 添加同级节点
    onAddSibling(row, index) {
      console.log("onAddSibling", row, index);
      const parentId = row.parentId || null;
      // 先判断是不是根节点
      if (!parentId) {
        // 当前节点直接添加
        // this.tableData.push(this.generateRow(parentId))
        let addIndex =
          this.tableData
            .filter((item) => !item.parentId)
            .findIndex((item) => item.columnId == row.columnId) + 1;
        this.tableData.splice(addIndex, 0, this.generateRow(parentId));
      } else {
        this.handleAddOneRow(row, index, "SIBLING");
      }
    },
    // 添加子节点  todo
    onAddChild(row, index) {
      this.handleAddOneRow(row, index, "CHILD");
    },
    /**
     * 处理添加一行数据
     * @param {object} row 当前节点
     * @param {number} index
     * @param {string} type 操作类型 SIBLING 同级 / CHILD 子级
     */
    handleAddOneRow(row, index, type) {
      const { parentId, columnId } = row;
      const curId = type === "SIBLING" ? parentId : columnId;
      let curRow = {};
      // 在 tableData 中，找到当前节点
      const findRow = (data) => {
        data.forEach((item) => {
          if (item.columnId === curId) {
            curRow = item;
          }
          if (item.children && item.children.length) {
            findRow(item.children);
          }
        });
      };

      findRow(this.tableData);

      const { columnId: generateParentId, children } = curRow;

      let newRow = this.generateRow(generateParentId);
      if (children) {
        if (type === "SIBLING") {
          let addIndex =
            children.findIndex((item) => item.columnId == row.columnId) + 1;
          children.splice(addIndex, 0, newRow);
        } else {
          children.push(newRow);
        }
      } else {
        this.$set(curRow, "children", [newRow]);
      }
    },
    getUuid() {
      return new Date().getTime();
    },
    createRowAuthName(type) {
      return `row${type}` + generateId();
    },
    /**
     * 生成一行数据
     */
    generateRow(parentId) {
      let tmpId = "column" + generateId();
      let uuid = this.getUuid();
      var row = {
        columnId: uuid,
        kid: uuid,
        parentId: parentId || null,
        required: false,
        width: 150,
        prop: tmpId,
        label: tmpId,
        align: "left",
        show: true,
        sortable: true,
        filterable: true,
        exportType: null,
        footerDataType: null,
        footerMethodConfg: null,
        widgetList: [],
        labelColor: null,
        rowAddAuthName: this.createRowAuthName("Add"),
        rowEditAuthName: this.createRowAuthName("Edit"),
        rowAddShow: null,
        rowEditShow: null,
        utcTransformEnabled: false,
        labelIconClass: null,
        labelIconPosition: "rear",
        labelTooltip: null,
        // treeNode: false,
      };
      return row;
    },
    isUtcTransformColumn(row) {
      const formatS = row.formatS;
      if (!formatS) {
        return true;
      }
      return [
        "d1",
        "d2",
        "d3",
        "d4",
        "d5",
        "render",
        "create_date",
        "modify_date",
      ].includes(formatS);
    },
    // 添加根节点
    onAddRoot() {
      this.tableData.push(this.generateRow());
    },
    // 删除当前节点及对应子节点数据
    onDelete(row) {
      const { parentId, columnId } = row;
      // 根节点直接删除
      if (!parentId) {
        const delIndex = this.tableData.findIndex(
          (item) => item.columnId === columnId
        );
        this.tableData.splice(delIndex, 1);
      } else {
        // 找到父节点，通过父节点删除
        let parentRow = {};
        const findRow = (data) => {
          data.forEach((item) => {
            if (item.columnId === parentId) {
              parentRow = { ...item };
            }
            if (item.children && item.children.length) {
              findRow(item.children);
            }
          });
        };
        findRow(this.tableData);

        const { children } = parentRow;

        const delIndex = children.findIndex(
          (item) => item.columnId === columnId
        );

        children.splice(delIndex, 1);
      }
    },
    // 数据准备 生成 id 和 parentId
    handleTableDataFormat(data) {
      const tableFormat = (tableData, parentId) => {
        tableData.forEach((item) => {
          // item.parentId = parentId || null
          if (!item.kid) item.kid = item.columnId;
          if (item.children && item.children.length > 0) {
            tableFormat(item.children, item.columnId);
          }
        });
      };

      tableFormat(data);
      return data;
    },
    //drag begin
    //行拖拽
    rowDrop() {
      if (this.dragSort) this.dragSort.destroy(); // 防止在Dom上重复绑定事件
      // const tbody = document.querySelector('.drag .el-table__body-wrapper tbody');
      var tbody = this.$refs.singleTable.$el.querySelectorAll(
        ".el-table__fixed-body-wrapper > table > tbody"
      )[0];
      const _this = this;
      this.dragSort = Sortable.create(tbody, {
        ghostClass: "sortable-ghost",
        // draggable: ".drag-option",    // 修改可拖拽元素
        handle: ".drag-option", // 指定拖动按钮
        setData: function (e) {
          e.setData("Text", "");
        },
        onEnd({ newIndex, oldIndex }) {
          _this.rowDropEnd(newIndex, oldIndex);
        },
      });
    },

    //树转数组
    toArray(data) {
      const result = [];
      data.forEach((item) => {
        const loop = (data) => {
          result.push({
            ...data,
          });
          let child = data.children;
          if (child) {
            for (let i = 0; i < child.length; i++) {
              loop(child[i]);
            }
          }
        };
        loop(item);
      });
      return result;
    },
    //数组转树
    arrToTree(arr, parentId) {
      return arr
        .filter((item) =>
          !parentId ? !item.parentId : item.parentId === parentId
        )
        .map((item) => {
          item.children = this.arrToTree(arr, item.columnId);
          return item;
        });
    },
    //查看树中v2 是否 为 v1的底级
    isTreeBottom(tree, v1, v2) {
      let result = false;

      function recursion(tree, v1, v2, flag) {
        for (let i = 0; i < tree.length; i++) {
          const item = tree[i];
          if (item.columnId === v2) {
            result = flag;
            return;
          } else if (item.columnId === v1) {
            item.children ? recursion(item.children, v1, v2, true) : "";
          } else {
            item.children ? recursion(item.children, v1, v2, flag) : "";
          }
        }
      }

      recursion(tree, v1, v2, false);
      return result;
    },
    //行结束拖拽事件
    rowDropEnd(newIndex, oldIndex) {
      //判断是否没有更换位置,如果没更换,则不做任何操作
      if (newIndex === oldIndex) return;
      //树形结构转数组
      this.tableDataArray = this.toArray(this.tableData);

      let oldRow = this.tableDataArray[oldIndex];
      let newRow = this.tableDataArray[newIndex];

      //判断是否把该行 拖拽到 自己的底级中
      if (this.isTreeBottom(this.tableData, oldRow.columnId, newRow.columnId)) {
        this.$message({
          type: "error",
          message: "不能放到子节点",
        });
        let tableData = this.tableData;
        this.tableData = [];
        this.$nextTick(() => {
          this.tableData = tableData;
        });
        return;
      }

      if (oldRow.parentId != newRow.parentId) {
        this.$message({
          type: "error",
          message: "不能放到父节点",
        });
        let tableData = this.tableData;
        this.tableData = [];
        this.$nextTick(() => {
          this.tableData = tableData;
        });
        return;
      }

      let pid = this.tableDataArray[newIndex].parentId || null;
      //拿到当前行数据,并从数组中删除该数据
      const currRow = this.tableDataArray.splice(oldIndex, 1)[0];
      //把当前行数据的 父id 给 赋值为结束位置的父id,因为当前行与结束行平级.父id相同.
      currRow.parentId = pid;
      //把更改了父id的当前行数据给插入到数组中
      this.tableDataArray.splice(newIndex, 0, currRow);
      //表格显示的数据清空
      this.tableData = [];
      this.$nextTick(() => {
        //表格显示的数据  为 修改了位置的数组转换成的属性结构
        this.tableData = this.arrToTree(this.tableDataArray);
        //新的数组为 表格显示的数据转换
        this.tableDataArray = this.toArray(this.tableData);
      });
    },
    getIsButtontCell(formatS) {
      let isButtontCell = false;
      let widgetType = this.columnFormatMap[formatS];
      if (widgetType) {
        isButtontCell =
          widgetType === "a-link" ||
          widgetType === "button" ||
          widgetType === "dropdown";
      }
      return isButtontCell;
    },
    //drag end
    changeFormatS(row, isEdit) {
      let formatS = isEdit ? row.editFormatS : row.formatS;
      let isButtontCell = this.getIsButtontCell(formatS);
      let attachmentPrefix = this.designer.getAttachmentPrefix();
      let columnSelectedWidget = this.designer.createColumnWidget(row, isEdit);
      if (!isEdit) {
        if (columnSelectedWidget) {
          row.widget = columnSelectedWidget;
        } else {
          row.widget = null;
        }
        row.utcTransformEnabled = false;
      } else {
        if (row.prop && row.prop.startsWith(attachmentPrefix)) {
          let suffix = row.prop.replace(attachmentPrefix, "");
          columnSelectedWidget.options.keyName = row.prop;
          columnSelectedWidget.options.keyNameSuffix = suffix;
        }
        if (columnSelectedWidget) {
          row.editWidget = columnSelectedWidget;
        } else {
          row.editWidget = null;
        }
      }

      if (!isEdit) {
        if (row.formatS == "editTreeButtonGroup") {
          row.prop = null;
          row.label = null;
          row.sortable = false;
          row.width = 150;
          row.widget = null;
        } else if (isButtontCell) {
          if (row.formatS == "dropdown") {
            row.width = 100;
          } else if (row.formatS == "aLink" || row.formatS == "button") {
            if (!row.width || row.width == 47) row.width = 150;
          } else {
            row.width = 47;
          }
          row.prop = null;
          row.label = null;
          row.sortable = false;
        } else {
          let tmpId = "column" + generateId();
          if (!row.width || row.width == 47) row.width = 150;
          if (!row.prop) row.prop = tmpId;
          if (!row.label) row.label = tmpId;

          if (this.userFields.includes(row.formatS)) {
            let item = this.businessOptions.find(
              (item) => item.value == row.formatS
            );
            if (item) {
              row.prop = item.value;
              row.label = item.label;
            }
          }

          row.sortable = true;

          if (!isEdit) {
            if (formatS == "editAttachment") {
              row.prop = columnSelectedWidget.options.keyName;
            } else {
              row.prop = row.prop.replaceAll(attachmentPrefix, "");
            }
          }
        }
      }
    },
    getColumnWidgetConfig(row, isChange, isEdit) {
      let formatS = isEdit ? row.editFormatS : row.formatS;
      let columnSelectedWidget = null;
      let columnEditFields = null;

      let type = this.columnFormatMap[formatS];

      if (type) {
        const applyNewWidgetDefaults = (widget) => {
          widget.options.required = row.required || false;
          if ("editDelete" == formatS) {
            widget.options.prefixIcon = "el-icon-delete";
            widget.options.label = "删除";
            widget.options.labelHidden = true;
            widget.options.hiddenByWf = true;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nlet tableRef = this.getWidgetRef(this.parentWidget.options.name);\ntableRef.deleteRow(tableParam.row,tableParam.rowIndex);";
          } else if ("editButton" == formatS) {
            widget.options.prefixIcon = "el-icon-edit";
            widget.options.label = "查看";
            widget.options.labelHidden = true;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nlet tableRef = this.getWidgetRef(this.parentWidget.options.name);\ntableRef.openEditDialog(tableParam.row)";
          } else if ("addSiblingEditRow" == formatS) {
            widget.options.prefixIcon = "el-icon-plus";
            widget.options.label = "新增兄弟节点";
            widget.options.labelHidden = false;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nthis.getParentTarget().addSiblingTreeRow(null,tableParam);";
          } else if ("addChildTreeRow" == formatS) {
            widget.options.prefixIcon = "el-icon-plus";
            widget.options.label = "新增子节点";
            widget.options.labelHidden = false;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nthis.getParentTarget().addChildTreeRow(null,tableParam);";
          } else if ("moveUpRow" == formatS) {
            widget.options.label = "↑上移";
            widget.options.labelHidden = false;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nthis.getParentTarget().moveUpRow(tableParam);";
          } else if ("moveDownRow" == formatS) {
            widget.options.label = "↓下移";
            widget.options.labelHidden = false;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nthis.getParentTarget().moveDownRow(tableParam);";
          } else if ("removeTreeRow" == formatS) {
            widget.options.prefixIcon = "el-icon-delete";
            widget.options.label = "删除";
            widget.options.labelHidden = true;
            widget.options.onClick =
              "let tableParam = this.tableParam;\nthis.getParentTarget().removeTreeRow(tableParam);";
          }
        };

        if (!isChange) {
          const sourceWidget = this.designer.getColumnWidget(row, isEdit);
          if (sourceWidget) {
            columnSelectedWidget = this.$baseLodash.cloneDeep(sourceWidget);
            columnSelectedWidget.options.required = row.required || false;
            if ("editDelete" == formatS) {
              columnSelectedWidget.options.hiddenByWf =
                columnSelectedWidget.options.hiddenByWf ?? true;
              columnSelectedWidget.options.prefixIcon =
                columnSelectedWidget.options.prefixIcon || "el-icon-delete";
            } else if ("editButton" == formatS) {
              columnSelectedWidget.options.prefixIcon =
                columnSelectedWidget.options.prefixIcon || "el-icon-edit";
            }
          } else {
            columnSelectedWidget = this.designer.copyNewFieldWidget(
              this.designer.getFieldWidgetByType(type)
            );
            applyNewWidgetDefaults(columnSelectedWidget);
          }
        } else {
          columnSelectedWidget = this.designer.copyNewFieldWidget(
            this.designer.getFieldWidgetByType(type)
          );
          applyNewWidgetDefaults(columnSelectedWidget);
        }

        if (columnSelectedWidget.options.hasOwnProperty("keyName")) {
          columnSelectedWidget.options.keyName = row.prop;
          columnSelectedWidget.options.keyNameEnabled = true;
        } else {
          columnSelectedWidget.options.name = row.prop;
        }

        if (type != "button" && type != "a-link") {
          columnSelectedWidget.options.label = row.label;
          columnSelectedWidget.options.labelHidden = true;
        }
      }
      return { columnSelectedWidget, columnEditFields };
    },
    findColumnByColumnId(columnList, columnId) {
      let result = null;
      if (columnList) {
        let column = columnList.find((item) => item.columnId == columnId);
        for (let column of columnList) {
          if (column.columnId == columnId) {
            result = column;
            break;
          } else if (column.children && column.children.length) {
            let subColumn = this.findColumnByColumnId(
              column.children,
              children
            );
            if (subColumn) {
              result = subColumn;
              break;
            }
          }
        }
      }
      return result;
    },

    getRowWidget(row) {
      let widget = row.widget;
      if (!widget) {
        widget.options.a = a;
        widget.options.a = a;
      }
      return widget;
    },
    confirmEditTreeButtonGroupConfig(rowConfig) {
      if (this.currentEditTreeButtonGroupRow) {
        Object.assign(this.currentEditTreeButtonGroupRow, rowConfig);
      }
      this.currentEditTreeButtonGroupRow = null;
      this.editTreeButtonGroupRowData = null;
    },
    openFormatConfigDialog(row, index) {
      if (row.formatS === "editTreeButtonGroup") {
        this.currentEditTreeButtonGroupRow = row;
        this.editTreeButtonGroupRowData = this.$baseLodash.cloneDeep(row);
        this.showEditTreeButtonGroupConfigDialog = true;
        return;
      }
      if (row.formatS == "widgetRender") {
        let formWidgetList = deepClone(this.designer.widgetList);
        const widgetMap = this.buildColumnWidgetMap(
          this.sourceTableColumnsSnapshot || this.optionModel.tableColumns || []
        );
        let tableData = this.restoreColumnWidgetRefs(
          this.cloneTableColumnsForEdit(this.tableData),
          widgetMap
        );
        let columnId = row.columnId;

        let dataTableName = this.optionModel.name;

        let targetColumn = null;
        loopHandleWidget(formWidgetList, (item) => {
          if (item.options.name == dataTableName) {
            item.options.tableColumns = tableData;
            targetColumn = this.findColumnByColumnId(
              item.options.tableColumns,
              columnId
            );
          }
        });
        let getWidgetList = (subWidgetList = []) => {
          targetColumn.widgetList = this.$baseLodash.cloneDeep(subWidgetList);
          return formWidgetList;
        };
        let sourceData = {
          formWidgetList,
          dataTableName,
          columnId,
          getWidgetList,
        };

        this.openWidgetRenderDialog(row, sourceData);
        return;
      }

      const { columnSelectedWidget, columnEditFields } =
        this.getColumnWidgetConfig(row);
      if (!columnSelectedWidget) {
        this.$message.warning(this.$t1("请先选择列格式化类型"));
        return;
      }
      columnSelectedWidget.options = this.$baseLodash.cloneDeep(
        columnSelectedWidget.options
      );
      this.operateIndex = index;
      this.openWidgetPropertyDialog({
        row: row,
        columnSelectedWidget,
        tableColumns: this.tableData,
        index: index,
        columnEditFields,
        callback: (confirmedWidget) => {
          this.confirmFormatConfigDialog(confirmedWidget, row);
        },
      });
    },
    getFieldKeyNameByOptions(options) {
      let o = options.name;
      return (options.keyNameEnabled && options.keyName) || o;
    },
    confirmFormatConfigDialog(columnSelectedWidget, row) {
      row.widget = columnSelectedWidget;
      const options = columnSelectedWidget.options;

      let isButtontCell = this.getIsButtontCell(row.formatS);
      if (!isButtontCell) {
        row.prop = this.getFieldKeyNameByOptions(options);
        row.label = options.label;
        row.required = options.required;
      }
    },
    openEditFormatConfigDialog(row, index) {
      const { columnSelectedWidget, columnEditFields } =
        this.getColumnWidgetConfig(row, false, true);
      if (!columnSelectedWidget) {
        this.$message.warning(this.$t1("请先选择编辑列格式化类型"));
        return;
      }
      columnSelectedWidget.options = this.$baseLodash.cloneDeep(
        columnSelectedWidget.options
      );
      this.operateIndex = index;
      this.openWidgetPropertyDialog({
        row: row,
        tableColumns: this.tableData,
        columnSelectedWidget,
        index: index,
        columnEditFields,
        callback: (confirmedWidget) => {
          this.confirmEditFormatConfigDialog(confirmedWidget, row);
        },
      });
    },
    confirmEditFormatConfigDialog(columnSelectedWidget, row) {
      row.editWidget = columnSelectedWidget;
    },
    openTableColumnConfigDialog(row, index) {
      this.operateIndex = index;
      this.currentTableColumn = row;
      let eventName = "tableColumnConfig";
      let eventParams = ["dataId", "formCode"];
      this.tableColumnConfigHeader = `${
        this.optionModel.name
      }.${eventName}(${eventParams.join(", ")}) {`;
      this.tableColumnConfigCode = this.$baseLodash.cloneDeep(
        row.tableColumnConfig || ""
      );

      this.tableColumnConfigTitle = `自定义表格列属性配置(${row.label})`;
      this.showTableColumnConfigDialog = true;
    },
    saveTableColumnConfigDialog() {
      let row = this.currentTableColumn;
      const codeHints = this.$refs.ecEditor.getEditorAnnotations();
      let syntaxErrorFlag = false;
      if (!!codeHints && codeHints.length > 0) {
        codeHints.forEach((chItem) => {
          if (chItem.type === "error") {
            syntaxErrorFlag = true;
          }
        });

        if (syntaxErrorFlag) {
          this.$message.error(
            this.i18nt("designer.setting.syntaxCheckWarning")
          );
          return;
        }
      }
      this.$set(
        row,
        "tableColumnConfig",
        this.$baseLodash.cloneDeep(this.tableColumnConfigCode)
      );
      this.showTableColumnConfigDialog = false;
    },
    changeRowLabel(row) {
      this.setRowWidgetAttars(row, "label", row.label);
    },
    changeRowProp(row) {
      this.setRowWidgetAttars(row, "keyName", row.prop);
    },
    changeRowRequired(row) {
      this.setRowWidgetAttars(row, "required", row.required);
    },
    setRowWidgetAttars(row, key, value) {
      let type1 = this.columnFormatMap[row.formatS];
      let type2 = this.columnFormatMap[row.editFormatS];
      let newWidget = type1
        ? this.designer.copyNewFieldWidget(
            this.designer.getFieldWidgetByType(type1)
          )
        : null;

      let newEditWidget = type2
        ? this.designer.copyNewFieldWidget(
            this.designer.getFieldWidgetByType(type2)
          )
        : null;

      if (newWidget && newWidget.formItemFlag && row.widget) {
        if (row.widget.options[key] !== undefined) {
          row.widget.options[key] = value;
        }
      }

      if (newEditWidget && newEditWidget.formItemFlag && row.editWidget) {
        if (row.editWidget.options[key] !== undefined) {
          row.editWidget.options[key] = value;
        }
      }
    },
    openRowEditDialog(row, index) {
      this.editRowData = row;
      this.rowData = this.cloneTableColumnsForEdit([row])[0];
      this.rowDataIndex = index;
      this.showRowEditDialog = true;
    },
    submitRowEditDialog() {
      Object.assign(this.editRowData, this.rowData);
      if (this.rowData.widget) {
        this.editRowData.widget = this.rowData.widget;
      }
      if (this.rowData.editWidget) {
        this.editRowData.editWidget = this.rowData.editWidget;
      }
      if (this.rowData.widgetList && this.rowData.widgetList.length) {
        this.editRowData.widgetList = this.rowData.widgetList;
      }
      this.showRowEditDialog = false;
    },
    closeRowEditDialog() {
      this.showRowEditDialog = false;
    },
  },
};
</script>
<style scoped lang="scss">
.icon-drag:before {
  content: "\e61d";
}

/* 固定弹框内容区高度，避免加载前后抖动 */
::v-deep .table-column-config-dialog.el-dialog {
  .el-dialog__body {
    height: 532px;
    max-height: 532px;
    overflow: hidden;
    box-sizing: border-box;
  }
}

.table-column-dialog-cont {
  height: 516px;
  min-height: 516px;
  max-height: 516px;
  overflow: hidden;
  box-sizing: border-box;
}

/* 完整列配置弹框：挂到 body，内容区可滚动 */
::v-deep .table-column-row-edit-dialog.el-dialog {
  .el-dialog__body {
    max-height: calc(90vh - 130px);
    overflow-y: auto;
    overflow-x: hidden;
    box-sizing: border-box;
  }
}

.table-column-row-edit-cont {
  padding-bottom: 8px;
  box-sizing: border-box;

  ::v-deep .form-m2 {
    height: auto;
    overflow: visible;

    .form-item-full {
      width: calc(100% - 20px) !important;
      display: block;
    }

    .form-item-full .el-input {
      width: 100% !important;
    }
  }

  ::v-deep .custom-divider.el-divider--horizontal {
    margin: 10px 0;
  }
}
</style>
