<template>
  <div class="ems-dashboard-editor-container" style="background-color: #ffffff" v-loading="loading">
    <el-form :inline="true" class="select-container">
      <el-form-item label="站点选择">
        <el-select v-model="siteId" placeholder="请选择换电站名称" :loading="searchLoading" loading-text="正在加载数据" @change="onSearch" clearable>
          <el-option :label="item.siteName" :value="item.siteId" v-for="(item,index) in siteList" :key="index+'zdxeSelect'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年份选择">
        <el-date-picker
            v-model="defaultYear"
            type="year"
            :clearable="false"
            placeholder="请选择年份"
            align="center"
            format="yyyy年"
            value-format="yyyy"
            @change="changeDefaultYear"
          >
        </el-date-picker>
      </el-form-item>
      <br>
      <el-form-item>
        <el-button type="primary" @click="addPowerConfig('')">新增电价配置</el-button>
      </el-form-item>
    </el-form>
    <div class="month-lists-container" v-infinite-scroll="getData" infinite-scroll-immediate="false">
      <el-empty v-show="tableData.length<=0" :image-size="200"></el-empty>
      <el-card
          shadow="always"
          class="common-card-container time-range-card"
          v-for="item in tableData"
          :key="item.id"
      >
        <div slot="header" class="time-range-header">
          <span class="card-title">{{siteList.find(i=>i.siteId===item.siteId).siteName || item.siteId || ''}}-{{item.month}}月电价时段划分</span>
          <div>
            <el-button type="primary" size="mini" @click="addPowerConfig(item.id)">编辑</el-button>
            <el-button type="warning" size="mini" @click="deletePowerConfig(item)">删除</el-button>
          </div>
        </div>
        <div class="price-table-container">
          <div class="price-table">
            <div class="time-list">
              <div class="time"> </div>
              <div class="type">时段</div>
              <div class="price">电价（元/kWh）</div>
            </div>
            <div class="time-list" v-for="(rangeItem,rangeIndex) in item.range" :key="rangeIndex+'price'">
              <div class="time">{{`${rangeItem.startTime}-${rangeItem.endTime}`}}</div>
              <div class="type">{{priceTypeOptions[rangeItem.costType]}}</div>
              <div class="price">{{item[rangeItem.costType]}}</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <add-power-tariff ref="addPowerTariff" @update="getData(true)"/>
  </div>
</template>

<script>
import {energyPriceConfig,listPriceConfig} from '@/api/ems/powerTariff'
import {getAllSites} from '@/api/ems/zddt'
import AddPowerTariff from './AddPowerTariff.vue'
import DateTimeSelect from "@/views/ems/search/DateTimeSelect.vue";
export default {
  name: "PowerTariff",
  components: {DateTimeSelect, AddPowerTariff},
  computed: { },
  data() {
    return {
      loading:false,
      pageNum:1,
      pageSize:40,
      searchLoading:false,
      siteId:'',
      siteList:[],
      tableData:[],
      tableTotal:0,
      defaultYear:'',
      pickerOptions:{
        disabledDate(time) {
          return time.getFullYear() >= new Date().getFullYear()+1;
        },
      },
      priceTypeOptions:{
        'peak':'尖',
        'high':'峰',
        'flat':'平',
        'valley':'谷'
      },
    }
  },
  methods:{
    resetTableData(){
      this.tableData=[]
      this.tableTotal=0
      this.pageNum=1
    },
    // 搜索
    onSearch(){
      this.getData(true)
    },
    //获取站点列表
    getZdList(){
      this.searchLoading=true
      getAllSites().then(response => {
        this.siteList = response?.data || []
      }).finally(() => {this.searchLoading=false})
    },
    changeDefaultYear(){
      this.getData(true)
    },
    getData(reset=false){
      reset && this.resetTableData()
      console.log('湖区====',reset,this.tableData.length,this.tableTotal,this.pageNum);
      if(!reset && this.tableData.length>=this.tableTotal) return
      this.loading=true;
      const date = new Date(this.defaultYear).getFullYear()
      const startTime = date+'-01',endTime = date+'-12'
      listPriceConfig({startTime,endTime,pageNum:this.pageNum,pageSize:this.pageSize,siteId:this.siteId}).then(response => {
        const data = JSON.parse(JSON.stringify(response?.rows || []))
        data.length > 0 && (this.pageNum += 1)
        this.tableData.push(...data)
        this.tableTotal=response?.total || 0
      }).finally(() => {this.loading=false})
    },
    addPowerConfig(id=''){
      this.$refs.addPowerTariff.showDialog(id);
    },
    deletePowerConfig(row){
      this.$confirm(`确认要删除${row.month}月的电价配置吗?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose:false,
        closeOnClickModal:false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            energyPriceConfig(row.id).then(response => {
              response.code === 200 && done();
            }).finally(() => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      }).then(() => {
        //只有在废弃成功的情况下会走到这里
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData(true)
        //调用接口 更新表格数据
      }).catch(() => {
        //取消关机
      });
    },
  },
  mounted() {
    this.defaultYear = new Date()
    this.getZdList()
    this.getData(true)
  }
}
</script>

<style lang="scss" scoped>
.month-lists-container{
  max-height:100vh ;
  overflow-y: auto;
}
.common-card-container{
  width: 100%;
  margin-top: 20px;
}
.price-table-container{
  overflow-x: auto;
  .price-table{
    border:1px solid #eee;
    width: fit-content;
    overflow-x: auto;
    display: flex;
    .time-list{
      &:not(:first-child){
        border-left:1px solid #eee;
      }
      text-align: center;
      width: 140px;
      &>div{
        height: 30px;
        font-size: 12px;
        line-height: 30px;
        color:#000;
        &.time,&.type{
          border-bottom: 1px solid #eee;
        }
      }
    }
  }
}
</style>
