
import Vue from 'vue'
import { onlAutoListMixin } from '@/mixins/OnlAutoListMixin';

import {getAction,postAction,deleteAction,downFile} from "@/api/manage";
import {filterObj} from "@/utils/util";
import {onlUtil} from '@/mixins/OnlineCommonUtil';
import CgformAutoListTable from '@/views/codegen/form/auto/common/CgformAutoListTable';
import CgformAutoListButtons from '@/views/codegen/form/auto/common/CgformAutoListButtons';
import CgformAutoListQueryParams from '@/views/codegen/form/auto/common/CgformAutoListQueryParams';

export const CgformAutoListMixins = {
  mixins : [onlUtil, onlAutoListMixin],
  provide : function() {
    return {
      loadData : this.loadData,
      handleAdd : this.handleAdd,
      handleEdit : this.handleEdit,
      handleDetail : this.handleDetail,
      handleDelBatch : this.handleDelBatch,
      handleDeleteOne : this.handleDeleteOne,
      handleImportXls : this.handleImportXls,
      handleExportXls : this.handleExportXls,
      cgButtonJsHandler : this.cgButtonJsHandler,
      cgButtonLinkHandler : this.cgButtonLinkHandler,
      cgButtonActionHandler : this.cgButtonActionHandler,
      onClearSelected : this.onClearSelected,
      handleSuperQuery : this.handleSuperQuery,
      handleSearchQuery : this.handleSearchQuery,
      handleSearchReset : this.handleSearchReset
    };
  },
  components : {
    CgformAutoListTable : CgformAutoListTable,
    CgformAutoListButtons : CgformAutoListButtons,
    CgformAutoListQueryParams : CgformAutoListQueryParams
  },
  data : function() {
    return {
      code : "",
      schema : {},
      queryParamsMap : {},
      dictOptions : {},
      cgButtonList : [],
      cgButtonLinkList : [],
      hasBpmStatus : false,
      superQuery : {
        fieldList : [],
        params : "",
        matchType : "and"
      },
      table : {
        loading : true,
        scroll : {
          x : false
        },
        columns : [],
        dataSource : [],
        selectedRowKeys : [],
        selectionRows : [],
        pagination : {}
      },
      isorter : {
        column : "id",
        order : "desc"
      },
      metaPagination : {
        current : 1,
        pageSize : 10,
        pageSizeOptions : ["10", "20", "30"],
        showTotal : function(shipping, items) {
          return items[0] + "-" + items[1] + " 共" + shipping + "条";
        },
        showQuickJumper : true,
        showSizeChanger : true,
        total : 0
      },
      actionColumn : {
        title : "操作",
        dataIndex : "action",
        scopedSlots : {
          customRender : "action"
        },
        align : "center",
        width : 150
      },
      checkboxFlag : false,
      scrollFlag : 0,
      buttonSwitch : {
        add : true,
        update : true,
        delete : true,
        batch_delete : true,
        import : true,
        export : true,
        detail : true,
        super_query : true,
        bpm : true
      },
      EnhanceJS : "",
      formTemplate : "99",
      currentTableName : "",
      settingColumns : [],
      acceptHrefParams : {}
    };
  },
  computed : {
    queryParam : {
      get : function() {
        return this.queryParamsMap[this.code];
      },
      set : function(data) {
        this.$set(this.queryParamsMap, this.code, data);
      }
    },
    url : function() {
      let base = "/online/cgform/api";
      return {
        getColumns : base.concat("/getColumns/", this.code),
        getData : base.concat("/getData/", this.code),
        optPre : base.concat("/form/", this.code, "/"),
        exportXls : base.concat("/exportXls/"),
        buttonAction : base.concat("/doButton"),
        startProcess : "/act/process/extActProcess/startMutilProcess",
        getQueryInfo : base.concat("/getQueryInfo/", this.code),
        importUrl : base.concat("/importXls/", this.code)
      };
    },
    localCode : function() {
      return "onl_" + this.currentTableName;
    }
  },
  watch : {
    $route : {
      deep : true,
      immediate : true,
      handler : function() {
        this.initialAutoList();
      }
    }
  },
  mounted : function() {
    this.cgButtonJsHandler("mounted");
  },
  methods : {
    initialAutoList : function() {
      if (this.code = this.$route.params.code, !this.code) {
        return false;
      }
      if (!this.queryParam) {
        this.queryParam = {};
      }
      this.superQuery.params = "";
      if (this.$refs.superQuery) {
        this.$refs.superQuery.handleOutReset(false);
      }
      this.handleAcceptHrefParams();
      this.loadAll();
    },
    handleAcceptHrefParams : function() {
      let settings = this;
      this.acceptHrefParams = {};
      let params = this.$route.query;
      if (params) {
        this.acceptHrefParams = Object.assign({}, params);
        Object.keys(params).map(function(name) {
          settings.queryParam[name] = params[name];
        });
      }
    },
    loadAll : function() {

      this.table.loading = true;
      this.loadColumns(false, errorCallback);
      this.loadData(1, false, errorCallback);
      /**
       * @param {?} callback
       * @return {?}
       */
      function getArticleMeta(callback) {
        return _ref4.apply(this, arguments);
      }
      var _ref4 = _asyncToGenerator$jscomp$0(G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.mark(function init(errorCallback) {
        return G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.wrap(function(context$5$0) {
          for (; 1;) {
            switch(context$5$0.prev = context$5$0.next) {
              case 0:
                return this.table.loading = true, context$5$0.next = 3, this.loadColumns(false, errorCallback);
              case 3:
                return context$5$0.next = 5, this.loadData(1, false, errorCallback);
              case 5:
                /** @type {boolean} */
                this.table.loading = false;
              case 6:
              case "end":
                return context$5$0.stop();
            }
          }
        }, init, this);
      }));
      return getArticleMeta;
    }(),
    loadData : function() {
      /**
       * @return {?}
       */
      function ItemLabelView() {
        return _ref4.apply(this, arguments);
      }
      var _ref4 = _asyncToGenerator$jscomp$0(G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.mark(function update() {
        var t;
        var n;
        var data;
        var p;
        var self = this;
        /** @type {!Arguments} */
        var fixtureUrls = arguments;
        return G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.wrap(function(_context) {
          for (; 1;) {
            switch(_context.prev = _context.next) {
              case 0:
                return fixtureUrls.length > 0 && void 0 !== fixtureUrls[0] ? fixtureUrls[0] : 1,
                  t = !(fixtureUrls.length > 1 && void 0 !== fixtureUrls[1]) || fixtureUrls[1],
                  n = fixtureUrls.length > 2 ? fixtureUrls[2] : void 0,
                  data = this.getQueryParams(),
                  this.table.pagination ? this.table.pagination.current = data.pageNo : data["pageSize"] = -521,
                n && (data["tabletype"] = n),
                t && (this.table.loading = true),
                  p = Object(_api_manage__WEBPACK_IMPORTED_MODULE_2__$jscomp$0["c"])(this.url.getData,
                  data), p.then(function(response) {
                  if (response.success) {
                    var result = response.result;
                    if (self.table.pagination) {
                      if (Number(result.total) > 0) {
                        self.table.pagination.total = Number(result.total);
                        self.table.dataSource = result.records;
                      } else {
                        self.table.pagination.total = 0;
                        self.table.dataSource = [];
                      }
                    } else {
                      self.table.dataSource = result.records ? result.records : [];
                    }
                  } else {
                    self.$message.warning(response.message);
                  }
                }), t && p.finally(function() {
                  /** @type {boolean} */
                  self.table.loading = false;
                }), _context.abrupt("return", p);
              case 11:
              case "end":
                return _context.stop();
            }
          }
        }, update, this);
      }));
      return ItemLabelView;
    }(),
    loadColumns : function() {
      /**
       * @return {?}
       */
      function ItemLabelView() {
        return _ref4.apply(this, arguments);
      }
      var _ref4 = _asyncToGenerator$jscomp$0(G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.mark(function update() {
        var jdx;
        var cnt;
        var keepLayersOrder;
        var r;
        var that = this;
        /** @type {!Arguments} */
        var fixtureUrls = arguments;
        return G_jeecgboot_shangye_make_jeecgboot3_1_0_20220223_os_antd_jeecg_vue_os_onlinelib_3_1_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default$jscomp$0.a.wrap(function(_context) {
          for (; 1;) {
            switch(_context.prev = _context.next) {
              case 0:
                return jdx = !(fixtureUrls.length > 0 && void 0 !== fixtureUrls[0]) || fixtureUrls[0], cnt = fixtureUrls.length > 1 && void 0 !== fixtureUrls[1] ? fixtureUrls[1] : "", jdx && (this.table.loading = true), keepLayersOrder = {
                  tabletype : cnt
                }, r = Object(_api_manage__WEBPACK_IMPORTED_MODULE_2__$jscomp$0["c"])(this.url.getColumns, keepLayersOrder), r.then(function(response) {
                  if (response.success) {
                    var options = response.result;
                    var body = options.checkboxFlag;
                    var includerReg = options.paginationFlag;
                    var r = options.fieldHrefSlots;
                    var o = options.dictOptions;
                    var template = options.formTemplate;
                    var a = response.result;
                    var l = a.currentTableName;
                    var x = a.cgButtonList;
                    var xf = a.enhanceJs;
                    var h = a.hideColumns;
                    var c = a.columns;
                    var f = a.scrollFlag;
                    var content = a.description;
                    /** @type {boolean} */
                    that.checkboxFlag = "Y" === body;
                    that.table.pagination = "Y" === includerReg && _objectSpread$jscomp$0({}, that.metaPagination);
                    that.scrollFlag = f;
                    that.dictOptions = o;
                    that.description = content;
                    that.formTemplate = template;
                    that.currentTableName = l;
                    that.initCgEnhanceJs(xf);
                    that.initButtonSwitch(h);
                    that.initialCgButtonList(x);
                    var window = {};
                    r.forEach(function(object) {
                      return window[object.slotName] = object;
                    });
                    c.forEach(function(e) {
                      Object.keys(e).map(function(childProp) {
                        if (null == e[childProp]) {
                          delete e[childProp];
                        }
                      });
                      that.handleColumnHrefAndDict(e, window);
                      that.handleColumnShowLength(e);
                    });
                    if (3 == response.result.tableType) {
                      that.table.columns = _toConsumableArray$jscomp$0(c);
                    } else {
                      that.table.columns = c.concat([that.actionColumn]);
                    }
                    that.settingColumnsHandler(that.table.columns);
                    /** @type {!Array} */
                    that.table.selectedRowKeys = [];
                    that.hasBpmStatus = c.map(function(rowInfo) {
                      return (rowInfo.dataIndex || "").toLowerCase();
                    }).includes("bpm_status");
                  } else {
                    that.$message.warning(response.message);
                  }
                }), jdx && r.finally(function() {
                  /** @type {boolean} */
                  that.table.loading = false;
                }), _context.abrupt("return", r);
              case 8:
              case "end":
                return _context.stop();
            }
          }
        }, update, this);
      }));
      return ItemLabelView;
    }(),
    getQueryParams : function() {
      let params = Object.assign({}, this.queryParam, this.isorter);
      params.pageNo = this.table.pagination.current
      params.pageSize = this.table.pagination.pageSize
      params.superQueryMatchType = this.superQuery.matchType
      params.superQueryParams = encodeURIComponent(this.superQuery.params)
      return filterObj(params);
    },
    initialCgButtonList : function(buttionList) {
      let self = this;
      this.cgButtonList = [];
      this.cgButtonLinkList = [];
      if (buttionList) {
        buttionList.forEach(function(button) {
          if ("button" === button.buttonStyle) {
            self.cgButtonList.push(button);
          } else {
            if ("link" === button.buttonStyle) {
              self.cgButtonLinkList.push(button);
            }
          }
        });
      }
    },
    handleAdd : function() {
      this.cgButtonJsHandler("beforeAdd");
      this.$refs.modal.add(this.formTemplate);
    },
    handleEdit : function(data) {
      let self = this;
      this.beforeEdit(data).then(function() {
        self.$refs.modal.edit(self.formTemplate, data.id);
      }).catch(function(reason) {
        self.$message.warning(reason);
      });
    },
    beforeEdit : function(data) {
      return this.EnhanceJS["beforeEdit"] ? this.EnhanceJS["beforeEdit"](this, data) : Promise.resolve();
    },
    handleDetail : function(result) {
      this.$refs.modal.detail(this.formTemplate, result.id);
    },
    handleDelete : function(id) {
      let self = this;
      deleteAction(this.url.optPre + id).then(function(data) {
        if (data.success) {
          self.$message.success(data.message);
          self.loadData();
        } else {
          self.$message.warning(data.message);
        }
      });
    },
    handleDeleteOne : function(record) {
      let self = this;
      this.beforeDelete(record).then(function() {
        self.handleDelete(record.id);
      }).catch(function(reason) {
        self.$message.warning(reason);
      });
    },
    beforeDelete : function(callback) {
      return this.EnhanceJS["beforeDelete"] ? this.EnhanceJS["beforeDelete"](this, callback) : Promise.resolve();
    },
    handleGetSchema : function(obj) {
      let self = this;
      this.schema = obj;
      if (obj && obj.properties) {
        (function() {
          /**
           * @param {!Array} target
           * @param {!Object} data
           * @return {undefined}
           */
          var render = function(target, data) {
            var type = data.view || data.type || "string";
            type = "inputNumber" === type ? "number" : type;
            var result = {
              type : type,
              value : data.key,
              text : data.title,
              dictCode : data.dictCode,
              dictTable : data.dictTable,
              dictText : data.dictText,
              options : data.enum || data.options,
              order : data.order
            };
            if ("popup" === type) {
              result["popup"] = {
                code : data.popupCode || data.code,
                field : data.orgFields.split(",")[0],
                orgFields : data.orgFields.split(",")[0],
                destFields : data.destFields.split(",")[0]
              };
            }
            target.push(result);
          };
          /** @type {!Array} */
          var obj = [];
          /**
           * @param {string} prop
           * @return {?}
           */
          var init = function(prop) {
            if (!obj.properties.hasOwnProperty(prop)) {
              return "continue";
            }
            var action = obj.properties[prop];
            if ("tab" === action.view && 0 == action.relationType) {
              var data = {
                type : "sub-table",
                value : action.key,
                text : action.describe,
                children : []
              };
              if (action.columns) {
                var iterResult;
                var ret = _createForOfIteratorHelper$jscomp$0(action.columns);
                try {
                  ret.s();
                  for (; !(iterResult = ret.n()).done;) {
                    var res = iterResult.value;
                    render(data.children, res);
                  }
                } catch (ratio) {
                  ret.e(ratio);
                } finally {
                  ret.f();
                }
              }
              obj.push(data);
            } else {
              if ("tab" === action.view && 1 == action.relationType) {
                var data = {
                  type : "sub-table",
                  value : action.key,
                  text : action.describe,
                  children : []
                };
                Object.keys(action.properties).map(function(i) {
                  /** @type {string} */
                  action.properties[i]["key"] = i;
                  render(data.children, action.properties[i]);
                });
                obj.push(data);
              } else {
                /** @type {string} */
                action.key = prop;
                render(obj, action);
              }
            }
          };
          var i;
          for (i in obj.properties) {
            init(i);
          }
          /** @type {number} */
          var index = 0;
          for (; index < obj.length; index++) {
            /** @type {number} */
            var i = index + 1;
            for (; i < obj.length; i++) {
              var a = obj[index];
              var b = obj[i];
              if (a.order > b.order) {
                obj[index] = b;
                obj[i] = a;
              }
            }
          }
          /** @type {!Array} */
          self.superQuery.fieldList = obj;
        })();
      }
    },
    handleFormSuccess : function() {
      this.loadData();
    },
    handleImportXls : function() {
      if (this.$refs.importModal) {
        this.$refs.importModal.show();
      } else {
        if (this.$refs.autoListTable) {
          this.$refs.autoListTable.$refs.importModal.show();
        } else {
          this.$message.warn("未找到导入窗口");
        }
      }
    },
    handleExportXls : function() {
      var _this = this;
      var apidocData = this.queryParam;
      if (this.table.selectedRowKeys && this.table.selectedRowKeys.length > 0) {
        apidocData["selections"] = this.table.selectedRowKeys.join(",");
      }
      /** @type {string} */
      var paramsStr = JSON.stringify(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__$jscomp$0["a"])(apidocData));
      Object(_api_manage__WEBPACK_IMPORTED_MODULE_2__$jscomp$0["b"])(this.url.exportXls + this.code, {
        paramsStr : paramsStr
      }).then(function(torrent) {
        if (torrent && 0 !== torrent.size) {
          if ("undefined" !== typeof window.navigator.msSaveBlob) {
            window.navigator.msSaveBlob(new Blob([torrent]), _this.description + ".xls");
          } else {
            var uriContent = window.URL.createObjectURL(new Blob([torrent]));
            /** @type {!Element} */
            var a = document.createElement("a");
            /** @type {string} */
            a.style.display = "none";
            a.href = uriContent;
            a.setAttribute("download", _this.description + ".xls");
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(uriContent);
          }
        } else {
          _this.$message.warning("文件下载失败");
        }
      });
    },
    cgButtonJsHandler : function(name) {
      if (this.EnhanceJS[name]) {
        this.EnhanceJS[name](this);
      }
    },
    handleSuperQuery : function(query, type, default_alpha) {
      if (query && 0 !== query.length) {
        this.superQuery.params = JSON.stringify(query);
      } else {
        this.superQuery.params = "";
      }
      this.superQuery.matchType = type;
      if (default_alpha === 1) {
        this.loadData(1);
      }
    },
    handleSearchQuery : function() {
      this.loadData(1);
    },
    handleSearchReset : function() {
      let self = this;
      this.queryParam = {};
      if (this.acceptHrefParams) {
        Object.keys(this.acceptHrefParams).map(function(name) {
          self.queryParam[name] = self.acceptHrefParams[name];
        });
      }
      this.loadData(1);
    },
    initButtonSwitch : function(hash) {
      let self = this;
      Object.keys(this.buttonSwitch).forEach(function(topo_objectName) {
        self.buttonSwitch[topo_objectName] = true;
      });
      if (hash && hash.length > 0) {
        Object.keys(this.buttonSwitch).forEach(function(n) {
          if (hash.indexOf(n) >= 0) {
            self.buttonSwitch[n] = false;
          }
        });
      }
    },
    initCgEnhanceJs(enhanceJsCode) {
      if (enhanceJsCode) {
        try {
          let enhanceJsFunction = eval("(" + enhanceJsCode + ")");
          this.EnhanceJS = new enhanceJsFunction(getAction, postAction, deleteAction);
          this.cgButtonJsHandler("created");
        } catch (e) {
          this.EnhanceJS = "";
          this.$message.warning("JS增强异常,请检查list配置!");
        }
      } else {
        this.EnhanceJS = "";
      }
    },
    cgButtonLinkHandler : function(obj, event, name) {
      let self = this;
      if ("js" === name) {
        if (this.EnhanceJS[event]) {
          this.EnhanceJS[event](this, obj);
        }
      } else {
        if ("action" === name) {
          let defaults = {
            formId : this.code,
            buttonCode : event,
            dataId : obj.id
          };
          postAction(this.url.buttonAction, defaults).then(function(data) {
            if (data.success) {
              self.loadData();
              self.$message.success("处理完成!");
            } else {
              self.$message.warning(data.message);
            }
          });
        }
      }
    },
    cgButtonActionHandler : function(buttonCode) {
      let self = this;
      if (!this.table.selectedRowKeys || 0 === this.table.selectedRowKeys.length) {
        return this.$message.warning("请先选中一条记录"), false;
      }
      let dataId = this.table.selectedRowKeys.join(",");
      let params = {
        formId : this.code,
        buttonCode : buttonCode,
        dataId : dataId
      };
      postAction(this.url.buttonAction, params).then(function(data) {
        if (data.success) {
          self.loadData();
          self.$message.success("处理完成!");
        } else {
          self.$message.warning(data.message);
        }
      });
    },
    onClearSelected : function() {
      this.table.selectedRowKeys = [];
      this.table.selectionRows = [];
    },
    handleDelBatch : function() {
      let self = this;
      if (this.table.selectedRowKeys.length <= 0) {
        return this.$message.warning("请选择一条记录！"), false;
      }
      this.$confirm({
        title : "确认删除",
        content : "是否删除选中数据？",
        onOk : function() {
          let message = self.table.selectedRowKeys.join(",");
          self.handleDelete(message);
          self.onClearSelected();
        }
      });
    },
    settingColumnsHandler : function(rowsArr) {
      let self = this;
      let columnsStr = Vue.ls.get(this.localCode);
      if (columnsStr && columnsStr.length !== 0) {
        this.settingColumns = columnsStr.split(",");
      } else {
        /** @type {!Array} */
        this.settingColumns = [];
        rowsArr.forEach(function(cell) {
          if (self.settingColumns.indexOf(cell["dataIndex"]) < 0) {
            self.settingColumns.push(cell["dataIndex"]);
          }
        });
      }
    }
  }
}