<template>
  <el-dialog
    title="单据列表"
    :append-to-body="true"
    :modal-append-to-body="true"
    :close-on-click-modal="falseValue"
    :visible.sync="showDialog"
    :modal="falseValue"
    custom-class="dialog-style list-dialog dialog-checkbox pd_0"
    width="1200px"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
  >
    <div class="cont" style="height:450px">
      <vxe-grid
        class="is-pointer"
        ref="table-m1"
        v-bind="vxeOption"
        @resizable-change="$vxeTableUtil.onColumnWitchChange"
        @custom="$vxeTableUtil.customHandle"
        @checkbox-change="addDataTable"
        @checkbox-all="checkAll"
        @cell-dblclick="checkWithSubmit"
      >
        <template #form>
          <div class="clearfix screen-btns">
            <div class="fr">
              <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                          plain>重置
              </vxe-button>
              <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">搜索</vxe-button>
            </div>
          </div>
          <template v-if="searchFields.length>0">
            <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData"
                      @submit="searchEvent" @reset="searchEvent">
              <vxe-form-item v-for="(item,index) in searchFields"
                             :key="index" :title="item.label+':'">
                <template v-slot>
                  <el-input v-model="formData[item.prop]" size="small" clearable/>
                </template>
              </vxe-form-item>
            </vxe-form>
          </template>
        </template>
      </vxe-grid>
    </div>
    <label id="labBtn" class="transverse">
      <div class="icon">
        <i class="el-icon-more"></i>
        <i class="el-icon-more"></i>
      </div>
    </label>
    <div class="multipleChoice">
      <el-tooltip :enterable="false" effect="dark" :content="$t1('全部删除')" placement="top"><a class="allDel icon-quanbushanchu"
                                                                                     @click="clearChecked()"></a>
      </el-tooltip>
      <div class="list">
        <div class="item" v-for="(checkRow, index) in checkRows" :key="'c'+index">
          <p>{{ checkRow[showFormField] }}</p>
          <a class="el-icon-close" @click="clearTable1Select(index)"></a>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
			<span class="fl tips" v-if="!selectMulti">{{ $t1('注：双击确认选择（单选）') }}</span>
			<el-button type="primary" plain class="button-sty" @click="dialogClose">
				<i class="el-icon-close el-icon"></i>
				{{ $t2('取 消', 'system.button.cancel2') }}
			</el-button>
			<el-button type="primary" @click="dialogPrimary" class="button-sty">
				<i class="el-icon-check el-icon"></i>
				{{ $t2('确 定', 'system.button.confirm2') }}
			</el-button>
		</span>
  </el-dialog>
</template>

<script>
import {selectDialogMixins} from '../../../../../mixins/selectDialog/index.js';

export default {
  name: "vabSearchDialog",
  props: ['visiable', 'multi', 'rows', 'param', 'formCode', 'showFormField', 'widget'],
  mixins: [selectDialogMixins],
  inject: ['scriptHttp'],
  created() {
    this.initSetting();
    this.checkField = this.showFormField;
  },
  mounted() {
    this.initTableM1();
  },
  data() {
    var that = this;
    return {
      showDialog: true,
      falseValue: false,
      selectMulti: true,
      formData: {},
      vxeOption: {},
      formInsListField0DTOs: [],
      formInsListField1DTOs: [],
      targetFormTemplate: null,
      formJson: null,
      tableColumns: [],
      searchFields: [],
      tableConfig: {},
      checkField: null,
      filedKey: 'dialogConfig'
    };
  },
  methods: {
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.$refs['table-m1'].commitProxy('reload');
    },
    async initTableM1() {
      let that = this;
      let tableRef = 'table-m1';
      let syncColumns = [];
      await this.createColumns().then(res => {
        syncColumns = res;
      });
      this.checkField = this.tableConfig.showFormField || this.showFormField || 'id';
      let defaultPath = USER_PREFIX + '/form_ins/listPage';
      let path = this.tableConfig.url || defaultPath;

      let optionModel = this.widget.options;
      let targetFormConfig = this.targetFormConfig;
      let isScriptEnabled = false;
      let scriptUuid = null;
      let scriptUuid2 = null;
      let returnType = 0;
      if (this.targetFormTemplate) {
        let gridConfig = targetFormConfig[this.filedKey] || {};
        isScriptEnabled = !!gridConfig.isLoadDataByAccess && !!gridConfig.scriptUuid;
        scriptUuid = gridConfig.scriptUuid;
        scriptUuid2 = gridConfig.scriptUuid2;
        returnType = isScriptEnabled ? gridConfig.accessReturnType : 1;
      } else {
        isScriptEnabled = !!optionModel.isLoadDataByAccess && !!optionModel.scriptUuid;
        scriptUuid = optionModel.scriptUuid;
        scriptUuid2 = optionModel.scriptUuid2;
        returnType = isScriptEnabled ? optionModel.accessReturnType : 1;
      }
      if(returnType===null || returnType===undefined){
        returnType = 1;
      }

      let tableOption = {
        vue: that,
        tableRef: tableRef,
        tableName: 'user-form_form_ins_dialog-m1',
        path: path,
        param: () => {
          let customParam = this.getCustomParam();
          let condition = {
            ...this.formData,
            ...this.param,
            ...customParam
          }
          Object.keys(condition).forEach(key => {
            if (condition[key] === "" || condition[key] === null) {
              delete condition[key]
            }
          })
          if (path == defaultPath) {
            return {
              formCode: this.formCode,
              condition: condition
            };
          } else {
            return {
              ...condition
            };
          }

        },
        columns: [
          {type: 'checkbox', fixed: 'left', width: 48, resizable: false},
          ...syncColumns,
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false
          }
        ],
        config: {
          checkboxConfig: {
            checkStrictly: true,
            showHeader: this.selectMulti,
            trigger: 'row'
          },
          proxyConfig: {
            props: {
              result: returnType === 1 ? 'objx.records' : 'objx', // 配置响应结果列表字段
              total: returnType === 1 ? 'objx.total' : 'objx.length' // 配置响应结果总页数字段
            },
            ajax: {
              // 接收 Promise 对象
              query: ({page, sorts, filters, form}) => {
                if (!path) {
                  return;
                }

                let formData = tableOption.param ? tableOption.param() || {} : {};
                const queryParams = Object.assign({}, formData);
                if (isScriptEnabled) {
                  let condition = queryParams.condition
                  delete queryParams.condition;
                  delete queryParams.formCode;
                  Object.assign(queryParams, condition);
                }

                // 处理排序条件
                const firstSort = sorts[0];
                if (firstSort) {
                  queryParams.sort = firstSort.property;
                  queryParams.order = firstSort.order;
                }
                // 处理筛选条件
                filters.forEach(({property, values}) => {
                  queryParams[property] = values.join(",");
                });
                if (page.pageSize !== undefined) {
                  queryParams["size"] = `${page.pageSize}`;
                  queryParams["current"] = `${page.currentPage}`;
                }

                var $grid = this.$refs[tableRef];
                let isQueryAllPage = $grid.isQueryAllPage;
                let pathStr1 = "";
                if (isQueryAllPage === false) {
                  queryParams.searchCount = false;
                }

                var reqPath = typeof path == "function" ? path() : path;

                let toDo = (res) => {
                  let rows = res.objx ? res.objx.records || res.objx || [] : [];
                  if (tableOption.callback) {
                    that.$nextTick(() => {
                      setTimeout(function () {
                        tableOption.callback(rows);
                      }, 0);
                    });
                  }
                }

                return new Promise((resolve, reject) => {
                  if (isScriptEnabled) {
                    let option1 = this.$baseLodash.cloneDeep(optionModel);
                    option1.scriptUuid = scriptUuid;
                    option1.scriptUuid2 = scriptUuid2;
                    this.scriptHttp({
                      options: option1,
                      params: queryParams,
                      targetFormTemplate: this.targetFormTemplate,
                      isLoading: false,
                      callback: (res) => {
                        resolve(res);
                        if (res.type == "success") {
                          toDo(res);
                        }
                      }
                    });
                  } else {
                    that.$http({
                      url: reqPath,
                      method: "post",
                      data: queryParams,
                      callback: (res) => {
                        resolve(res);
                        if (res.type == "success") {
                          toDo(res);
                        }
                      },
                      error: (error) => {
                        reject(error);
                      },
                    });
                  }
                });
              }
            },
          }
        }
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        that.vxeOption = opts;
      });
    },
    async createColumns() {
      await this.getFormTemplate();
      await this.getListFields();

      let formField = this.formField;
      return this.tableColumns.map((row, index) => {
        let column = {
          title: row.label,
          field: row.prop,
          width: 150
        }
        if (index === 0) {
          column.fixed = 'left';
        }
        return column;
      })
    },
    async getListFields() {
      if (!this.formCode) return;
      return this.$http({
        url: USER_PREFIX + '/form_ins/getListFields',
        method: `post`,
        data: {stringOne: this.formCode},
        isLoading: true,
        loadingTarget: document.body,
        // modalStrictly: true,
        success: res => {
          let formInsListFieldDTOs = res.objx || [];
          this.formInsListField0DTOs = formInsListFieldDTOs.filter(item => item.fieldType === 0);
          this.formInsListField1DTOs = formInsListFieldDTOs.filter(item => item.fieldType === 1);

          if (!this.tableColumns.length) {
            this.tableColumns = this.formInsListField0DTOs.map(row => {
              return {
                label: row.fieldDesc,
                prop: row.fieldName,
                width: 150
              }
            });
          }
          if (!this.searchFields.length) {
            this.searchFields = this.formInsListField1DTOs.map(row => {
              return {
                label: row.fieldDesc,
                prop: row.fieldName
              }
            });
          }
        }
      });
    },
    async getFormTemplate() {
      let options = this.widget.options;
      let customGridConfig = options[this.filedKey] || {};
      this.customGridConfig = customGridConfig
      let searchField0s = customGridConfig && customGridConfig.searchFields ? customGridConfig.searchFields : [];
      let tableColumn0s = customGridConfig && customGridConfig.tableColumns ? customGridConfig.tableColumns : [];
      if (!this.formCode) {
        this.searchFields = searchField0s;
        this.tableColumns = tableColumn0s;
        this.tableConfig = customGridConfig;
        this.targetFormTemplate = null
        this.targetFormConfig = null;
        return;
      }
      return this.$http({
        url: USER_PREFIX + `/formTemplate/getByFormCode`,
        method: `post`,
        data: {
          stringOne: this.formCode
        },
        isLoading: true,
        loadingTarget: document.body,
        success: res => {
          let targetFormTemplate = res.objx || {};
          let formJson = targetFormTemplate.formViewContent ? JSON.parse(targetFormTemplate.formViewContent) : {};
          let formConfig = formJson.formConfig;
          this.targetFormTemplate = res.objx ? targetFormTemplate : null
          this.targetFormConfig = formConfig;

          let gridConfig = formConfig[this.filedKey] || {}

          let searchFields = gridConfig.searchFields || []
          let tableColumns = gridConfig.tableColumns || [];
          searchFields = searchFields.filter(item => {
            return !!item.prop && !!item.label;
          });
          this.tableColumns = tableColumns;
          this.searchFields = searchFields;

          let tableConfig = {};
          Object.assign(tableConfig, gridConfig, customGridConfig)
          this.tableConfig = tableConfig;
        }
      });
    },
    getCustomParam() {
      let tableConfig = this.tableConfig
      if (!!tableConfig.searchParams) {
        var e = new Function(tableConfig.searchParams);
        return e.call(this);
      }
    }
  }
}
</script>

<style scoped>

</style>
