//选择年月 配置尖峰平谷对应的电价 配置24小时选择对应的尖峰平谷
<template>
  <div>
    <el-dialog v-loading="loading" width="780px" :visible.sync="dialogTableVisible" class="ems-dialog" title="电价配置" :close-on-click-modal="false" :show-close="false">
      <div class="items-container">
        <div class="item-title">站点:</div>
        <div class="item-content">
          <el-select v-model="siteId" :disabled="mode === 'edit'" placeholder="请选择站点" :loading="searchLoading" loading-text="正在加载数据">
            <el-option :label="item.siteName" :value="item.siteId" v-for="(item,index) in siteList" :key="index+'zdxeSelect'"></el-option>
          </el-select>
        </div>
      </div>
      <div class="items-container">
        <div class="item-title">时间:</div>
        <div class="item-content">
          <el-date-picker
              v-model="powerDate"
              format="yyyy-MM"
              value-format="yyyy-MM"
              type="month"
              placeholder="请选择月份"
              :disabled="mode === 'edit'"
          >
          </el-date-picker>
        </div>
      </div>
      <div style="display: flex">
        <div class="items-container price-types" v-for="item in priceTypeOptions" :key="item.id">
          <div class="item-title">{{item.name}}:</div>
          <div class="item-content">
            <el-input
                placeholder="请输入价格"
                v-model="item.price">
            </el-input>
          </div>
        </div>
      </div>
      <div class="items-container">
        <div class="item-title">
            <el-button
              @click.native.prevent="addRow"
              block
              type="primary"
              size="mini">
            新增时间段配置
          </el-button>
        </div>
        <div class="item-content">
          <div class="time-lists-container">
            <div class="time-lists time-lists-title">
              <div>开始时间</div>
              <div>结束时间(不包括)</div>
              <div>电价</div>
              <div>操作</div>
            </div>
            <div class="time-lists" v-for="(item,index) in hoursOptions" :key="'hoursOptions'+index">
              <div>
                <el-time-select
                    placeholder="开始时间"
                    v-model="item.startTime"
                    :picker-options="{
                        start: '00:00',
                        step: '01:00',
                        end: '23:00',
                    }">
                </el-time-select>
              </div>
              <div>
                <el-time-select
                  placeholder="结束时间"
                  v-model="item.endTime"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '24:00',
                    minTime: item.startTime
                  }">
                </el-time-select>
              </div>
              <div>
                <el-select v-model="item.costType" placeholder="请选择">
                  <el-option v-for="(value,key) in priceTypeOptions" :key="key+'priceTypeOptions'" :label="value.name" :value="value.id"></el-option>
                </el-select>
              </div>
              <div>
                <el-button
                    @click.native.prevent="deleteRow(index)"
                    type="warning"
                    size="mini">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addPriceConfig,editPriceConfig,detailPriceConfig} from '@/api/ems/powerTariff'
import {getAllSites} from '@/api/ems/zddt'
export default {
  data() {
    return {
      mode:'',
      id:'',
      searchLoading:false,
      siteId:'',
      siteList:[],
      powerDate:'',//时间
      //尖-peak,峰-high,平-flat,谷=valley
      priceTypeOptions:[{
        id:'peak',
        name:'尖',
        price:''
      },{
        id:'high',
        name:'峰',
        price:''
      },{
        id:'flat',
        name:'平',
        price:''
      },{
        id:'valley',
        name:'谷',
        price:''
      }],
      hoursOptions:[],
      loading:false,
      dialogTableVisible:false,
    }
  },
  methods: {
    addRow(){
      this.hoursOptions.push({
        startTime:'',
        endTime:'',
        costType:''
      })
    },
    deleteRow(index){
      this.hoursOptions.splice(index,1)
    },
    //获取站点列表
    getZdList(){
      this.searchLoading=true
      getAllSites().then(response => {
        this.siteList = response?.data || []
      }).finally(() => {this.searchLoading=false})
    },
    showDialog(id){
      this.getZdList()
      this.id = id
      if(id) {
        this.mode='edit'
        //获取详情 初始化hoursOptions
        this.loading = true
        detailPriceConfig(id).then(response => {
          const data = response?.data || {}
          this.siteId = data?.siteId || ''
          this.hoursOptions = data?.range || []
          this.powerDate=data?.year && data?.month  ? data.year +'-'+data.month : ''
          this.priceTypeOptions.forEach(item=>{
            item.price = data[item.id]
          })
        }).finally(()=>this.loading = false)
      }else {
        this.mode='add'
      }
      this.dialogTableVisible=true
    },
    saveDialog() {
      if(this.siteId === '') return this.$message.error('请选择站点')
      if(this.powerDate === '') return this.$message.error('请选择时间')
      let priceArr=[]
      this.priceTypeOptions.forEach(item=>{
        !['0',0].includes(item.price) && !item.price && priceArr.push(item.name)
      })
      if(priceArr.length>0) return this.$message.error(`请配置${priceArr.join(',')}的电价`)

      if(this.hoursOptions.length<=0) return this.$message.error(`请配置24小时的电价`)
      let hours=false,hourDis=false
      this.hoursOptions.forEach(item=>{
        if(!item.startTime || !item.endTime || !item.costType ) hours=true
        if(parseInt(item.startTime)>=parseInt(item.endTime)) hourDis=true
      })
      if(hours) return this.$message.error(`时间段电价配置错误`)
      if(hourDis)  return this.$message.error(`结束时间要大于开始时间`)
      let hoursMap={}
      this.hoursOptions.forEach(item=>{
        let s = parseInt(item.startTime),e=parseInt(item.endTime)
        for(s;s<e;s++){
          if(!hoursMap[s]) hoursMap[s]=1
          else hoursMap[s]+=1
        }
      })
      console.log('hoursMap======',hoursMap)
      if(Object.values(hoursMap).length<24 || Object.values(hoursMap).find(i=>i>1)) return this.$message.error(`请配置24小时的电价且时间不能重复`)
      const {powerDate,priceTypeOptions,hoursOptions,mode,id,siteId} =this
      this.loading = true
      let params={
        year:powerDate.split('-')[0],
        month:parseInt(powerDate.split('-')[1]),
        range:hoursOptions,
        siteId,
      }
      priceTypeOptions.forEach(item=>{params[item.id]=item.price})
      if(mode === 'edit') params.id = id
      console.log('参数=======',params)
      //调接口传数据 区分新增还是修改 成功之后关闭弹窗 更新表格
      if(mode === 'add'){
        addPriceConfig(params).then(response => {
          if(response.code === 200){
            this.$emit('update')
            this.closeDialog()
          }else{
            this.$message.error('新增失败')
          }
        }).finally(() => {
          this.loading = false
        })
      }else{
        editPriceConfig(params).then(response => {
          if(response.code === 200){
            this.$emit('update')
            this.closeDialog()
          }else{
            this.$message.error('修改失败')
          }
        }).finally(() => {
          this.loading = false
        })
      }
    },
    closeDialog(){
      // 清空所有数据
      this.$emit('clear')
      this.mode=''
      this.id=''
      this.siteId=''
      this.siteList=[]
      this.searchLoading=false
      this.powerDate=''
      this.hoursOptions=[]
      this.priceTypeOptions.forEach(item=>{
        item.price=''
      })
      this.dialogTableVisible=false
    }
  },
}

</script>

<style scoped lang="scss">
.items-container{
  margin-bottom: 20px;
  .item-title{
    line-height: 16px;
    padding: 10px 0;
    color: #000;
  }
}
.price-types{
  width: 150px;
  &:not(:last-child){
    margin-right: 20px;
  }
}
.time-lists-container{
  width: 100%;
  border:1px solid #eee;
  .time-lists{
    &:not(:last-child){
      border-bottom: 1px solid #eee;
    }
    display: flex;
    &>div{
      width: 16%;
      box-sizing: border-box;
      text-align: center;
      padding: 10px 15px;
      &:not(:last-child){
        width: 28%;
        border-right: 1px solid #eee;
      }
      .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
      }
    }
  }
  .time-lists-title{
    color: #000;
    font-size: 12px;
    font-weight: bold;
    line-height: 20px;
  }
}

</style>