<script>
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import PackagingType from "@/views/ecw/channel/componrnts/packaging-type.vue";
import {getChannelList} from "@/api/ecw/channel";
import AirFreightRouteTemplate from "@/views/ecw/offer/components/airFreightRouteTemplate.vue";
import {createWarehouseLineChannelPackaging, getAirLineChannelPackagingList} from "@/api/ecw/customerContacts";

export default {
  name: "channel-route",
  components: {AirFreightRouteTemplate, PackagingType},
  mounted() {
    getChannelList({lineId: this.lineId}).then((res) => (this.channelList = res.data));
    this.getRouteDetails(this.lineId, (value) => {
      this.form.channelList = this.setChannelData(value)
    })
  },

  data() {
    return {
      form: {
        "lineId": 0,
        channelList: [{
          "channelIds": "",
          "packagingCreateReqVOList": [
            {
              "airWeightLimit": 0,
              "packagingTypes": "",
              "priceStepClearanceCreateReqVOList": []
            }
          ]
        }],
      },
      channelList: [],
      dialogVisible: false,
    }
  },
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    deletePackagingTypes() {
      return (index) => {
        let a = []
        this.form.channelList[index].packagingCreateReqVOList.forEach(i => {
          a.push(...i.packagingTypes)
        })
        return a
      }
    },
    channelIdBlackList() {
      let arr = []
      this.form.channelList.forEach(i => {
        arr.push(...i.channelIds)
      })
      return arr
    },
    // 线路id
    lineId() {
      return Number(this.$route.query.id);
    }
  },
  methods: {
    deleteFn(index) {
      this.form.channelPackagingList.splice(index, 1)
    },
    getDictDatas,
    //添加包装类型
    addPackaging(index) {
      let p = {
        airWeightLimit: '',
        packagingTypes: [],
        priceStepClearanceCreateReqVOList: [],
      }
      let arr = this.form.channelList[index].packagingCreateReqVOList
      arr.push(p)
      this.$set(this.form.channelList[index], 'packagingCreateReqVOList', arr);
    },
    newChannelsAdd(index) {
      this.form.channelList.splice(index + 1, 0, {
        "channelIds": "",
        "packagingCreateReqVOList": [
          {
            "airWeightLimit": 0,
            "packagingTypes": "",
            "priceStepClearanceCreateReqVOList": []
          }
        ]
      },)
    },
    channelsDelete(index) {
      this.form.channelList.splice(index, 1)
    },
    deletePackag(index, indexx) {
      let arr = this.form.channelList;
      arr[index].packagingCreateReqVOList.splice(indexx, 1);
      this.form.channelList = arr;
    },
    getRouteDetails(id, callback = () => {
    }) {
      getAirLineChannelPackagingList(id).then((r) => {
        callback(r.data)
      })
    },
    setChannelData(list = []) {
      let arr = []
      list.forEach((i, index) => {
        if (index === 0) {
          arr.push({channelIds: i.channelIds, packagingCreateReqVOList: [i]})
        } else {
          if (i.channelIds === list[index - 1].channelIds) {
            arr[arr.length - 1].packagingCreateReqVOList.push(i)
          } else {
            arr.push({channelIds: i.channelIds, packagingCreateReqVOList: [i]})
          }
        }
      })
      arr.forEach(i => {
        i.channelIds = i.channelIds ? i.channelIds.split(',') : []
        i.packagingCreateReqVOList.forEach(item => {
          item.packagingTypes = item.packagingTypes ? item.packagingTypes.split(',') : [];
          item.priceStepClearanceCreateReqVOList = item.lineChannelPriceStepClearanceBackVOList || [];
          item.lineChannelPriceStepClearanceBackVOList = null;
          item.priceStepClearanceCreateReqVOList.forEach(itemm => {
            itemm.clearancePriceUnit = item.clearancePriceUnit
            itemm.clearanceVolumeUnit = item.clearanceVolumeUnit
          })
        })
      })
      if (arr.length === 0) {
        return [{
          "channelIds": "",
          "packagingCreateReqVOList": [
            {
              "airWeightLimit": 0,
              "packagingTypes": "",
              "priceStepClearanceCreateReqVOList": []
            }
          ]
        }]
      }
      return arr;

    },
    getChannelDate(value) {
      let obj = Object.assign({}, value)
      let arr = []
      obj.channelList.forEach(i => {
        i.packagingCreateReqVOList.forEach(item => {
          item.channelIds = i.channelIds.join(',');
          let p = {
            "airWeightLimit": item.airWeightLimit,
            "channelIds": item.channelIds,
            "clearancePriceUnit": item.priceStepClearanceCreateReqVOList[0].clearancePriceUnit,
            "clearanceVolumeUnit": item.priceStepClearanceCreateReqVOList[0].clearanceVolumeUnit,
            "lineId": this.lineId,
            "packagingTypes": item.packagingTypes.join(','),
            priceStepClearanceCreateReqVOList: this.getPriceStepClearanceCreateReqVOList(item.priceStepClearanceCreateReqVOList)
          }
          arr.push(p)
        })
      })
      return {
        lineId: this.lineId,
        packagingCreateReqVOList: arr,
      }
    },
    getPriceStepClearanceCreateReqVOList(list) {
      let arr = []
      list.forEach(i => {
        arr.push({
          "clearancePrice": i.clearancePrice,
          "endNum": i.endNum,
          "startNum": i.startNum
        })
      })
      return arr
    },
    submit() {
      if (!this.validation()) return
      createWarehouseLineChannelPackaging(this.getChannelDate(this.form)).then(r => {
        this.$message.success('保存成功');
        this.$router.back()
      })
    },
    copy(value) {
      this.getRouteDetails(value.id, (value) => {
        this.form.channelList = this.setChannelData(value)
        this.$message.success('复制成功。')
      })
    },
    validation() {
      let flag = true
      try {
        this.form.channelList.forEach((item, index) => {
          if (!item.channelIds.length) {
            throw `渠道${index + 1}没有选择航道`;
          }
          item.packagingCreateReqVOList.forEach((itemm, indexx) => {
            if (!itemm.packagingTypes.length) {
              throw `渠道${index + 1}-包装类型${indexx + 1}，没有选择包装类型。`;
            }
            if (!(itemm.airWeightLimit > 0)) {
              throw `渠道${index + 1}-包装类型${indexx + 1}，没有输入空运订单重量上限。`;

            }
            let check = (indexxx) => {
              return `渠道${index + 1}-包装类型${indexx + 1}- 第${indexxx + 1}价格输入有问题。`

            }
            itemm.priceStepClearanceCreateReqVOList.forEach((itemmm, indexxx) => {
              if (!itemmm.clearancePrice || itemmm.clearancePrice === '') {
                throw check(indexxx);
              }
              if (!itemmm.clearancePriceUnit || itemmm.clearancePriceUnit === '') {

                throw check(indexxx);
              }
              if (!itemmm.clearanceVolumeUnit || itemmm.clearanceVolumeUnit === '') {
                throw check(indexxx);
              }
              if (isNaN(itemmm.endNum) || itemmm.endNum === '') {
                throw check(indexxx);
              }
              if (isNaN(itemmm.startNum) || itemmm.startNum === '') {
                throw check(indexxx);
              }
              // if (!itemmm.weightUnit || itemmm.weightUnit === '') {
              //   throw check(indexxx);
              // }
            })
          })
        })
      } catch (e) {
        flag = false
        console.log(e.Error, 'eee')
        this.$message.warning(e);
      }
      return flag
    }
  }
}
</script>

<template>
  <div style="padding: 20px">
    <div style="margin-bottom: 15px">
      <span>目的国：{{ $route.query.destCountryName }}</span>
      <span>路线：{{ $route.query.startWarehouseTitle }}到{{ $route.query.destWarehouseTitle }}</span>
      <span style="margin-left: 30px;">运输方式：空运专线</span>
    </div>
    <el-card style="margin-bottom: 10px" v-for="(itemOuter,index) in form.channelList" :key="index">
      <template #header>
        <el-row :gutter="20" type="flex" align="middle">
          <el-col :span="1">渠道{{ index + 1 }}
          </el-col>
          <el-col :span="3">
            <el-select multiple v-model="itemOuter.channelIds">
              <el-option
                  :disabled="channelIdBlackList.includes(item.channelId.toString()) && (!itemOuter.channelIds.includes(item.channelId.toString()))"
                  v-for="item in channelList" :value="item.channelId.toString()" :key="item.channelId"
                  :label="$l(item, 'name')"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-button size="mini" type="primary" @click="newChannelsAdd(index)">新增渠道</el-button>
          </el-col>
          <el-col :span="3">
            <el-button size="mini" type="danger" :disabled="form.channelList.length === 1"
                       @click="channelsDelete(index)">
              删除当前渠道
            </el-button>
          </el-col>
          <el-col :span="3">
            <air-freight-route-template :lineId="lineId" @copy="copy">
              <el-button size="mini" v-if="index === 0" type="text">选择渠道包装模板</el-button>
            </air-freight-route-template>
          </el-col>
        </el-row>
      </template>
      <div style="display: flex;justify-content: space-between;">
        <h1>
          <span style="color: red;font-size: 14px;font-weight: 700;">*</span>
          渠道包装列表
        </h1>
        <div>
          <el-button type="primary" @click="addPackaging(index)">添加包装类型</el-button>
        </div>
      </div>
      <el-row :gutter="20" v-for="(itemm, indexx) in itemOuter.packagingCreateReqVOList"
              style="margin-bottom: 50px; border-bottom: 1px solid #cccccc" :key="indexx">
        <el-col :span="2">包装类型{{ indexx + 1 }}：</el-col>
        <el-col :span="5">
          <el-select multiple v-model="itemm.packagingTypes">
            <el-option
                :disabled="deletePackagingTypes(index).includes(item.value) && (!itemm.packagingTypes.includes(item.value))"
                v-for="item in getDictDatas(DICT_TYPE.ECW_PACKAGING_TYPE)" :value="item.value" :key="item.value"
                :label="$l(item, 'label')"></el-option>
          </el-select>
        </el-col>
        <el-col :span="16">
          <!--          v-if="itemOuter.packagingCreateReqVOList[indexx].length"-->
          <packaging-type key-arr="priceStepClearanceCreateReqVOList"
                          v-model="itemOuter.packagingCreateReqVOList[indexx]">
            <el-button @click="deletePackag(index,indexx)" :disabled="itemOuter.packagingCreateReqVOList.length === 1"
                       type="danger">删除包装类型{{ indexx + 1 }}
            </el-button>
          </packaging-type>
        </el-col>
      </el-row>
    </el-card>
    <div class="footer">
      <el-button type="primary" @click="submit">保存</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.footer {
  position: fixed;
  bottom: 20px;
}
</style>
