<template>
  <div>
    <el-dialog
      custom-class="dialog-style list-dialog"
      :title="title"
      :visible.sync="dialogVisible"
      :show-close="!0"
      :append-to-body="false"
      :modal="false"
      :close-on-click-modal="!1"
      :close-on-press-escape="!1"
      :destroy-on-close="!0"
      width="1220px"
      v-dialog-drag
      v-el-dialog-center
      @close="closeDialog"
    >
      <div class="cont" style="height:calc(100vh -  120px)">
        <el-form :model="option" label-width="120px">
          <el-form-item label="请求地址">
            <el-input type="text" v-model="option.url" placeholder="/user/form_ins/listPage"
                      style="width: 240px !important;"></el-input>
          </el-form-item>
          <el-form-item label="展示字段key" v-if="type==1">
            <el-input
              class="search-input"
              max="200"
              v-model="option.showFormField"
              @clear="
                $forceUpdate();
              "
              clearable
              style="width: 240px !important;"
            >
              <i slot="suffix" class="el-input__icon el-icon-search" @click="openFormFieldDialog"
                 v-if="!!targetFormCode"></i>
            </el-input>
          </el-form-item>
          <el-form-item label-width="0">
            <el-divider class="custom-divider-margin-top">查询参数维护</el-divider>
          </el-form-item>
          <el-alert type="info" :closable="false" title="pram(){"></el-alert>
          <code-editor :mode="'javascript'" :readonly="false" v-model="option.searchParams"
                       ref="ecEditor"></code-editor>
          <el-alert type="info" :closable="false" title="}"></el-alert>
          <el-form-item label-width="0">
            <el-divider class="custom-divider-margin-top">查询字段维护(
              <el-button size="mini" @click="createDefaultSearchs">初始化</el-button>
              )
            </el-divider>
          </el-form-item>
          <el-table
            ref="paramTable"
            width="100%"
            :data="option.searchFields"
            max-height="300"
            border=""
            row-key="columnId"
            stripe=""
          >
            <el-table-column type="index" width="35" fixed="left"></el-table-column>
            <el-table-column label="" width="35"><i class="el-icon-s-operation drag-option"></i></el-table-column>
            <el-table-column :label="i18nt('designer.setting.columnName')" width="150" prop="prop">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prop"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.columnLabel')" width="150" prop="label">
              <template slot-scope="scope">
                <el-input v-model="scope.row.label"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.actionColumn')" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  :title="i18nt('designer.setting.deleteTableColumn')"
                  size="mini"
                  type=""
                  circle=""
                  icon="el-icon-minus"
                  @click="handlSearcheDelete(scope.$index, scope.row)"
                ></el-button>
              </template>
              <template #header="{ column, $index }">
                {{ i18nt('designer.setting.actionColumn') }}
                <el-button :title="i18nt('designer.setting.addTableColumn')" size="mini" type="" circle=""
                           icon="el-icon-plus" @click="addSearchCol"></el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-form-item label-width="0">
            <el-divider class="custom-divider-margin-top">列表字段维护(
              <el-button size="mini" @click="createDefaultColumns">初始化</el-button>
              )
            </el-divider>
          </el-form-item>
          <el-table
            ref="singleTable"
            width="100%"
            :data="option.tableColumns"
            max-height="500"
            border=""
            row-key="columnId"
            stripe=""
          >
            <el-table-column type="index" width="35" fixed="left"></el-table-column>
            <el-table-column label="" width="35"><i class="el-icon-s-operation drag-option"></i></el-table-column>
            <el-table-column :label="i18nt('designer.setting.columnName')" width="150" prop="prop">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prop"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.columnLabel')" width="150" prop="label">
              <template slot-scope="scope">
                <el-input v-model="scope.row.label"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.columnWidth')" width="100" prop="width">
              <template slot-scope="scope">
                <el-input v-model="scope.row.width"></el-input>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.visibleColumn')" width="70" prop="show">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.show"></el-switch>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('必填')" width="70" prop="required">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.required"></el-switch>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.sortableColumn')" width="70" prop="sortable">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.sortable"></el-switch>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.fixedColumn')" width="100" prop="fixed">
              <template slot-scope="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.alignTypeOfColumn')" width="100" prop="align">
              <template slot-scope="scope">
                <el-select v-model="scope.row.align">
                  <el-option v-for="e in alignOptions" :value="e.value" :label="e.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="i18nt('designer.setting.formatOfColumn')" width="200" prop="formatS">
              <template slot-scope="scope">
                <el-select v-model="scope.row.formatS" 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="i18nt('designer.setting.renderFunction')" width="70" fixed="right" align="center">
              <template slot-scope="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.actionColumn')" width="100" fixed="right" align="center">
              <template #header="{ column, $index }">
                {{ i18nt('designer.setting.actionColumn') }}
                <el-button :title="i18nt('designer.setting.addTableColumn')" size="mini" type="" circle=""
                           icon="el-icon-plus" @click="addCol"></el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  :title="i18nt('designer.setting.deleteTableColumn')"
                  size="mini"
                  type=""
                  circle=""
                  icon="el-icon-minus"
                  @click="handleDelete(scope.$index, scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button type="" @click="dialogVisible = !1" class="button-sty" icon="el-icon-close">
            {{ i18nt('designer.hint.cancel') }}
          </el-button>
          <el-button type="primary" class="button-sty" icon="el-icon-check" @click="colSubmit">
            {{ i18nt('designer.hint.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="i18nt('designer.setting.renderFunction')"
      :visible.sync="showRenderDialogFlag"
      append-to-body=""
      :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
    >
      <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="closeDialog" 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>
    <formFieldDialog v-if="showFormFieldDialog" :visiable.sync="showFormFieldDialog"
                     @confirm="confirmFormField" :formCode="targetFormTemplate.formCode"
                     :formVersion="targetFormTemplate.formVersion"
                     multi="false"/>
  </div>
</template>

<script>
import i18n from '../../../../../../components/xform/utils/i18n';
import {generateId, deepClone} from "../../../../../../components/xform/utils/util";
import Sortable from "sortablejs";
import formFieldDialog from "../../../../../../components/xform/form-designer/form-widget/dialog/formFieldDialog";

export default {
  name: "vabsearchConfigDialog",
  mixins: [i18n],
  components: {formFieldDialog},
  inject: ['getReportTemplate', 'getFormTemplateTableDTOs'],
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object,
    type: {
      type: Number,
      default: () => 1,//1 弹框， 2 列表
    },
    isFormConfig: {
      type: Boolean,
      default: () => false
    }
  },
  computed: {
    title() {
      let type = this.type;
      return type == 1 ? '表单弹框配置' : '表单列表配置';
    },
    typeField() {
      let type = this.type;
      return type == 1 ? 'dialogConfig' : 'gridConfig';
    },
    targetFormCode() {
      if (this.isFormConfig) {
        let targetFormTemplate = this.getReportTemplate();
        return targetFormTemplate.formCode
      } else {
        return this.optionModel.formCode
      }
    }
  },
  data() {
    return {
      dialogVisible: true,
      option: {
        tableColumns: [],
        searchFields: [],
        searchParams: null
      },
      alignOptions: [
        {
          value: 'left',
          label: 'left'
        },
        {
          value: 'center',
          label: 'center'
        },
        {
          value: 'right',
          label: 'right'
        }
      ],
      fieldTypeOptions: [
        {
          value: 'text',
          label: 'Text'
        },
        {
          value: 'number',
          label: 'Number'
        },
        {
          value: 'date',
          label: 'Date'
        }
      ],
      op: [
        {
          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##%'
            }
          ]
        }
      ],
      showRenderDialogFlag: !1,
      renderJson: '',
      currentTableColumn: null,
      showFormFieldDialog: false,
      targetFormTemplate: {},
      tableColumns: [],
      searchFields: []
    }
  },
  created() {
    let gridConfig = this.$baseLodash.cloneDeep(this.optionModel[this.typeField] || {});
    gridConfig.searchFields = gridConfig.searchFields || [];
    gridConfig.tableColumns = gridConfig.tableColumns || [];
    if (!gridConfig.type) gridConfig.type = 1;//type 1:默认请求方式，其他请求方式
    this.option = gridConfig;
  },
  async mounted() {
    this.initFormFields();
    this.$nextTick(function () {
      this.dragSort();
      this.dragSearchSort();
    });
  },
  methods: {
    dragSort: function () {
      var e = this.$refs.singleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0],
        t = this.option.tableColumns;
      this.sortable = Sortable.create(e, {
        ghostClass: 'sortable-ghost',
        setData: function (e) {
          e.setData('Text', '');
        },
        onEnd: function (e) {
          var i = t.splice(e.oldIndex, 1)[0];
          t.splice(e.newIndex, 0, i);
          t[e.newIndex].id;
          t[e.newIndex - 1] && t[e.newIndex - 1].id, t[e.newIndex + 1] && t[e.newIndex + 1].id;
        }
      });
    },
    dragSearchSort: function () {
      var e = this.$refs.paramTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0],
        t = this.option.searchFields;
      this.sortable2 = Sortable.create(e, {
        ghostClass: 'sortable-ghost',
        setData: function (e) {
          e.setData('Text', '');
        },
        onEnd: function (e) {
          var i = t.splice(e.oldIndex, 1)[0];
          t.splice(e.newIndex, 0, i);
          // t[e.newIndex].id;
          // t[e.newIndex - 1] && t[e.newIndex - 1].id, t[e.newIndex + 1] && t[e.newIndex + 1].id;
        }
      });
    },
    showRenderDialog: function (e) {
      (this.currentTableColumn = e), (this.renderJson = e.render || ''), (this.showRenderDialogFlag = !0);
    },
    colSubmit: function () {
      this.optionModel[this.typeField] = this.$baseLodash.cloneDeep(this.option);
      this.dialogVisible = !1;
      this.$emit('update:visiable', false);
    },
    addSearchCol: function () {
      var e = {
        prop: null,
        label: null
      };
      this.option.searchFields.push(e);
    },
    addCol: function () {
      let tmpId = 'column' + generateId();
      var e = {
        columnId: new Date().getTime(),
        required: false,
        width: 150,
        prop: tmpId,
        label: tmpId,
        show: true,
        sortable: true
      };
      this.option.tableColumns.push(e), this.designer.emitHistoryChange();
    },
    handlSearcheDelete: function (e, t) {
      this.option.searchFields.splice(e, 1);
    },
    handleDelete: function (e, t) {
      this.option.tableColumns.splice(e, 1);
    },
    saveColumnRender: function () {
      this.$set(this.currentTableColumn, 'render', this.renderJson);
      this.closeDialog();
    },
    editEventHandler(eventName, eventParams) {
      this.dispatch('SettingPanel', 'editEventHandler', [eventName, [...eventParams]])
    },
    closeDialog() {
      this.showRenderDialogFlag = !1;
      this.$emit('update:visiable', false);
    },
    confirmFormField(rows) {
      if (rows.length) {
        let row = rows[0];
        // this.optionModel.showFormField = row.fieldName;
        this.option.showFormField = row.fieldName;
      }
    },
    openFormFieldDialog() {
      if (this.isFormConfig) {
        let targetFormTemplate = this.getReportTemplate();
        this.targetFormTemplate = targetFormTemplate;
      } else {
        if (!this.optionModel.formCode) {
          return
        }
        this.targetFormTemplate = {
          formCode: this.optionModel.formCode,
          formVersion: this.optionModel.formVersion
        }
      }

      this.showFormFieldDialog = true;
    },


    async initFormFields() {
      let formConfig, formCode;
      if (this.isFormConfig) {
        formConfig = this.getFormJson();
        let targetFormTemplate = this.getReportTemplate();
        formCode = targetFormTemplate.formCode;
      } else {
        formCode = this.optionModel.formCode;
        if (!formCode) return;
        await this.$http({
          url: USER_PREFIX + `/formTemplate/getByFormCode`,
          method: `post`,
          data: {
            stringOne: formCode
          },
          isLoading: true,
          loadingTarget: document.body,
          success: res => {
            let targetFormTemplate = res.objx || {};
            formConfig = targetFormTemplate.formViewContent ? JSON.parse(targetFormTemplate.formViewContent) : {};
          }
        });
      }
      let formTemplateTableDTOs = this.getFormTemplateTableDTOs(formConfig, formCode);
      let formTemplateTableDTO = formTemplateTableDTOs.find(item => item.tableType == 0);
      let formInsListFieldDTOs = [];
      if (formTemplateTableDTO) {
        formInsListFieldDTOs = formTemplateTableDTO.formTemplateFieldDTOs || [];
      }
      let tableColumns = formInsListFieldDTOs.map(row => {
        return {
          label: row.fieldDesc,
          prop: row.fieldName,
          width: 150
        }
      })
      this.tableColumns = tableColumns;
      this.searchFields = formInsListFieldDTOs.map(row => {
        return {
          label: row.fieldDesc,
          prop: row.fieldName,
          width: 150
        }
      })
    },
    createDefaultSearchs() {
      let defaultTableColumns = this.$baseLodash.cloneDeep(this.searchFields);
      let searchFields = this.option.searchFields
      let keys = searchFields.map(item => item.prop);
      let items = defaultTableColumns.filter(item => !keys.includes(item.prop));
      this.option.searchFields.push(...items);
    },
    createDefaultColumns() {
      let defaultTableColumns = this.$baseLodash.cloneDeep(this.tableColumns);
      let tableColumns = this.option.tableColumns
      let keys = tableColumns.map(item => item.prop);
      let items = defaultTableColumns.filter(item => !keys.includes(item.prop))
      this.option.tableColumns.push(...items);

    },
    getFormJson() {
      return {
        widgetList: deepClone(this.designer.widgetList),
        formConfig: deepClone(this.designer.formConfig)
      };
    },
  }
}
</script>

<style scoped>

</style>
