<template>
  <el-dialog
    custom-class="dialog-style list-dialog"
    title="明细导出列维护"
    :visible.sync="showDialog"
    :modal="false"
    :show-close="!0"
    :close-on-click-modal="!1"
    :close-on-press-escape="!1"
    :destroy-on-close="!0"
    top="5vh"
    width="1220px"
    v-dialog-drag
    @close="closeHandle"
  >
    <div class="cont">
      <el-table
        ref="singleTable"
        width="100%"
        row-key="id"
        :data="tableData"
        height="500"
        border=""
        stripe=""
        v-loading="pictLoading"
        element-loading-background="rgba(0, 0, 0, 0)"
        element-loading-text="数据正在加载中"
        element-loading-spinner="el-icon-loading"
      >
        <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="title"
          fixed="left"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.title"
              clearable=""
              :disabled="!!scope.row.formatS && userFields.includes(scope.row.formatS)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :label="i18nt('designer.setting.columnName')"
          width="150"
          prop="field"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.field"
              clearable=""
              :disabled="!!scope.row.formatS && userFields.includes(scope.row.formatS)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="导出类型" width="150" prop="exportType">
          <template #default="scope">
            <el-select v-model="scope.row.exportType" clearable>
              <el-option value="Image2" label="图片"></el-option>
              <el-option value="Number" label="数值"></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)"
              clearable
            >
              <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="i18nt('designer.setting.renderFunction')"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-button
              :disabled="'render' !== scope.row.formatS"
              size="mini"
              plain=""
              round=""
              icon="el-icon-edit"
              @click="showRenderDialog(scope.row)"
              >{{ scope.row.render ? "已维护" : "" }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <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-delete"
                @click="onDelete(row, $index)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </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>
</template>
<script>
import i18n from "../../../../../../components/xform/utils/i18n";
import Sortable from "sortablejs";
import { generateId } from "../../../../../../components/xform/utils/util";
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,
  },
  data() {
    return {
      pictLoading: true,
      dragSort: null,
      showDialog: true,
      tableData: [],
      showRenderDialogFlag: !1,
      renderJson: "",
      currentTableColumn: null,
      businessOptions,
      userFields,
      hideAfter: 1500,
      openDelay: 500,
      op: [
        {
          label: "动态渲染",
          options: [
            {
              value: "render",
              label: "render",
            },
          ],
        },
        {
          label: "业务模块",
          options: businessOptions,
        },
        {
          label: "Date Format",
          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: "Number Format",
          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##%",
            },
          ],
        },
      ],
    };
  },
  beforeDestroy() {
    if (this.dragSort) this.dragSort.destroy();
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      setTimeout(() => {
        this.tableData = this.$baseLodash.cloneDeep(
          this.optionModel.exportItemColumns || []
        );
        setTimeout(() => {
          this.rowDrop();
          this.pictLoading = false;
        }, 200);
      });
    },
    closeHandle() {
      this.showDialog = false;
      this.$emit("update:visiable", false);
    },
    colSubmit() {
      for (let i = 0; i < this.tableData.length; i++) {
        let row = this.tableData[i];
        if (!row.title || !row.field) {
          this.$message.error("请输入显示名称和字段名称");
          return;
        }
      }
      this.optionModel.exportItemColumns = this.$baseLodash.cloneDeep(this.tableData);
      this.closeHandle();
    },
    generateRow() {
      let tmpId = "column" + generateId();
      var row = {
        id: tmpId,
        field: null,
        title: null,
        formatS: null,
        render: null,
        exportType: null,
      };
      return row;
    },
    // 添加根节点
    onAddRoot() {
      this.tableData.push(this.generateRow());
    },
    // 删除当前节点及对应子节点数据
    onDelete(row, index) {
      this.tableData.splice(index, 1);
    },
    showRenderDialog: function (e) {
      (this.currentTableColumn = e),
        (this.renderJson = e.render || ""),
        (this.showRenderDialogFlag = !0);
    },
    saveColumnRender: function () {
      this.$set(this.currentTableColumn, "render", this.renderJson),
        (this.showRenderDialogFlag = !1);
    },
    changeFormatS(row) {
      if (this.userFields.includes(row.formatS)) {
        let item = this.businessOptions.find((item) => item.value == row.formatS);
        if (item) {
          row.field = item.value;
          row.title = item.label;
        }
      }
    },
    //行拖拽
    rowDrop() {
      if (this.dragSort) this.dragSort.destroy(); // 防止在Dom上重复绑定事件
      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);
        },
      });
    },
    //行结束拖拽事件
    rowDropEnd(newIndex, oldIndex) {
      if (oldIndex === newIndex) return;

      const newData = [...this.tableData];
      const movedRow = newData.splice(oldIndex, 1)[0];

      // 关键：如果 oldIndex < newIndex，说明删除后 newIndex 需要 -1
      const insertIndex = oldIndex < newIndex ? newIndex - 1 : newIndex;

      newData.splice(insertIndex, 0, movedRow);
      this.tableData = newData; // 触发响应式更新
    },
  },
};
</script>
<style lang="scss"></style>
