<template>
    <el-dialog :visible.sync="dialogTableVisible" class="ems-dialog" :title="mode === 'add'?'新增模板':`编辑模板` ">
      <el-form ref="addTempForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="formData.templateName" placeholder="请输入" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="soc限制" prop="sdcLimit" required>
          <el-switch :active-value="1" :inactive-value="0" v-model="formData.sdcLimit"></el-switch>
        </el-form-item>
<!--        <template v-if="formData.sdcLimit === 1">-->
          <el-form-item label="soc下限" prop="sdcDown">
            <el-input v-model="formData.sdcDown" placeholder="请输入" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="soc上限" prop="sdcUp">
            <el-input v-model="formData.sdcUp" placeholder="请输入" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
<!--        </template>-->
      </el-form>
      <el-button type="primary" size="mini" @click="addTime">新增</el-button>
<!--      新增时间段表单-->
      <el-collapse-transition>
          <el-card v-show="showAddTime" shadow="always" class="common-card-container" style="margin-top:25px;">
            <el-form class="add-time-form transition-box" ref="addTimeForm" :model="formInline" :rules="formInlineRule" label-width="100px" style="margin-top:25px">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-select
                placeholder="开始时间"
                v-model="formInline.startTime"
                :picker-options="{
                start: '00:00',
                step: '01:00',
                end: '23:00',
              }">
              </el-time-select>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-time-select
                placeholder="结束时间"
                v-model="formInline.endTime"
                :picker-options="{
                start: '00:00',
                step: '01:00',
                end: '23:00',
              }">
<!--                minTime: formInline.startTime-->
              </el-time-select>
            </el-form-item>
            <el-form-item label="冲放功率" prop="chargeDischargePower">
              <el-input v-model="formInline.chargeDischargePower" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="充电状态" prop="chargeStatus">
              <el-select v-model="formInline.chargeStatus" placeholder="请选择">
                <el-option v-for="(value,key) in chargeStatusOptions" :key="key+'chargeStatusOptions'" :label="value" :value="key"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="saveTime">保存</el-button>
              <el-button size="mini" @click="cancelAddTime">取消</el-button>
            </el-form-item>
          </el-form>
          </el-card>
      </el-collapse-transition>
      <el-table
        :data="tableData"
        border
        style="width: 100%;margin-top:25px">
        <!--            todo 如果要在span-method中使用column.property 在表格中必须定义prop="xxx"属性-->
        <el-table-column
          prop="startTime"
          label="开始时间">
        </el-table-column>
        <el-table-column
          prop="endTime"
          label="结束时间">
        </el-table-column>
        <el-table-column
          prop="chargeDischargePower"
          label="充放功率（kW）">
        </el-table-column>
        <el-table-column
          prop="chargeStatus"
          label="充电状态">
          <template slot-scope="scope">
            {{chargeStatusOptions[scope.row.chargeStatus]}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="120">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              type="warning"
              size="mini">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </div>
    </el-dialog>
</template>
<script>
import {mapState} from 'vuex'
import {addStrategyTemp,editStrategyTemp,getStrategyTempDetail} from '@/api/ems/dzjk'
export default {
  inject:['$home'],
  data() {
    return {
      mode:'',
      editTempId:'',
      dialogTableVisible:false,
      formData: {
        templateName: '',
        sdcLimit: false,
        sdcDown: '',
        sdcUp: '',
      },
      rules: {
        templateName: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }],
        sdcDown: [
          {required: true,message: '请输入', trigger: 'blur'},
          { pattern: /^(0|[1-9]\d*)(\.\d+)?$/, message: '请输入合法数字或小数' }
        ],
        sdcUp: [
          {required: true,message: '请输入', trigger: 'blur'},
          { pattern: /^(0|[1-9]\d*)(\.\d+)?$/, message: '请输入合法数字或小数' }
        ],
      },
      showAddTime: false,
      formInline:{
        startTime:'',endTime:'',chargeDischargePower:'',chargeStatus:''
      },
      formInlineRule:{
        startTime: [{
          required: true,
          message: '请选择开始时间',
          trigger: 'change'
        }],
        endTime: [{
          required: true,
          message: '请选择结束时间',
          trigger: 'change'
        }],
        chargeDischargePower: [{
            required: true,
            message: '请输入冲放功率',
            trigger: 'blur'
          },
          { pattern: /^(0|[1-9]\d*)(\.\d+)?$/, message: '请输入合法数字或小数' }
        ],
        chargeStatus:[{
          required: true,
          message: '请选择充放状态',
          trigger: ['blur','change']
          }
        ]
      },
      tableData:[],
    }
  },
  computed: {
    ...mapState({
      chargeStatusOptions: state => state?.ems?.chargeStatusOptions || {},
    })
  },
  watch: {
    "formInline.startTime":{
      handler(newVal,oldVal){
        if(newVal && this.formInline.endTime){
          const endTime = parseInt((this.formInline.endTime).split(':')[0] || 0)
          const startTime =parseInt(newVal.split(':')[0])
          if(endTime<=startTime){
            this.formInline.endTime = `${startTime+1 <=9 ? '0'+(startTime+1) : startTime+1}:00`
          }
        }
      },
      deep:true
    },
  },
  methods: {
    changeSiteId(){
      this.dialogTableVisible=false
      this.mode=''
      this.editTempId=''
      this.formData={
        templateName: '',
        sdcLimit: false,
        sdcDown: '',
        sdcUp: '',
      }
      this.formInline={
        startTime:'',endTime:'',chargeDischargePower:'',chargeStatus:''
      }
      this.showAddTime = false
      this.tableData=[]
    },
    show({mode = 'add', editTempId = ''}){
      this.$nextTick(() => {
        this.dialogTableVisible = true
        this.mode = mode
        this.editTempId=editTempId
        if(mode === 'edit' && editTempId){
          getStrategyTempDetail(this.editTempId).then(response => {
            const data=JSON.parse(JSON.stringify(response?.data || []));
            if(data.length>0){
              const {templateName,sdcLimit,sdcDown,sdcUp} =JSON.parse(JSON.stringify( data[0]));
              this.formData.templateName=templateName
              this.formData.sdcLimit=sdcLimit
              this.formData.sdcDown=sdcDown
              this.formData.sdcUp=sdcUp
            }
            if(data.length === 1){
              const {startTime,endTime}=data;
              if(!startTime || !endTime){
                this.tableData = []
              }else{
                this.tableData= data
              }
            }else{
              this.tableData= data
            }
          })
        }
      })
    },
    addTime(){
      this.showAddTime=true
    },
    cancelAddTime(){
      this.$refs.addTimeForm.resetFields()
      this.showAddTime=false
      this.formInline = {startTime:'',endTime:'',chargeDischargePower:'',chargeStatus:''}
    },
    saveTime(){
      //表单校验，校验成功，添加到tableData里
      this.$refs.addTimeForm.validate(valid => {
        if (!valid) return
        this.tableData.push(JSON.parse(JSON.stringify(this.formInline)));
        this.$nextTick(() => {this.cancelAddTime()})
      })
    },
    deleteRow(index, table){
      this.tableData.splice(index,1)
    },
    saveDialog() {
      this.$refs.addTempForm.validate(valid => {
        if (!valid) return
        const {templateName,sdcLimit,sdcDown,sdcUp} = this.formData
        const {siteId,updateStrategyId} =this.$home
        const {tableData} = this
        if(this.mode==='edit'){
          editStrategyTemp({siteId,strategyId:updateStrategyId,templateId:this.editTempId,templateName,sdcLimit,sdcDown,sdcUp,timeConfigList:tableData}).then(response=>{
            if(response?.code === 200){
              this.closeDialog()
              this.$emit('update')
              this.$emit('updateTimeSetting')
            }
          })
        }else{
          addStrategyTemp({siteId,strategyId:updateStrategyId,templateName,sdcLimit,sdcDown,sdcUp,timeConfigList:tableData}).then(response=>{
            if(response?.code === 200){
              this.closeDialog()
              this.$emit('update')
            }
          })
        }

      })
    },
    closeDialog(){
      // 清空所有数据
      this.$refs.addTempForm.resetFields()
      this.formData={
        templateName: '',
          sdcLimit:0,
          sdcDown: '',
          sdcUp: '',
      }
      this.tableData=[]
      this.cancelAddTime()
      this.dialogTableVisible=false
    }
  }
}

</script>
