<template>
  <div v-if="print">
    {{ vehicleName }}
  </div>
  <div
    v-else
    class="select-vehicle-wrp"
  >
    <Input
      ref="vehicleIpt"
      v-model="vehicleName"
      :class="isRedShow ? 'isred' : ''"
      :placeholder="placeholder"
      :disabled="disabled"
      @click.native="inputFocus()"
      @on-blur="inputBlur()"
    />
    <transition name="slide-fade">
      <div
        v-show="isShow"
        ref="popper"
        v-transfer-dom
        :class="`h-ems-place vehiclePopWrap-${rid}`"
        :data-transfer="transfer"
      >
        <div class="h-ems-title">
          选择交通工具及等级
          <i
            class="ivu-icon ivu-icon-ios-close-empty"
            @click="closePlace()"
          ></i>
        </div>
        <div class="h-ems-content">
          <CheckboxGroup
            v-model="vehicleVal"
            @on-change="vehicleChange"
          >
            <Checkbox
              v-for="(item, i) in venicles"
              :key="i"
              :label="item.value"
            >
              <span style="width: 55px;display: inline-block;">{{ item.label }}</span>
              <div
                style="display: inline-block;"
                @click.stop.prevent
              >
                <Select
                  v-if="item.lecels.length > 1"
                  v-model="grade[item.value]"
                  :value="grade[item.value]"
                  :transfer="isTransferSelect"
                  @on-change="gradeChange"
                  @click.stop.prevent
                >
                  <Option
                    v-for="(item2, index2) in item.lecels"
                    v-if="!(businessLineCode == 'SZ' && (gradeRule[item.value] && gradeRule[item.value] > parseInt(item2.value)))"
                    :key="index2"
                    :value="item2.value"
                    :label="item2.label"
                    :disabled="businessLineCode == 'SZ' && (gradeRule[item.value] && gradeRule[item.value] > parseInt(item2.value))"
                    :class="(gradeRule[item.value] && gradeRule[item.value] > parseInt(item2.value))?'vehicleValRed':''"
                    @click.native.stop.prevent
                  >
                  </Option>
                </Select>
                <Input
                  v-else
                  placeholder="暂无可选"
                  disabled
                  :value="item.lecels[0] ? item.lecels[0].label : ''"
                />
              </div>
            </Checkbox>
          </CheckboxGroup>
        </div>
        <div
          class="btns"
          style="background: #FFF;"
        >
          <Button
            size="small"
            @click="closePlace()"
          >
            取消
          </Button>
          <Button
            type="primary"
            size="small"
            @click="closePlace()"
          >
            确定
          </Button>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import TransferDom from "../../util/transfer-dom.js";
import axios from '../axios.js';
const Popper = require("popper.js/dist/umd/popper.js"); // eslint-disable-line

export default {
  name: "SelectVehicle",
  directives: { TransferDom },
  model: {
    prop: "value",
    event: "input"
  },
  props: {
    // print = true 表示只用来作为显示使用
    print: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ""
    },
    isred: {
      type: Boolean,
      default: false
    },
    transfer: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    gradeRule: {
      type: Object,
      default() {
        return {};
      }
    },
    businessLineCode: {
      type: String,
      default: ""
    },
    placeholder: {
      type: String,
      default: "请选择"
    },
    veniclesUrl: {
      type: String,
      default: "", // /ems/ems-base-application/mams/sys/valueset/item/list/VEHICLE
      required: true
    },
    batchUrl: {
      type: String,
      default: "", // /ems/ems-base-application/mams/sys/valueset/item/batchlist/
      required: true
    },
    // Select组件是否要穿透，在一些情况下显示不了需要穿透
    isTransferSelect: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      index: 0,
      isShow: false,
      siteTop: 0,
      siteLeft: 0,
      popper: null,
      popperStatus: false,
      venicles: [],
      variclesObj: {},
      vehicleName: "",
      vehicleId: this.value,
      vehicleVal: [],
      grade: { 1: "3", 2: "3", 3: "5", 4: "3", 5: "20", 7: "1", 8: "3", 9: "3" },
      traffic: '',
      tgrade: '',
      isRedShow: this.isred,
      rid: parseInt(Math.random()*10000)
    };
  },
  created: function() {
    this.setItem();
    let venicles = JSON.parse(sessionStorage.getItem("venicles"));
    const variclesObj = JSON.parse(sessionStorage.getItem("variclesObj")) || {};
    const veniclesKeys = {
      1: "trainType",
      2: "highSpeedType",
      3: "shipType",
      4: "airType",
      7: "VEHICLE_LEVEL",
      8: "subway",
      9: "CRH",
      5: "SOFT_DEATS_TRAIN"
    };
    const codeList = "trainType,highSpeedType,shipType,airType,VEHICLE_LEVEL,subway,CRH,SOFT_DEATS_TRAIN";
    if (!venicles) {
      const queryValueSet = this.veniclesUrl;
      const queryBatchlist = `${this.batchUrl}?codeList=${codeList}`;
      axios.get(queryValueSet).then((response) => {
        const data = response.data;
        if (data.statusCode === '0') {
          venicles = [];
          for (const item of data.dataResult) {
            venicles.push({ label: item.vsiValue, value: item.vsiKey });
          }
          axios.post(queryBatchlist, {}).then((response2) => {
            if (response2.data.statusCode == '0') {
              const lecels = response2.data.dataResult;
              for (let i = 0; i < venicles.length; i++) {
                const vlecels = lecels[veniclesKeys[venicles[i].value + ""]] || [];
                const result = [];
                for (let j = 0; j < vlecels.length; j++) {
                  const item = vlecels[j];
                  result.push({ label: item.vsiValue, value: item.vsiKey, parentKey: item.vsiParentKey });
                }
                venicles[i].lecels = result;
                for (let j = 0; j < result.length; j++) {
                  variclesObj[venicles[i].value + "-" + result[j].value] = venicles[i].label + "-" + result[j].label;
                }
              }
              this.venicles = venicles;
              sessionStorage.setItem("venicles", JSON.stringify(venicles));
              this.variclesObj = variclesObj;
              sessionStorage.setItem("variclesObj", JSON.stringify(variclesObj));
              this.initValue();
            } else {
              this.$Message.error(response2.data.msg);
            }
          }).catch((error) => {
            this.$Message.error(error || '网络错误！');
          });
        } else {
          this.$Message.error(data.msg);
        }
      }).catch(err => this.$Message.error(err || '网络错误！'));
    } else {
      this.venicles = venicles;
      this.variclesObj = variclesObj;
      this.initValue();
    }
  },
  mounted() {
    if (this.transfer) {
      this.update();
    }
  },
  beforeDestroy: function() {
    if (this.popper) {
      this.popper.destroy();
    }
  },
  methods: {
    setItem() {
      const val = this.vehicleId || '';
      const data = val.split(',');
      const traffic = [];
      const tgrade = [];
      data.forEach(item => {
        traffic.push(item.split('-')[0]);
        tgrade.push(item.split('-')[1]);
      });
      this.traffic = traffic.join();
      this.tgrade = tgrade.join();
    },
    initValue() {
      this.vehicleVal = [];
      if (this.traffic) {
        const tids = [];
        const names = [];
        const gradeIds = {};
        const traffics = this.traffic.split(",");
        for (let j = 0; j < traffics.length; j++) {
          const traffic = traffics[j];
          for (let i = 0; i < this.venicles.length; i++) {
            if (traffic == this.venicles[i].value) {
              let id = "";
              if (this.tgrade) {
                const tgrades = this.tgrade.split(",");
                id = traffic + "-" + tgrades[j];
                gradeIds[traffic] = tgrades[j];
              } else {
                for (const name in this.grade) {
                  if (name == traffic) {
                    id = name + "-" + this.grade[name];
                    gradeIds[name] = this.grade[name];
                  }
                }
              }
              tids.push(id);
              names.push(this.variclesObj[id]);
            }
          }
        }
        for (let i = 0; i < tids.length; i++) {
          const tid = tids[i].split("-");
          if (this.vehicleVal.indexOf(tid[0]) < 0) {
            this.vehicleVal.push(tid[0]);
          }
          this.grade[tid[0]] = tid[1];
        }
        this.vehicleName = names.toString();
        this.vehicleId = tids.toString();
        this.$emit("input", this.vehicleId);
        this.$emit("selected", gradeIds);
      } else {
        this.vehicleName = "";
      }
    },
    vehicleChange: function(value) {
      this.setValue();
    },
    setValue() {
      const tids = [];
      const names = [];
      const gradeIds = {};
      for (let i = 0; i < this.vehicleVal.length; i++) {
        const vv = this.vehicleVal[i] + "";
        const lecel = this.getLecel(vv);
        let id = vv;
        if (lecel && lecel.length > 1) {
          for (const name in this.grade) {
            if (name == vv) {
              id += "-" + this.grade[name];
              gradeIds[name] = this.grade[name];
              break;
            }
          }
        } else if (lecel && lecel.length == 1) {
          id += "-" + lecel[0].value;
          gradeIds[vv] = lecel[0].value;
        }
        names.push(this.variclesObj[id]);
        tids.push(id);
      }
      this.vehicleName = names.toString();
      this.vehicleId = tids.toString();
      this.$emit("input", this.vehicleId);
      this.$emit("selected", gradeIds);
      this.$refs.vehicleIpt.focus();
    },
    gradeChange: function(value) {
      this.setValue();
    },
    getLecel: function(id) {
      for (let i = 0; i < this.venicles.length; i++) {
        if (this.venicles[i].value == id) {
          return this.venicles[i].lecels;
        }
      }
    },
    inputFocus: function() {
      if (this.disabled) {
        return false;
      }
      if (this.transfer) {
        this.update();
      }
      this.isShow = true;
    },
    inputBlur: function() {
    },
    closePlace: function() {
      this.isShow = false;
    },
    transferFix() {
      const $vehicleIpt = this.$refs.vehicleIpt.$el.getBoundingClientRect();
      this.$refs.popper.style.top = $vehicleIpt.top + $vehicleIpt.height + "px";
      this.$refs.popper.style.left = $vehicleIpt.left + "px";
    },
    update() {
      if (this.popper) {
        this.$nextTick(() => {
          this.popper.update();
          this.popperStatus = true;
        });
      } else if (!this.print) {
        this.$nextTick(() => {
          this.popper = new Popper(this.$refs.vehicleIpt.$el, this.$refs.popper, {
            placement: "bottom-start",
            modifiers: {
              computeStyle: {
                gpuAcceleration: false
              },
              preventOverflow: {
                boundariesElement: "window"
              }
            },
            onCreate: () => {
              this.resetTransformOrigin();
              this.$nextTick(this.popper.update());
            },
            onUpdate: () => {
              this.resetTransformOrigin();
            }
          });
        });
      }
    },
    destroy() {
      if (this.popper) {
        setTimeout(() => {
          if (this.popper && !this.popperStatus) {
            this.popper.destroy();
            this.popper = null;
          }
          this.popperStatus = false;
        }, 300);
      }
    },
    resetTransformOrigin() {
      if (!this.popper) return;
      const xPlacement = this.popper.popper.getAttribute("x-placement");
      const placementStart = xPlacement.split("-")[0];
      const placementEnd = xPlacement.split("-")[1];
      const leftOrRight = xPlacement === "left" || xPlacement === "right";
      if (!leftOrRight) {
        this.popper.popper.style.transformOrigin =
          placementStart === "bottom" || (placementStart !== "top" && placementEnd === "start")
            ? "center top"
            : "center bottom";
      }
    },
    setRedInputVal(){
      // 文本框变红 临时解决方案
      this.$nextTick(()=>{
        const $vehiclePopWrap = document.querySelector(`.vehiclePopWrap-${this.rid}`)
        if(Array.from($vehiclePopWrap.querySelectorAll(".ivu-checkbox-wrapper-checked .ivu-select-item-selected.vehicleValRed")).length){
          this.isRedShow = true;
        }else{
          this.isRedShow = false;
        }
      })
    }
  },
  watch: {
    value(val) {
      this.vehicleId = val;
      this.setItem();
      this.initValue();
    },
    vehicleName(){
      this.setRedInputVal()
    },
    gradeRule(val){
      if(val){
        this.setRedInputVal()
      }
    }
  }
};
</script>
<style lang="less">
.vehicleValRed{
  color: red;
}

html .ivu-form .select-vehicle-wrp .isred .ivu-input.ivu-input-default {
  color: red !important;
}
</style>
<style lang="less" scoped>
.select-vehicle-wrp {
  position: relative;
}
.h-ems-place {
  width: 250px;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 32px;
  left: 0;
  z-index: 999999;
}
.h-ems-place .h-ems-title {
  padding-left: 5px;
  background: #f5d07b;
  color: #444;
  height: 30px;
  line-height: 30px;
}
.h-ems-place .h-ems-content {
  background: #fff;
}
.h-ems-place .ivu-icon-ios-close-empty {
  font-size: 30px;
  position: absolute;
  top: 2px;
  right: 10px;
  cursor: pointer;
}
.ivu-checkbox-group-item {
  display: block;
  padding: 5px;
  border-bottom: 1px solid #e4e4e4;
}
.ivu-radio-group-vertical .ivu-radio-wrapper {
  display: inline-block;
  height: 15px;
  line-height: 15px;
}
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
