<template>
  <el-dialog :title="$t('批量修改')" :before-close="()=>{$emit('update:showConsBatchEdit',false)}"
             :visible.sync="showConsBatchEdit">
    <h1>合共<span style="color: red">{{ consIds.length }}</span> 个包裹</h1>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card class="mt-10">
        <div slot="header" class="card-title">{{ $t('运输') }}</div>
        <div class="form-section">
          <el-form-item :label="$t('运输方式')" prop="transportId">
            <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" formatter="number"
                           clearable @input="updateRoutes('transportId')"/>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('集运仓库')" v-model="form.wareId" prop="wareId" :rules="{
                              required: true, message: '请选择集运仓库', trigger: 'blur'
                              }">
            <template v-for="(item, index) in warehouseList">
              <el-button :type="warehouseList.length === 1 ||form.wareId === item.id ? 'primary' : 'default'"
                         @click="setWarehouseId(item)">
                {{ item.titleZh }}
              </el-button>
            </template>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('始发城市')" prop="departureId" :disabled="true">
            <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')" :disabled="true"
                       clearable @input="updateRoutes('departureId')">
              <el-option v-for="item in exportCityList" :label="$l(item, 'title')" :value="item.id"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的国家')" prop="consigneeCountryId">
            <el-select v-model="form.consigneeCountryId" :placeholder="$t('请选择目的国家')"
                       @change="handleChangeDestCountry" clearable :disabled="form.shipmentState > 0">
              <el-option v-for="item in showDestCountryList" :label="$l(item, 'guojiaName')" :value="item.guojia"
                         :key="item.guojia"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的城市')" prop="consigneeCityId">
            <el-select v-model="form.consigneeCityId" :placeholder="$t('请选择目的地')" @change="handleChangeDestCity"
                       clearable>
              <el-option v-for="item in showDestCityList" :label="$l(item, 'shiName')" :value="item.shi"
                         :key="item.shi"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('选择线路')" prop="lineId">
            <el-input
              :value="selectedRouter ? $l(selectedRouter, 'startTitle') + ' > ' + $l(selectedRouter, 'destTitle') : ''"
              disabled :placeholder="$t('请在右侧选择线路')"></el-input>
          </el-form-item>
          <!--select是原生组件，不受el-form的disabled控制-->
          <select size="5" v-model="form.warehouseLineId"
                  style="margin-left: 5px;min-width: 300px; border:1px solid #DCDFE6; border-radius:4px"
                  @change="handleChangeLineId">
            <option v-for="item in routerList" :value="item.id" :key="item.id">
              {{ $l(item, 'startTitle') }} >> {{ $l(item, 'destTitle') }}
              (
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="item.transportType"></dict-tag>
              )
            </option>
          </select>
        </div>
      </el-card>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t("确认修改") }}</el-button>
      <el-button @click="$emit('update:showConsBatchEdit',false)">{{ $t("取 消") }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import imageUpload from "@/components/ImageUpload/index.vue";
import {updateConsBatch} from '@/api/ecw/cons'
import {DICT_TYPE} from "@/utils/dict";
import {listAllSimpl} from "@/api/system/user";
import Template from "@/views/cms/template/index.vue";
import {
  getConsWarehouse,
  getGuojiaAndShiAndWarehouseList,
  openedRouterList as getOpenedRouterList
} from "@/api/ecw/warehouse";
import {getTradeCityList} from "@/api/ecw/region";

export default {
  name: 'EcwBatchConsEdit',
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    importCityIds() {
      let ids = []
      this.destCityList.forEach(item => {
        ids.push(item.shi)
      })
      return ids
    },
    importCountryIds() {
      let ids = []
      this.destCountryList.forEach(item => {
        ids.push(item.guojia)
      })
      return ids
    },
    exportCityList() {
      console.log("this.tradeCityList", this.tradeCityList)
      return this.tradeCityList.filter(item => item.type == 2 || item.type == 3)
    },
    showDestCountryList() {
      return this.destCountryList
    },
    exportCityIds() {
      let ids = []
      this.exportCityList.forEach(item => {
        ids.push(item.id)
      })
      return ids
    },
  },
  components: {Template, imageUpload},
  props: {
    consIds: {  // 接收数组
      type: Array,
      default: () => []
    },
    showConsBatchEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      warehouseList: [],
      showDestCityList: [],
      tradeCityList:[],
      selectedRouter: null,
      routerList: [],
      rules: {
        status: [
          { required: true, message: "请选择状态", trigger: "blur" }
        ]
      },
    }
  },
  async created() {
    getConsWarehouse().then((r) => {
      this.warehouseList = r.data;
      if (this.warehouseList.length === 1) {
        this.setWarehouseId(this.warehouseList[0]);
      }
    });
    listAllSimpl().then((r) => {
      this.allSimplList = r.data
    })
    await this.getTradeCity()
    await getGuojiaAndShiAndWarehouseList({tradeType: 1}).then(({data}) => {
      this.destCountryList = data.guojiaList
      this.destCityList = data.shiList
      this.showDestCityList = data.shiList
    })
    getConsWarehouse().then((r) => {
      this.warehouseList = r.data;
      if (this.warehouseList.length === 1) {
        this.setWarehouseId(this.warehouseList[0]);
      }
    });
  },
  watch:{
    'form.wareId'(val) {
      const departureId=this.warehouseList.find(item => item.id === val).shi
      this.$set(this.form, 'departureId', departureId)
      this.getOpenedRouterList()
    },
  },
  methods: {
    setWarehouseId(item) {
      this.$set(this.form, 'wareId', item.id)
    },
    async getTradeCity(a) {
      let query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      this.tradeCityList = (await getTradeCityList(query)).data
    },
    // 切换线路回调
    async handleChangeLineId() {
      await this.$nextTick()
      this.selectedRouter = this.routerList.find(item => item.id === this.form.warehouseLineId)
      console.log("handleChangeLineId",
        "路线", this.form.warehouseLineId,
        "目的市", this.selectedRouter?.destCityId,
        "目的国", this.selectedRouter?.destCountryId,
        "始发市", this.selectedRouter?.startCityId)
      if (this.form.warehouseLineId) {
        this.form.consigneeCityId = this.selectedRouter?.destCityId
        this.form.consigneeCountryId = this.selectedRouter?.destCountryId
        this.form.departureId = this.selectedRouter?.startCityId
        this.form.consigneeWarehouseId = this.selectedRouter?.destWarehouseId
      }
    },
    // 切换目的国
    handleChangeDestCountry(val) {
      console.log("handleChangeDestCountry", val)
      // 目的城市赋值
      this.form.consigneeCountryId = val
      if (!val) {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList))
      } else {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList.filter(item => item.guojia === val)))
      }
      if (this.form.consigneeCountryId) {
        this.form.consigneeCityId = null
        this.form.warehouseLineId = null
        this.selectedRouter = null
        this.updateRoutes('handleChangeDestCountry')
      }
    },
    // 切换目的城市
    async handleChangeDestCity(val) {
      this.form.consigneeCityId = val
      if (this.form.consigneeCityId) {
        this.form.warehouseLineId = null
        this.selectedRouter = null
        this.form.consigneeCountryId = this.destCityList.find(item => item.shi === val)?.guojia

      }
      await this.updateRoutes('handleChangeDestCity')
    },
    // 更新路线并打印来源
    updateRoutes(fr) {
      console.log("%cupdateRotutes", "color: blue", fr)
      return this.getOpenedRouterList()
    },
    // 获取路线
    async getOpenedRouterList() {
      let params = {}
      if (this.form.departureId) {
        params.startCityId = this.form.departureId
      }
      if (this.form.consigneeCountryId) {
        params.destCountryId = this.form.consigneeCountryId
      }
      if (this.form.consigneeCityId) {
        params.destCityId = this.form.consigneeCityId
      }
      if (this.form.transportId) {
        params.transportType = this.form.transportId
      }
      if (this.form.channelId) {
        params.channelId = this.form.channelId
      }
      console.log("获取路线,参数", params)
      // 始发，目的和运输方式都没有的时候不获取
      if (!params.startCityId && !params.destCountryId && !params.destCityId && !params.transportType) return false
      return getOpenedRouterList(params).then(res => {
        this.routerList = res.data.filter(item => {
          return this.exportCityIds.indexOf(item.startCityId) > -1 && this.importCountryIds.indexOf(item.destCountryId) > -1 && (this.importCityIds && this.importCityIds.indexOf(item.destCityId) > -1 && (item.otherService && item.otherService.indexOf(1) > -1))
        })
        console.log(`已获取到路线${res.data?.length}条，有效路线${this.routerList.length}条,参数:${JSON.stringify(params)}`)
        console.table([
          {
            all: res.data.map(item => item.id).join(","),
            avail: this.routerList.map(item => item.id).join(",")
          }
        ])
        // 如果已选择的线路ID不在上述路线列表里则重置
        if (this.form.warehouseLineId) {
          this.selectedRouter = this.routerList.find(item => item.id == this.form.warehouseLineId)
          if (!this.selectedRouter) {
            console.log(`获取到的路线未找到原路线lineId: ${this.form.warehouseLineId}，重置为null`)
            this.$set(this.form, 'warehouseLineId', null)
          }
        }
      })
    },
    submitForm() {
      //二次确认
      this.$modal
        .confirm(this.$t("确认更新数据" + "?"))
        .then(() => {
          this.form.consIds = this.consIds;
          this.$refs.form.validate(validate => {
            if (validate) {
              updateConsBatch(this.form).then(response => {
                this.$emit("update:showConsBatchEdit", false)
                this.$emit("determine")
                this.$modal.msgSuccess("批量修改成功")
              })
            }
          })
        })
        .catch(() => {
          return false;
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.form-section {
  display: flex;

}
</style>
