<template>
  <!-- 用于下拉搜索框（物流相关模块） -->
  <div class="DropDownSelectFilter">
    <div class="DropDownSelectInput">
      <Select
        ref="selectOne"
        v-model="choosedExpress"
        multiple 
        multiple-type
        style="width:32px"
        label-in-value
        choose-all
        @on-change="chooseExpress"
      >
        <Option
          v-for="item in expressList"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
        </Option>
      </Select>
      <Input
        v-model="ruleName"
        icon
        suffix="ios-search"
        :placeholder="placeholder"
        style="width: auto"
        search
        @on-change="getEnterExpressList"
        @on-search="getEnterExpressList"
      />
      <!-- on-search -->
    </div>
    <div class="choosedItemBox">
      <div class="boxTitle">
        <span class="title">{{ choosedTitle }}</span>
        <Button
          v-if="choosedExpressList.length>0"
          icon="ios-close-circle"
          type="text"
          ghost
          style="color: var(--primary-color);"
          @click="clearChoosedExpress"
        >
          清空
        </Button>
      </div>
      <div class="contentBox">
        <p
          v-if="choosedExpressList.length==0"
          style="margin-top: 16px;"
        >
          提示:系统优先选择排序靠前的{{ tipMsg }}
        </p>
        <draggable
          class="syllable_ul"
          element="ul"
          :list="choosedExpressList"
          :options="{group:'title', animation:150}"
          :no-transition-on-drag="true"
        >
          <transition-group
            type="transition"
            :css="true"
          >
            <li
              v-for="(item, index) in choosedExpressList"
              :key="item.value"
              class="expressItem"
            >
              <span class="orderSpan">{{ index+1 }}</span>
              <span class="labelSpan">{{ item.label }}</span>
              <Icon
                type="md-close"
                color="#989898"
                class="iconSpan"
                @click="deleteOneItem(index,item)"
              />
            </li>
          </transition-group>
        </draggable>
      </div>
    </div>
  </div>
</template>

<script>
  import draggable from 'vuedraggable';

  const R3 = window.R3;

  const { network } = R3;
  export default {
    components: {
      draggable
    },
    props: {
      preChoosed: {
        type: Array,
        default: () => []
      },
      pageType: {
        type: String,
        default: () => ''
      },
      idArray: {
        type: [Array],
        default: () => []
      }
    },
    data() {
      return {
        ruleName: '',
        choosedTitle: '',
        placeholder: '',
        tipMsg: '',
        choosedExpress: [], // 下拉框默认选中
        expressListAll: [],
        expressList: [], // 下拉框全部数据
        choosedExpressList: [], // 展示框已经选中
        totalCount: 0,
      };
    },
    created() {
      if (this.pageType == 'onAddRelation') {
        this.choosedTitle = '已选择实体仓库';
        this.placeholder = '请点击下拉箭头选择仓库，或者输入关键字识别搜索';
        this.tipMsg = '实体仓库';
      } else if (this.pageType == 'SetLogisticsRules') {
        this.choosedTitle = '已选择物流公司';
        this.placeholder = '请点击下拉箭头选择物流公司，或者输入关键字识别搜索';
        this.tipMsg = '物流公司';
      } else {
        this.choosedTitle = '已选择物流规则';
        this.placeholder = '请点击下拉箭头选择物流规则，或者输入关键字识别搜索';
        this.tipMsg = '物流规则';
      }
      setTimeout(() => {
        this.preChoosed.forEach(item => {
          this.choosedExpress.push(String(item));
        });
        this.getExpressList();
      }, 300);
    },
    watch: {
      choosedExpressList: {
        handler(val) {
          this.$emit('changeChoosedExpressList', val);
        }
      }
    },
    methods: {
      exist(num, arr1) {
        for (let j = 0; j < arr1.length; j++) {
          if (num.value === arr1[j].value) {
            return false; // 如果传过来的元素在arr1中能找到相匹配的元素，我们返回fasle
          }
        }
        return true; // 如果不能找到相匹配的元素，返回true
      },
      getwarehouse(type){
        // 获取选中的分仓规则ID
        const ruleId = Number(this.idArray[0]) || '';
        // 发起查询请求
        network.post('/p/cs/warehouse/query', {
          ruleId,
          warehousename: this.ruleName,
        }).then(res => {
         const { code ,data} = res.data
         this.expressList = []
          if (code === 0) {
            data.forEach((item) => {
              this.choosedExpressList.forEach((preItem, index) => {
                if (preItem == item.WAREHOUSEID) {
                  this.choosedExpress.push(item.WAREHOUSEID)

                  let obj = {
                    value: String(item.WAREHOUSEID),
                    label: String(item.WAREHOUSENAME),
                  };
                  this.choosedExpressList[index] = obj;
                }
              });
              let obj = {
                value: String(item.WAREHOUSEID),
                label: String(item.WAREHOUSENAME),
              };
              this.expressList.push(obj);
            });
            if (type) {
              this.$refs.selectOne.visible = true;
            } else {
              this.expressListAll = JSON.parse(JSON.stringify(this.expressList));
              this.totalCount = this.expressList.length;
            }
          }
        })
      },
      chooseExpress(value) {
        if (value.length == this.expressListAll.length) {
          let list = [];
          value.forEach(item => {
            this.choosedExpressList.forEach(itemOne => {
              if (itemOne.value == item.value) {
                list.push(item);
              }
            });
          });
          setTimeout(()=> {
            let newArr = [];
            for (let i = 0; i < this.expressList.length; i++) {
              // 我们将arr2中的元素依次放入函数中进行比较，然后接收函数的返回值
              if (this.exist(this.expressList[i], list)) { // 如果返回的值是true，我们将元素放入新的数组中
                newArr[newArr.length] = this.expressList[i];
              }
            }
            if (newArr.length != this.expressList.length && this.choosedExpressList.length != 0) {
              newArr.forEach(item => {
                if (this.choosedExpressList.length >= this.totalCount) {

                } else {
                  this.choosedExpressList.push(item);
                }
              });
            } else {
              this.choosedExpressList = value;
            }
          }, 500);
          // this.expressList.forEach(item => {
          //   this.choosedExpress.push(item.value);
          // });
          // this.choosedExpressList = JSON.parse(JSON.stringify(this.expressList));
        } else {
          let notChooesedList = this.getDistinct(this.expressList, value);
          let deleteList = this.getDistinct(this.choosedExpressList, notChooesedList);
          let delList = this.getSame(notChooesedList, deleteList);
          if (delList.length > 0) {
            delList.forEach(item => {
              this.choosedExpressList.forEach((express, index) => {
                if (item == express.value) {
                  this.choosedExpressList.splice(index, 1);
                }
              });
            });
          }
          let arr = this.uniq(this.choosedExpressList, value);
          if (arr.length == this.totalCount) {
            if (this.choosedExpressList.length > 0 && value.length !== this.totalCount) {
              let list = [];
              value.forEach(item => {
                this.expressListAll.forEach(itemOne => {
                  if (itemOne.value == item.value) {
                    list.push(itemOne);
                  }
                });
              });
              if (this.choosedExpressList.length !== this.expressListAll.length) {
                if (list.length >= this.choosedExpressList.length) {} else {
                  list.forEach((item, index) => {
                    this.choosedExpressList.forEach(itemNew => {
                      if (item.value == itemNew.value) {
                        list.splice(index, 1);
                      }
                    });
                  });
                  setTimeout((
                               list.forEach(item => {
                                 this.choosedExpressList.push(item);
                               })
                             ), 20);
                }
              }
            } else {
              this.choosedExpressList = JSON.parse(JSON.stringify(this.expressListAll)); 
            }
          } else {
            let arrOne = this.getDistinctOne(this.choosedExpressList, arr);
            if (arrOne.length > 0) {
              arrOne.forEach(item => {
                this.choosedExpressList.push(item);
              });
            }
            // this.choosedExpressList = this.choosedExpressList;
          }
        }
      },
      getEnterExpressList() {
        this.choosedExpress = [];
        this.choosedExpressList.forEach(item => {
          this.choosedExpress.push(item.value);
        });
        this.getExpressList('input');
      },
      getExpressList(type) {
         // 如果是添加关系的场景，特殊处理
         if (this.pageType === 'onAddRelation') {
          this.getwarehouse(type)
          return;
        }
        let params = {};
        
        if (this.pageType == 'setExperssRule' || this.pageType == 'setLogisticsRule') {
          params = {
            table: 'T_ESPLOGISTICSRULE',
            startindex: 0,
            range: 1000,
            fixedcolumns: {
              RULENAME: this.ruleName,
              IsCod: ['=0'] 
            },
            isactive: ['=Y'] 
          };
        } else if (this.pageType == 'setCodExperssRule' || this.pageType == 'CODSetLogisticsRule') {
          params = {
            table: 'T_ESPLOGISTICSRULE',
            startindex: 0,
            range: 1000,
            isdroplistsearch: true,
            fixedcolumns: {
              RULENAME: this.ruleName,
              IsCod: ['=1'] 
            },
            isactive: ['=Y'] 
          };
        } else if (this.pageType == 'onAddRelation') {
          params = {
            table: 'T_IESWAREHOUSE', 
            startindex: 0, 
            range: 1000, 
            isdroplistsearch: true, 
            fixedcolumns: {
              WAREHOUSENAME: this.ruleName
            }
          };
        } else if (this.pageType == 'SetLogisticsRules') {
          params = {
            table: 'T_V_OMSLOGISTICSCOMPANY',
            startindex: 0,
            range: 1000,
            isdroplistsearch: true,
            fixedcolumns: { NAME: this.ruleName, isactive: ['=Y'] }
          };
        }
        network.post('/p/cs/list/query', params).then((res) => {
          if (res.status == 200) {
            this.expressList = [];
            res.data.rows.forEach((item) => {
              this.choosedExpressList.forEach((preItem, index) => {
                if (preItem == item.ID.val) {
                  let obj = {};
                  if (this.pageType == 'onAddRelation') {
                    obj = {
                      value: item.ID.val,
                      label: String(item.WAREHOUSENAME.val),
                    };
                  } else if (this.pageType == 'SetLogisticsRules') {
                    obj = {
                      value: item.ID.val,
                      label: String(item.NAME.val),
                    };
                  } else {
                    obj = {
                      value: item.ID.val,
                      label: String(item.RULENAME.val),
                    };
                  }
                  // this.choosedExpress[index] = item.ID.val;
                  this.choosedExpressList[index] = obj;
                }
              });
              let obj = {};
              if (this.pageType == 'onAddRelation') {
                obj = {
                  value: item.ID.val,
                  label: String(item.WAREHOUSENAME.val),
                };
              } else if (this.pageType == 'SetLogisticsRules') {
                obj = {
                  value: item.ID.val,
                  label: String(item.NAME.val),
                };
              } else {
                obj = {
                  value: item.ID.val,
                  label: String(item.RULENAME.val),
                };
              }
              this.expressList.push(obj);
            });
            if (type) {
              this.$refs.selectOne.visible = true;
            } else {
              this.expressListAll = JSON.parse(JSON.stringify(this.expressList));
              this.totalCount = this.expressList.length;
            }
          }
        });
      },
      clearChoosedExpress() {
        this.choosedExpress = [];
        this.choosedExpressList = [];
      },
      // clearChoosedExpressFilter() {
      //   this.expressList.forEach(item => {
      //     this.choosedExpressList.forEach((item1,index) => {
      //     })
      //   })
      // },
      deleteOneItem(index, item) {
        this.choosedExpress.forEach((itemOne, indexOne) => {
          if (itemOne == item.value) {
            this.choosedExpress.splice(indexOne, 1);
          }
        });
        this.choosedExpressList.splice(index, 1);
      },
      getdiffrent(arr, arr1) { // 获取两个数组不同项
        let c = [...arr, ...arr1];
        let d = new Set(c);
        let e = Array.from(d);
        let f = [...e.filter(_ => !arr.includes(_)), ...e.filter(_ => !arr1.includes(_))];
        return f;
      },
      getDistinct(arr1, arr2) {
        let arr = [];
        for (let i = 0; i < arr1.length; i++) {
          let obj1 = arr1[i].value;
          let isExist = false;
          for (let j = 0; j < arr2.length; j++) {
            let obj2 = arr2[j].value;
            if (obj1 == obj2) {
              isExist = true;
              break;
            }
          }
          if (!isExist) {
            arr.push(obj1);
          }
        }
        return arr;
      },
      getDistinctOne(arr1, arr2) { // 获取两个数组不同项
        let differentArr = arr2.filter(item=>!arr1.some(ele=>ele.value == item.value)); 
        return differentArr;
      },
      getSame(arr1, arr2) { // 获取两个数组相同项
        let newArr = [];
        for (let i = 0; i < arr2.length; i++) {
          for (let j = 0; j < arr1.length; j++) {
            if (arr1[j] === arr2[i]) {
              newArr.push(arr1[j]);
            }
          }
        }
        return newArr;
      },
      getSameOne(arr1, arr2) { // 获取两个数组相同项
        let newArr = [];
        for (let i = 0; i < arr2.length; i++) {
          for (let j = 0; j < arr1.length; j++) {
            if (arr1[j].value == arr2[i].value) {
              newArr.push(arr1[j]);
            }
          }
        }
        return newArr;
      },
      uniq(arr, arr1) { // 数组去重
        const temp = [];
        const index = [];
        const array = [...arr, ...arr1];
        const l = array.length;
        for (let i = 0; i < l; i++) {
          for (let j = i + 1; j < l; j++) {
            if (array[i].value === array[j].value) {
              i++;
              j = i;
            }
          }
          temp.push(array[i]);
          index.push(i);
        }
        return temp;
      },
    },
  };
</script>
<style lang='less'>
  .DropDownSelectFilter .ark-select-multiple .ark-select-selection {
    padding: 0px 28px 0px 2px;
    height: 36px;
  }
  .DropDownSelectFilter .ark-select .ark-select-dropdown {
    width: calc(100% - 32px);
  }
  .DropDownSelectFilter .ark-input-wrapper {
    width: calc(100% - 34px) !important;
  }
  .DropDownSelectFilter .ark-input {
    height: 36px;
  }
  .DropDownSelectFilter .ark-input-prefix i,.DropDownSelectFilter .ark-input-suffix i {
    line-height: 36px;
  }
  .DropDownSelectFilter .ark-btn > .ark-icon + span,.DropDownSelectFilter .ark-btn > span + .ark-icon {
    margin-left: 0px;
  }
  .DropDownSelectFilter .ark-input-search-icon {
    font-size: 22px;
    line-height: 36px;
  }
  .DropDownSelectFilter .ark-select-item-all.ark-select-item.ark-select-item-all-multipleType:hover {
    background: #fff;
  }
  .DropDownSelectFilter .ark-select-item-all.ark-select-item.ark-select-item-all-multipleType span:first-child:hover{
    background: #eee;
  }
  .DropDownSelectFilter .ark-select-item-all.ark-select-item.ark-select-item-all-multipleType span:last-child:hover{
    background: #eee;
  }

</style>
<style lang='less' scoped>
  .DropDownSelectInput {
    display: flex;
  }
  .choosedItemBox {
    border: 1px solid #DADADA;
    margin-top: 16px;
    padding: 16px;
    padding-bottom: 8px;
    .boxTitle {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      color: var(--primary-color);
      .title{
        height: 18px;
        line-height: 18px;;
        color: #323232;
        font-weight: 600;
      }
      span {
        margin-left: 0px;
      }
      .ark-btn {
        padding: 0px !important;
      }
    }
    .contentBox {
      height: 200px;
      overflow-y: auto;
    }
  }
  .expressItem {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 32px;
    background: #F2F2F2;
    padding-right:16px;
    margin-bottom: 8px;
  }
  .orderSpan {
    display: inline-block;
    width: 32px;
    height: 32px;
    line-height: 32px;
    border: 1px solid #DADADA;
    background: #fff;
    text-align: center;
    color: #4D4D4D;
    font-size: 14px;
  }
  .labelSpan {
    width: 100%;
    font-size: 12px;
    color: #4B4B4B;
    text-align: left;
    padding-left: 8px;
  }
  
</style>
