<template>
  <div class="setExpressRule">
    <div class="expressTopTip">
      <div class="tipLeft">
        <Icon
          type="ios-alert"
          size="20"
          color="#F28C35"
        />
      </div>
      <div class="tipRight">
        <div class="title">
          操作提示：
        </div>
        <div class="tipContent">
          拖动列进行排序，点击【清空】删除所有已选择物流规则或点击图标删除单条物流规则，系统优先选择排序靠前的物流公司。
        </div> 
      </div>
    </div>  
    <div class="expressContent">
      <div class="nowStore">
        当前店铺：<span>{{ nowStoreName }}</span>
      </div>
      <div
        class="filterContent"
      >
        <DropDownSelectFilter
          :page-type="pageType"
          :pre-choosed="preChoosed"
          @changeChoosedExpressList="changeChoosedExpressList"
        />
      </div>
    </div>
    <div class="bottomBtnBox">
      <Button
        size="small"
        class="cancelBtn"
        ghost
        @click="cancel"
      >
        取消
      </Button>
      <Button
        type="primary"
        size="small"
        class="sureBtn"
        @click="sureAdd"
      >
        保存
      </Button>
    </div>
  </div>
</template>

<script>
  import DropDownSelectFilter from '../customizedContent/DropDownSelectFilter.vue';

  const R3 = window.R3;

  const { network } = R3;
  export default {
    components: {
      DropDownSelectFilter
    },
    props: {
      idArray: {// 可获取明细表勾选的明细ID
        type: [Array, Object],
        default: () => {}
      },
      selectRowData: {// 获取ID用于多选,获取勾选的明细对应的row内的数据
        type: [Array, Object],
        default: () => {}
      }
    },
    data() {
      return {
        pageType: 'setExperssRule',
        nowStoreName: '',
        nowStoreId: '',
        choosedExpressList: [],
        choosedExpressIdList: [],
        preChoosed: [],
        objPreChoosed: [],
        addList: [],
        deleteList: [],
        sameList: []
      };
    },
    created() {
      this.nowStoreId = Number(this.idArray[0]);
      this.nowStoreName = this.selectRowData[0].IESSHOPID.val;
      this.getNowDetail(Number(this.idArray[0]));
    },
    methods: {
      getNowDetail(id) {
        this.objPreChoosed = [];
        this.preChoosed = [];
        let params = {
          table: 'T_ESPSHOPLOGISTICSRULE',
          startindex: 0,
          range: 100,
          fixedcolumns: { IESShopId: id, IsCod: ['=0'] },
          fkdrplist: {
            searchcols: ['Id', 'IESShopId', 'ESPLogisticsRuleId', 'OrderBy', 'IsCod'],
            orderby: [{ column: 'OrderBy', asc: true }]
          },
          isdroplistsearch: true
        };
        network.post('/p/cs/list/query', params).then((res) => {
          if (res.status == 200) {
            if (res.data.rows && res.data.rows.length > 0) {
              res.data.rows.forEach(rule => {
                let obj = {
                  ESPLOGISTICSRULEID: rule.ESPLOGISTICSRULEID.val,
                  ID: rule.ID.val
                };
                this.objPreChoosed.push(obj);
                this.preChoosed.push(rule.ESPLOGISTICSRULEID.val);
              });
            }
          }
        });
      },
      cancel() {
        this.$parent.close();
      },
      sureAdd() {
        this.getAddList();
        let logisticsRulesDetail = [];
        this.choosedExpressList.forEach((item, index) => {
          let obj = {
            IsCod: false,
            IESShopId: this.nowStoreId,
            ESPLogisticsRuleId: item.value,
            OrderBy: index * 10
          };
          if (item.isAdd) {
            obj.RowStatus = 'CREATE';
          } else if (item.isSame) {
            this.objPreChoosed.forEach(itemNew=>{
              if (item.value == itemNew.ESPLOGISTICSRULEID) {
                obj.Id = itemNew.ID;
              }
            });
            obj.RowStatus = 'UPDATE';
          }
          logisticsRulesDetail.push(obj);
        });
        this.deleteList.forEach(item => {
          let obj = {
            IsCod: false,
            IESShopId: this.nowStoreId,
            ESPLogisticsRuleId: item,
            RowStatus: 'DELETE'
          };
          this.objPreChoosed.forEach(itemNew=>{
            if (item == itemNew.ESPLOGISTICSRULEID) {
              obj.Id = itemNew.ID;
            }
          });
          logisticsRulesDetail.push(obj);
        });
        let params = {
          type: 2,
          logisticsRulesDetail
        };
        network.post('/p/cs/setLogisticsRules', params).then((res) => {
          if (res.status == 200) {
            this.$emit('closeActionDialog', true);
          }
        });
      },
      changeChoosedExpressList(val) {
        this.choosedExpressIdList = [];
        this.choosedExpressList = val;
        this.choosedExpressList.forEach(item => {
          this.choosedExpressIdList.push(item.value);
        });
      },
      getAddList() {
        let arrList = this.uniq(this.choosedExpressIdList, this.preChoosed);
        this.addList = this.getdiffrent(this.preChoosed, arrList);
        this.deleteList = this.getdiffrent(this.choosedExpressIdList, arrList);
        this.sameList = this.getSame(this.preChoosed, this.choosedExpressIdList);
        this.choosedExpressList.forEach((item, index) => {
          this.addList.forEach(itemNew => {
            if (item.value == itemNew) {
              this.choosedExpressList[index].isAdd = true;
            }
          });
        });
        this.choosedExpressList.forEach((item, index) => {
          this.sameList.forEach(itemNew => {
            if (item.value == itemNew) {
              this.choosedExpressList[index].isSame = true;
            }
          });
        });
      },
      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;
      },
      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;
      },
      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] === array[j]) {
              i++;
              j = i;
            }
          }
          temp.push(array[i]);
          index.push(i);
        }
        return temp;
      },
    },
  };
</script>
<style lang='less' scoped>
.setExpressRule {
  width: 720px;
}
.expressTopTip {
  display: flex;
  padding: 12px 8px;
  background: #F9F1C3;
  .tipLeft {
    margin-right: 8px;
  }
  .tipRight {
    color: #585348;
    font-size: 12px;
    line-height: 17px;
    .tipContent {
      margin-top: 4px;
    }
  }
}
.expressContent {
  margin-top: 16px;
  .nowStore {
    color: #CDCDCD;
    span {
      color: #323232;
    }
  }
}
.filterContent {
  min-height: 200px;
  margin-top: 12px;
}
.bottomBtnBox {
    width: calc(100% - 48px);
    margin: 16px auto 0px;
    text-align: center;
    .cancelBtn,.sureBtn {
      width: 72px;
      height: 32px;
      font-size: 12px;
    }
    .cancelBtn {
      color: #909399;
      border: 1px solid #DADADA;
      margin-right: 8px;
    }
  }
</style>
