import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import { getRegionTreeData, cloneDeep } from './common';
import Toast from '../toast';
import mixins from './mixins';

var __vue_render__ = function __vue_render__() {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c('div', {
    ref: "addressBox",
    staticClass: "ks-area-picker"
  }, [_c('div', {
    staticClass: "ks-area-picker-container"
  }, [_c('ks-swipe', {
    ref: "areaSwipeRef",
    staticClass: "area-picker-swipe",
    attrs: {
      "loop": false,
      "width": _vm.swipeWidth,
      "show-indicators": false
    },
    on: {
      "change": _vm.onSwipeChange
    }
  }, _vm._l(_vm.levelOptions, function (zoomItem, zoomIndex) {
    return _c('ks-swipe-item', {
      key: zoomIndex,
      staticClass: "area-swipe-item"
    }, [_c('div', {
      class: ["area-list area-list-" + zoomIndex]
    }, [_c('div', {
      class: ['area-list-title', {
        'select-color': _vm.selectData[zoomIndex].length > 0
      }]
    }, [_vm._v(_vm._s(zoomItem.name))]), _vm._v(" "), _c('div', {
      staticClass: "area-list-content"
    }, _vm._l(_vm.selectData[zoomIndex], function (v) {
      return _c('div', {
        directives: [{
          name: "show",
          rawName: "v-show",
          value: v.index > 0 || !zoomItem.allSelectDisabled,
          expression: "v.index > 0 || !zoomItem.allSelectDisabled"
        }],
        key: v.districtID,
        class: ['list-item', "list-item-" + v.index, {
          'is-choose': v.isChoose,
          'read-only': _vm.readOnly
        }]
      }, [_c('div', {
        staticClass: "item-choose",
        on: {
          "click": function click($event) {
            return _vm.showChildren(v, v.index, zoomIndex, false, true);
          }
        }
      }, [_c('div', {
        staticClass: "address-name",
        attrs: {
          "title": v.districtName
        }
      }, [_vm._v(_vm._s(v.simpleName || v.districtName))]), _vm._v(" "), !zoomItem.disabled ? _c('i', {
        staticClass: "checkbox-item",
        class: {
          'partial-checked': v.isIndeterminate,
          'no-checked': !v.isChecked,
          'all-checked': v.isChecked
        },
        on: {
          "click": function click($event) {
            $event.stopPropagation();
            return _vm.checkboxClick(v, v.index, zoomIndex);
          }
        }
      }) : _vm._e()])]);
    }), 0)])]);
  }), 1)], 1)]);
};

var __vue_staticRenderFns__ = [];
export default {
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__,
  name: 'area-picker',
  props: {
    // 下拉搜索前的事件fetch
    beforeSearch: {
      type: Function
    },
    level: {
      type: Number
    },
    // 添加区域前的事件fetch
    beforeAdd: {
      type: Function
    }
  },
  mixins: [mixins],
  computed: {
    maxlength: function maxlength() {
      return this.$parent.maxlength;
    },
    readOnly: function readOnly() {
      return this.$parent.readOnly;
    },
    areaData: function areaData() {
      return this.$parent.areaData;
    },
    checkedData: function checkedData() {
      return this.$parent.checkedData;
    },
    idMap: function idMap() {
      return this.$parent.idMap;
    },
    isArea: function isArea() {
      return this.$parent.isArea;
    },
    levelOptions: function levelOptions() {
      return this.$parent.levelOptions;
    }
  },
  watch: {
    areaData: function areaData(val) {
      var _this = this;

      if (this.setDataTimer) {
        clearTimeout(this.setDataTimer);
        this.setDataTimer = null;
      }

      this.setDataTimer = setTimeout(function () {
        _this.clearAll();

        if (val) {
          _this.showHistoryDataChecked(cloneDeep(_this.areaData || []));
        }
      }, 100);
    }
  },
  data: function data() {
    // const level = this.titles.length
    return {
      currentSwipeIndex: 0,
      swipeWidth: this.level > 2 ? document.body.clientWidth / 3 : document.body.clientWidth / 2,
      areaTree: getRegionTreeData(this.isArea),
      checkedListData: [],
      selectData: new Array(this.level).fill([]),
      lastCheckedData: []
    };
  },
  mounted: function mounted() {
    var _this2 = this;

    return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return _this2.getAreaData();

            case 2:
              if (_this2.areaData && _this2.areaData.length) {
                _this2.showHistoryDataChecked(cloneDeep(_this2.areaData || []));
              }

            case 3:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }))();
  },
  methods: {
    onSwipeChange: function onSwipeChange(index) {
      this.currentSwipeIndex = index;
    },
    switchSwipeIndex: function switchSwipeIndex(zoomIndex) {
      if (this.level > 3) {
        var diffOffset = zoomIndex - this.currentSwipeIndex;

        if (diffOffset === 2 && zoomIndex > 1 && zoomIndex < this.level - 1) {
          this.$refs.areaSwipeRef.next();
        }

        if (diffOffset === 0 && zoomIndex > 0) {
          this.$refs.areaSwipeRef.prev();
        }
      }
    },
    checkboxClick: function checkboxClick(item, vIndex, zoomIndex) {
      var _this3 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var oldChecked;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this3.switchSwipeIndex(zoomIndex);

                if (!_this3.readOnly) {
                  _context2.next = 3;
                  break;
                }

                return _context2.abrupt("return");

              case 3:
                if (!(vIndex === 0 && zoomIndex === 0)) {
                  _context2.next = 9;
                  break;
                }

                oldChecked = item.isChecked;

                _this3.clearAll();

                item.isChecked = !oldChecked;
                item.isIndeterminate = false;
                return _context2.abrupt("return");

              case 9:
                if (!(!item.isChecked || item.isIndeterminate)) {
                  _context2.next = 15;
                  break;
                }

                item.isChecked = true;
                item.isIndeterminate = false;
                _context2.next = 14;
                return _this3.changeCheckBox(true, item, vIndex, zoomIndex, true);

              case 14:
                return _context2.abrupt("return");

              case 15:
                item.isChecked = false;
                item.isIndeterminate = false;
                _context2.next = 19;
                return _this3.changeCheckBox(false, item, vIndex, zoomIndex);

              case 19:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))();
    },
    getAreaData: function getAreaData() {
      var _this4 = this;

      var areaList = this.areaTree.childrenNode;
      var childrenData = [this.areaTree].concat(areaList);
      this.$parent.idMap = new Map();
      this.idMap.set(this.areaTree.districtID, this.areaTree);
      this.$set(this.selectData, [0], childrenData);
      areaList.map(function (item) {
        item._parent = _this4.areaTree;

        _this4.idMap.set(item.districtID, item);
      });
    },
    isMaxLength: function isMaxLength() {
      if (this.maxlength) {
        if (this.checkedData.length >= this.maxlength) {
          Toast("\u6700\u591A\u9009\u62E9" + this.maxlength + "\u4E2A\u5730\u533A");
          return true;
        }

        return false;
      }

      return false;
    },
    // 回写数据到连级菜单中
    showHistoryDataChecked: function showHistoryDataChecked(val) {
      var _this5 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        var idArry, rootDisabled, _loop, i;

        return _regeneratorRuntime.wrap(function _callee3$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                idArry = []; // 过滤已有数据查询

                rootDisabled = _this5.levelOptions[0].disabled;
                _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop(i) {
                  var item, mapItem;
                  return _regeneratorRuntime.wrap(function _loop$(_context3) {
                    while (1) {
                      switch (_context3.prev = _context3.next) {
                        case 0:
                          item = val[i];
                          mapItem = _this5.idMap.get(item.districtID);

                          if (mapItem) {
                            _context3.next = 6;
                            break;
                          }

                          idArry.push(item.districtID);
                          _context3.next = 12;
                          break;

                        case 6:
                          if (!(mapItem && mapItem._erpZoom === 0 && !rootDisabled)) {
                            _context3.next = 12;
                            break;
                          }

                          if (mapItem.isChecked) {
                            _context3.next = 11;
                            break;
                          }

                          if (_this5.checkedData.some(function (v) {
                            return v.districtID === mapItem.districtID;
                          })) {
                            _context3.next = 11;
                            break;
                          }

                          _context3.next = 11;
                          return _this5.checkboxClick(mapItem, mapItem.index, 0);

                        case 11:
                          val.splice(i, 1);

                        case 12:
                        case "end":
                          return _context3.stop();
                      }
                    }
                  }, _loop);
                });
                i = val.length - 1;

              case 4:
                if (!(i >= 0)) {
                  _context4.next = 9;
                  break;
                }

                return _context4.delegateYield(_loop(i), "t0", 6);

              case 6:
                i--;
                _context4.next = 4;
                break;

              case 9:
                _context4.next = 11;
                return _this5.getAreaLinkData(idArry, _this5.idMap, _this5.areaTree);

              case 11:
                val && val.map(function (item, itemIndex) {
                  var checkedItem = _this5.idMap.get(item.districtID);

                  if (checkedItem) {
                    _this5.changeCheckBox(true, checkedItem, 1);

                    if (itemIndex === val.length - 1) {
                      _this5.openAddressLink(checkedItem, _this5.selectData);

                      for (var _i = checkedItem._erpZoom + 1; _i < _this5.level; _i++) {
                        var childNode = _this5.selectData[_i];
                        childNode && childNode.length && childNode.forEach(function (node) {
                          node.isChoose = false;
                        });

                        if (checkedItem._erpZoom === _i - 1 && checkedItem.childrenNode && checkedItem.childrenNode.length) {
                          _this5.$set(_this5.selectData, [_i], [].concat(checkedItem.childrenNode));
                        } else {
                          _this5.$set(_this5.selectData, [_i], []);
                        }
                      }
                    }
                  } else {
                    // 不存在的情况需要获取上级链路数据
                    _this5.checkedData.push(item);
                  }
                }); // setTimeout(() => {
                //   const nodes = Array.from(this.$refs.addressBox.querySelectorAll('.is-choose'))
                //   const length = nodes && nodes.length
                //   if (length) {
                //     nodes.reverse().forEach(node => node.scrollIntoView({ block: 'center', inline: 'center' }))
                //     if (length > 3) {
                //       this.$refs.areaSwipeRef.next()
                //     } else {
                //       if (this.currentSwipeIndex) {
                //         this.$refs.areaSwipeRef.prev()
                //       }
                //     }
                //   }
                // }, 200)

              case 12:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee3);
      }))();
    },
    // 递归打开最后一个城市
    showChildren: function showChildren(v, index, key, rootChecked, isClick) {
      var _this6 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
        var i, childNode, data, childrenData, _i2, _childNode;

        return _regeneratorRuntime.wrap(function _callee4$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                if (!(key === _this6.level - 1)) {
                  _context5.next = 3;
                  break;
                }

                _this6.checkboxClick(v, index, key);

                return _context5.abrupt("return");

              case 3:
                isClick && _this6.switchSwipeIndex(key);

                if (!(key >= _this6.level - 1)) {
                  _context5.next = 6;
                  break;
                }

                return _context5.abrupt("return");

              case 6:
                if (!(index === 0 && key === 0)) {
                  _context5.next = 10;
                  break;
                }

                for (i = key + 1; i < _this6.level; i++) {
                  childNode = _this6.selectData[i];
                  childNode && childNode.length && childNode.forEach(function (node) {
                    node.isChoose = false;
                  });

                  _this6.$set(_this6.selectData, [i], []);
                }

                v.childrenNode.map(function (k) {
                  k.isChoose = false;
                });
                return _context5.abrupt("return", false);

              case 10:
                v._parent && v._parent.childrenNode.map(function (k) {
                  k.isChoose = false;
                });
                v.isChoose = true;

                if (!(v.childrenNode && v.childrenNode.length)) {
                  _context5.next = 16;
                  break;
                }

                data = v.childrenNode;
                _context5.next = 19;
                break;

              case 16:
                _context5.next = 18;
                return _this6.getAreaChildren(_this6.idMap, v, key + 1, rootChecked);

              case 18:
                data = _context5.sent;

              case 19:
                childrenData = index === 0 ? [] : data;

                for (_i2 = key + 1; _i2 < _this6.level; _i2++) {
                  _childNode = _this6.selectData[_i2];
                  _childNode && _childNode.length && _childNode.forEach(function (node) {
                    node.isChoose = false;
                  });
                  _this6.selectData[_i2] = [];
                }

                _this6.$set(_this6.selectData, [key + 1], childrenData);

              case 22:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee4);
      }))();
    },
    // tag删除操作
    deleteName: function deleteName(item) {
      // 选择联动地区移除
      var indexKey = this.selectData[item._erpZoom].indexOf(item);

      item.isChecked = false;
      this.changeCheckBox(false, item, indexKey, item._erpZoom);
    },
    // 删除所有操作
    clearAll: function clearAll() {
      this.checkedListData = [];
      this.$parent.checkedData = [];
      this.selectData = new Array(this.level).fill([]);
      var areaList = this.areaTree.childrenNode;
      var childrenData = [this.areaTree].concat(areaList);
      this.$set(this.selectData, [0], childrenData);
      this.clearStatus(this.areaTree);

      if (this.currentSwipeIndex) {
        this.$refs.areaSwipeRef.prev();
      }
    },
    // 连级特殊处理
    specialSet: function specialSet(item, itemIndex, type) {
      if (item.districtID !== 'all') {
        this.areaTree.isChecked = false;
      }

      if (itemIndex === 0) {
        if (item._parent) {
          item._parent.isChecked = true;
          item._parent.isIndeterminate = false;
        }
      } else {
        if (item.childrenNode) {
          item.childrenNode[0] && (item.childrenNode[0].isChecked = type);
        }
      }
    },
    // 连级勾选handler
    changeCheckBox: function changeCheckBox(type, item, itemIndex, key, rootChecked) {
      var _this7 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
        var isMax, repeatItem;
        return _regeneratorRuntime.wrap(function _callee5$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.prev = 0;

                if (!type) {
                  _context6.next = 13;
                  break;
                }

                if (!(item.districtID !== 'all')) {
                  _context6.next = 7;
                  break;
                }

                isMax = _this7.isMaxLength();

                if (!isMax) {
                  _context6.next = 7;
                  break;
                }

                item.isChecked = false;
                return _context6.abrupt("return", false);

              case 7:
                _context6.next = 9;
                return _this7.checkoutBeforeAdd(item, true);

              case 9:
                repeatItem = _this7.getRepeat(item, true);

                if (!repeatItem) {
                  _context6.next = 13;
                  break;
                }

                item.isChecked = false;
                return _context6.abrupt("return");

              case 13:
                // step1 递归清除当前节点子集中的所有选中数据
                _this7.clearChildren(item); // step2 展示下级(同步获取接口数据)


                _context6.t0 = type && !isNaN(key);

                if (!_context6.t0) {
                  _context6.next = 18;
                  break;
                }

                _context6.next = 18;
                return _this7.showChildren(item, itemIndex, Number(key), rootChecked);

              case 18:
                // step3 同级展示操作
                _this7.setPeer(item, itemIndex, type); // step4 特殊情况处理


                _this7.specialSet(item, itemIndex, type); // step5 递归设置上层节点展示状态


                _this7.setFather(item);

                _this7.lastCheckedData = cloneDeep(_this7.checkedListData);
                _this7.checkedListData = []; // step6 获取tree数据中被选中的数据

                _this7.getChecked(_this7.areaTree); // step7 push或者delete数据


                _this7.getAddOrDeleteItems(type);

                _context6.next = 29;
                break;

              case 27:
                _context6.prev = 27;
                _context6.t1 = _context6["catch"](0);

              case 29:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee5, null, [[0, 27]]);
      }))();
    },
    // 对比上次的数据判断新增或删除的数据
    getAddOrDeleteItems: function getAddOrDeleteItems() {
      var _this8 = this;

      this.checkedListData.map(function (item) {
        var sameItem = _this8.lastCheckedData.find(function (key) {
          return key.districtID === item.districtID;
        });

        if (!sameItem) {
          _this8.checkedData.push(item);
        }
      });
      this.lastCheckedData.map(function (item) {
        var sameItem = _this8.checkedListData.find(function (key) {
          return key.districtID === item.districtID;
        });

        if (!sameItem) {
          var index = _this8.checkedData.findIndex(function (v) {
            return v.districtID === item.districtID;
          });

          if (index >= 0) {
            _this8.checkedData.splice(index, 1);
          }
        }
      });
    },
    // 获取连级数据中被选中的值
    getChecked: function getChecked(item) {
      var _this9 = this;

      // 选中全国
      if (item.districtID === 'all' && item.isChecked) {
        this.clearAll();
        item.isChecked = true;
        this.checkedListData.push(item);
        return;
      }

      item.childrenNode && item.childrenNode.map(function (v, vIndex) {
        if (v.isChecked || v.isChoose || v.isIndeterminate) {
          if (v._erpZoom === 0) {
            if (v.isChecked) {
              var isAllChecked = v.childrenNode && v.childrenNode.length && v.childrenNode[0].isChecked;
              isAllChecked && _this9.checkedListData.push(v);
            }

            _this9.getChecked(v);
          } else {
            if (vIndex !== 0) {
              if (v.isChecked) {
                if (v.childrenNode && v.childrenNode.length) {
                  var _isAllChecked = v.childrenNode[0].isChecked;
                  _isAllChecked && _this9.checkedListData.push(v);
                } else {
                  _this9.checkedListData.push(v);
                }
              }

              _this9.getChecked(v);
            }
          }
        }
      });
    },
    // 获取重复item
    getRepeat: function getRepeat(item) {
      return this.checkedData.find(function (v) {
        return v.districtID === item.districtID;
      });
    },
    // 取消联级菜单的全国勾选
    cancelCheckedAll: function cancelCheckedAll() {
      if (this.areaTree.isChecked) {
        // 全国被选中去掉勾选，去除勾选数据
        this.areaTree.isChecked = false;
        this.$parent.checkedData = [];
      }
    },
    checkoutBeforeAdd: function checkoutBeforeAdd(item, cancelChecked) {
      var _this10 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        var checkedData, result;
        return _regeneratorRuntime.wrap(function _callee6$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                if (_this10.beforeAdd) {
                  checkedData = cloneDeep(_this10.checkedData);
                  result = _this10.beforeAdd(item, checkedData);

                  if (result) {
                    cancelChecked && (item.isChecked = false); // throw new Error('checkoutBeforeAdd break')
                  }
                }

              case 1:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee6);
      }))();
    },
    saveArea: function saveArea() {
      // 保存操作
      var data = cloneDeep(this.checkedData);
      this.$emit('change', data);
    }
  }
};