<template>
  <div class="xd-region-path">
    <div class="xd-region-path__show" v-if="selectedList.length > 0">
      <xd-check-box-list
        :list="selectedList"
        @change="handleChange"
        v-model="selectedValue"
        label-key="value"
        label-name="label"
        item-width="auto"
        is-one-line
        :is-all="false"
        item-margin="0 20px 0 0"
      >
      </xd-check-box-list>
    </div>
    <div class="xd-region-path__option">
      <div class="xd-region-path__option-box">
        <el-cascader-panel
          ref="xdRegionPath"
          :style="` margin-right: 10px;height:${height};`"
          :props="props"
          filterable
          clearable
          collapse-tags
        >
        </el-cascader-panel>
        <div class="xd-region-path__option-add">
          <el-button type="primary" :size="size" @click="add">添加</el-button>
          <el-button type="primary" :size="size" @click="addAll">全部省/市</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  let $vm = null;
  import XdCheckBoxList from "@/components/XdCheckBoxList";

  export default {
    name: "XdRegionPath",
    components:{
      XdCheckBoxList
    },

    props: {
      defaultSelectedRegion:{
				type: Array,
				default() {
					return [
					  // {"label": "全国", "value": "0"},
            // {"label": "北京/北京/门头沟", "value": "2807"}
          ];
				}
      },

			searchWdith: {
      	type: String,
        default() {
					return '350px';
				}
			},

			multiple: {
      	type: Boolean,
        default : false,
      },

			height: {
				type: String,
        default: '260px'
      }
    },
    data(){
      return {
        size: null,
				isFirst: true,
      	selectedList: [], //已经添加的城市列表
        selectedValue: [], //选中的城市列表
				cascaderValue: [],
        parentNode: [], //省份
        options: [],
				props: {
					lazy: true,
					multiple: false,
					checkStrictly: true,
					lazyLoad(node, resolve){
						$vm.getCascaderDataList(node, resolve);
          }
        }
      }
    },

    watch: {
			defaultSelectedRegion(val){
				this.initSelect(val);
      },
    },

    created() {
			$vm = this;
      this.initSelect(this.defaultSelectedRegion);
      
      this.$set(this.props, 'multiple', this.multiple);
      if(this.multiple) {
        this.$set(this.props, 'checkStrictly', !this.multiple);
      }
      
      
			this.$emit('input', this.selectedList);
			if(!this.isFirst)this.$emit('change', this.selectedList);
			this.size = this.$xdHelper.isPC()?'medium': 'mini';
		},

		methods: {
      initSelect(){
    		if(this.$xdHelper.checkVarType(this.defaultSelectedRegion) === 'array'
          || this.$xdHelper.checkVarType(this.defaultSelectedRegion) === 'object'
        ) {
    		  let selectList = [];
    		  let selectValue = [];
          this.defaultSelectedRegion.map(item=>{
            selectList.push({...item});
            selectValue.push(item.value)
          });
          this.selectedList = selectList;
          this.selectedValue = selectValue;
        }
      },

			getCascaderDataList(node, resolve){
        console.log(node, this.maxLevel);
    		this.$emit('lazyLoad', node, (res)=>{
    		  if(node['level'] === 0) {
    		    let temp = [];
            res.map((item)=>{
              if(item.label !== '全国') {
                temp.push(item)
              }
            });
            this.parentNode = temp;
          }
          console.log('getCascaderDataList', node, this.parentNode);
          resolve(res);
					setTimeout(() => {
						this.isFirst = false;
					}, 400)
        });
      },

      handleChange(reslut){
    		let { list } = reslut;
				this.$emit('input', list);
				this.$emit('change', list);
      },

      addAll(){
        if(this.selectedList.length > 0) {
          this.$message({
            message: `您无法进行全部省/市选中，请重新选择！`,
            type: 'info',
            dangerouslyUseHTMLString: true,
            showClose: true,
            duration: 2000,
            onClose: () => {
            },
          });
          return;
        }
        let tempValue = [];
        let tempLabel = [];
        this.parentNode.map((item)=>{
        	if(Number(item.value) !== -1 && Number(item.value !== 0)) {
						let path_value = [item.value];
						let path_label = [item.label];
						tempValue.push(item.value);
						tempLabel.push({label: item.label, value: item.value, path_value, path_label});
          }
        });
        this.selectedValue = tempValue;
        this.selectedList = tempLabel;
      },

			add(){
        let node = this.$refs['xdRegionPath'].getCheckedNodes();
    		if(node.length === 0) {
					this.$message({
						message: '请选择快递配送区域范围',
						type: 'warning',
						showClose: true,
						duration: 2000,
						onClose: () => {
						},
					});
    			return;
        }
    		
    		console.log(node)
    		
    		let label = node[0]['pathLabels'].join('/');
    		let value = node[0]['value'];
    		let path_value = node[0]['path'];
        let path_label = node[0]['pathLabels'];

    		if(this.$xdHelper.isKeyInLists(this.selectedList, value, 'value')) {
					this.$message({
						message: `您选中的值【<span style="color: red">${label}</span>】重复，请重新选择！`,
						type: 'error',
						dangerouslyUseHTMLString: true,
						showClose: true,
						duration: 2000,
						onClose: () => {},
					});
					return;
        }

    		this.selectedValue.push(value);
    		this.selectedList.push({label,value, path_value, path_label});
      }
    },
	}
</script>

<style scoped lang="scss">
  .xd-region-path {
    &__show {
      padding-bottom: 10px;
    }

    &__option {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      &-box {
        position: relative;
        padding-right: 120px;
      }

      &-add {
        position: absolute;
        top: 0;
        right: 10px;
        display: flex;
        justify-content: flex-end;
        flex-wrap: wrap;
        width: 120px;

        & > * {
          margin: 0 0 10px 0;
        }
      }
    }

    ::v-deep .xd-check-all {
      display: none;
    }

    ::v-deep .xd-checkbox-item {
      display: flex;
      justify-content: flex-start;
      align-content: flex-start;
      align-items: center;
      flex-wrap: nowrap;
      width: auto !important;
    }

    ::v-deep .xd-checkbox-item .xd-checkbox-self {
      margin-right: 10px;
    }

    ::v-deep .el-cascader-panel {
      display: flex;
    }

    ::v-deep .el-cascader-menu,
    ::v-deep .el-cascader-menu__wrap {
      height: 100%;
    }

  }

  @media screen and (max-width: 768px) {
    .xd-region-path {
      width: 100%;
      overflow-x: auto;
      padding-bottom: 10px;
  
      &__option{
        &-box{
          padding-right: 95px;
        }
        &-add {
          width: 95px;
        }
      }
      
      
    }
  }
</style>
