<template>
  <div class="vbe-balancing">
    <el-row :gutter="20">
      <el-col :sm="24">
        <el-form-item
          label="Load Balancing Type:"
          label-width="160px">
          <el-select
            style="max-width: 150px;"
            v-model="balancingForm.loadBalancing"
            @change="changeBalance">
            <el-option
              v-for="(item,index) in balancingTypes"
              :key="index"
              :label="item"
              :value="item"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-if="balancingForm.loadBalancing == 'static'">
      <el-col :sm="24">
        <el-form-item
          label="Max Current At Site:"
          label-width="160px">
          <el-input
            style="max-width: 100px;"
            v-model.number="balancingForm.staticMaxAmpere"
            maxlength="5"
            @change="changeAmpere"/>
          <span class="text-unit">A</span>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row
      :gutter="30"
      v-for="(item, index) in balancingForm.siteChargingProfiles"
      :key="index">
      <el-col :sm="8" :md="7" :lg="6">
        <el-form-item
          label="Chargers In-Use:"
          label-width="130px">
          <el-select
            v-model="item.boxInUse"
            @change="changeInUse(index)">
            <el-option
              v-for="(item, idx) in boxUseOptions"
              :key="idx"
              :label="item"
              :value="item"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :sm="10" :md="9" :lg="8">
        <el-form-item
          label="Charging Profile:"
          label-width="130px">
          <el-select 
            v-model="item.chargingProfilePk"
            v-if="balancingForm.loadBalancing == 'static' && balancingPrifileList[index]"
            filterable
            v-loading="balancingPrifileList[index].loading">
            <el-option
              v-for="(item,idx) in balancingPrifileList[index].options"
              :key="idx"
              :label="item.description"
              :value="item.chargingProfilePk"/>
          </el-select>
          <el-select
            v-model="item.chargingProfilePk"
            v-else
            filterable>
            <el-option
              v-for="(item,idx) in chargingProfileOptions"
              :key="idx"
              :label="item.description"
              :value="item.chargingProfilePk"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :sm="6" :md="5" :lg="4">
        <img
          class="list-item-icon"
          @click="handelSubSiteChargingProfiles(index)"
          src="../../../assets/form-list-sub.png"/>
        <img
          v-if="balancingForm.siteChargingProfiles.length - 1 === index"
          class="list-item-icon"
          @click="handleAddSiteChargingProfiles"
          src="../../../assets/form-list-add.png"/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import site from '../../../http/api/site'
export default {
  name: "Balancing",
  props: {
    value: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      balancingTypes: [],
      boxUseOptions: [1,2,3,4,5,6,7,8,9,10],
      chargingProfileOptions: [],
      balancingPrifileList: [{
        loading: false,
        options: []
      }],
      balancingForm: {
        loadBalancing: 'dynamic',
        staticMaxAmpere: 0,
        siteChargingProfiles: [{
          boxInUse: '',
          chargingProfilePk: '',
          siteChargingProfileId: ''
        }]
      },
      oldConfig: {
        dynamic: [],
        static: []
      }
    }
  },
  watch: {
    value: {
      deep: true,
      handler(n, o) {
        this.balancingForm = n;
        this.init()
      }
    }
  },
  mounted() {
    this.balancingForm = this.value
    this.getBalancingTypeOptions()
    this.getChargingProfileOptions()
  },
  methods: {
    init() {
      if (this.balancingForm.siteChargingProfiles.length === 0) {
        this.handleAddSiteChargingProfiles()
      }
      this.$nextTick(() => {
        if (this.isEdit && this.balancingForm.loadBalancing == "static") {
          this.balancingForm.siteChargingProfiles.forEach((item, index) => {
            if (this.balancingPrifileList[index] == undefined) {
              this.addBalancingPrifileList()
            }
          })
          this.getAllBalancingChargingProfiles()
        }
      })
    },
    onChange() {
      //console.log(event);
      this.$emit('change', this.balancingForm);
    },
    /**
     * 切换均衡类型
     */
    changeBalance() {
      let list = [];
      if (this.balancingForm.loadBalancing == "dynamic") {
        this.oldConfig.static = [...this.balancingForm.siteChargingProfiles];
        list = this.oldConfig.dynamic;
      } else {
        this.oldConfig.dynamic = [...this.balancingForm.siteChargingProfiles];
        list = this.oldConfig.static
      }
      if (list.length > 0) {
        this.balancingForm.siteChargingProfiles = list;
      } else {
        this.balancingPrifileList = [];
        this.balancingForm.staticMaxAmpere = 0;
        this.balancingForm.siteChargingProfiles = [];
        this.handleAddSiteChargingProfiles()
        this.onChange()
      }
    },
    /**
     * 改变最大电流输入值
     */
    changeAmpere() {
      if (this.balancingForm.staticMaxAmpere == "" || typeof this.balancingForm.staticMaxAmpere == 'string') {
        this.balancingForm.staticMaxAmpere = 0;
      }
      this.getAllBalancingChargingProfiles(true)
      /*this.balancingForm.siteChargingProfiles = [];
      this.handleAddSiteChargingProfiles()*/
    },
    /**
     * 改变InUse下拉框
     * @param {Object} index ChargeProfile项目索引
     */
    changeInUse(index) {
      if (this.balancingForm.loadBalancing == 'static') {
        this.balancingForm.siteChargingProfiles[index].chargingProfilePk = "";
        this.getBalancingChargingProfiles(index)
      }
    },
    /**
     * 获取均衡类型选项
     */
    getBalancingTypeOptions() {
      site.getBalancingOptions().then(({ data }) => {
        this.balancingTypes = data
      })
    },
    /**
     * 获取充电配置选项
     */
    getChargingProfileOptions() {
      site.getChargingProfiles().then(({ data }) => {
        this.chargingProfileOptions = data
      })
    },
    addBalancingPrifileList() {
      this.balancingPrifileList.push({
        options: [],
        loading: false
      })
    },
    /**
     * 遍历获取均衡充电配置选项
     * @param {Object} clear 是否清除之前的选项
     */
    getAllBalancingChargingProfiles(clear) {
      this.balancingPrifileList.forEach((item, index) => {
        if (clear) {
          this.balancingForm.siteChargingProfiles[index].chargingProfilePk = ""
        }
        if (clear || item.options.length == 0) {
          this.getBalancingChargingProfiles(index)
        }
      })
    },
    /**
     * 动态获取均衡充电配置选项
     */
    getBalancingChargingProfiles(index) {
      if (this.balancingForm.siteChargingProfiles[index].boxInUse && this.balancingForm.staticMaxAmpere > 0) {
        this.balancingPrifileList[index].loading = true;
        site.getBalancingChargingProfiles({
          inUse: this.balancingForm.siteChargingProfiles[index].boxInUse,
          loadBalancing: this.balancingForm.loadBalancing,
          staticMaxAmpere: this.balancingForm.staticMaxAmpere
        }).then(({ data }) => {
          this.balancingPrifileList[index].options = data
        }).finally(() => {
          this.balancingPrifileList[index].loading = false
        })
      }
    },
    updateSubSiteChargingProfiles(index) {
      const item = this.balancingForm.siteChargingProfiles[index]
      this.$confirm('Are you sure you want to delete this config?', 'Delete', {
        confirmButtonText: 'Ok',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }).then(() => {
        if (item.siteChargingProfileId) {
          site.deleteChargingProfile(item.siteChargingProfileId).then(res => {
            
          })
          this.balancingForm.siteChargingProfiles.splice(index, 1)
          this.balancingPrifileList.splice(index, 1)
          if (this.balancingForm.siteChargingProfiles.length === 0) {
            this.handleAddSiteChargingProfiles()
          }
        } else {
          this.balancingForm.siteChargingProfiles.splice(index, 1)
          this.balancingPrifileList.splice(index, 1)
          if (this.balancingForm.siteChargingProfiles.length === 0) {
            this.handleAddSiteChargingProfiles()
          }
        }
      })
    },
    handelSubSiteChargingProfiles(index) {
      if (this.isEdit) {
        return this.updateSubSiteChargingProfiles(index);
      }
      this.balancingForm.siteChargingProfiles.splice(index, 1)
      this.balancingPrifileList.splice(index, 1)
      if (this.balancingForm.siteChargingProfiles.length === 0) {
        this.handleAddSiteChargingProfiles()
      } else {
        //this.onChange();
      }
    },
    handleAddSiteChargingProfiles() {
      this.balancingForm.siteChargingProfiles.push({
        boxInUse: '',
        chargingProfilePk: ''
      })
      if (this.balancingForm.loadBalancing == 'static') {
        this.balancingPrifileList.push({
          options: [],
          loading: false
        })
        this.addBalancingPrifileList()
        this.getAllBalancingChargingProfiles()
      }
      //this.onChange();
    }
  }
}
</script>

<style lang="scss">
  .vbe-balancing {
    .list-item-icon {
      width: 30px;
      height: 30px;
      cursor: pointer;
      margin: 5px 10px 22px;
    }
    .el-input {
      min-width: 60px;
    }
    .text-unit {
      font-size: 14px;
      margin-left: 10px;
    }
  }
</style>