<template>
  <div class="automation-control">
    <!-- 自动化控制排水系统开关 -->
    <el-card>
      <div class="control-header">
        <span>自动化控制排水系统</span>
        <el-switch
          v-model="formData.status"
          active-text="已开启"
          inactive-text="已关闭"
          active-value="1"
          inactive-value="0"
          @change="handleStatusChange"
        ></el-switch>
      </div>
    </el-card>
    <!-- 峰谷值时间段设置 -->
    <el-card>
      <div class="section">
        <h3>设置峰谷值时间段</h3>
        <el-time-picker
          is-range
          v-model="timeRange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          @change="handleTimeRangeChange"
        ></el-time-picker>
      </div>
      <el-divider></el-divider>
      <!-- 液体高度设置 -->
      <div class="section">
        <h3>设置液体高度 <el-link type="primary" :underline="false" @click="setDis">设置说明</el-link></h3>
        
        <!-- 每个水仓的设置 -->
        <div v-for="(sump, index) in formData.draPeakSumpVos" :key="sump.sumpId">
          <div class="sump-item">
            <div class="sump-header">
              <span>{{ sump.sumpName }}液位高度（m）：</span>
            </div>
            
            <div class="threshold-inputs">
              <div class="threshold-item">
                <span>A点值</span>
                <el-input v-model="sump.heghtThresholdA" placeholder="请输入A点值" size="small"></el-input>
              </div>
              <div class="threshold-item">
                <span>B点值</span>
                <el-input v-model="sump.heghtThresholdB" placeholder="请输入B点值" size="small"></el-input>
              </div>
              <div class="threshold-item">
                <span>C点值</span>
                <el-input v-model="sump.heghtThresholdC" placeholder="请输入C点值" size="small"></el-input>
              </div>
              <div class="threshold-item">
                <span>D点值</span>
                <el-input v-model="sump.heghtThresholdD" placeholder="请输入D点值" size="small"></el-input>
              </div>
            </div>
            
            <div class="pump-selection">
              <span>对应控制水泵：</span>
              <div class="pump-checkboxes">
                <el-checkbox
                  v-for="pump in sump.draPeakPumpVos"
                  :key="pump.pumpId"
                  v-model="pump.pumpStatus"
                  :true-label="1"
                  :false-label="0"
                  size="small"
                >
                  {{ pump.pumpName }}
                </el-checkbox>
              </div>
            </div>
          </div>
          
          <el-divider v-if="index < formData.draPeakSumpVos.length - 1"></el-divider>
        </div>
      </div>

      <!-- 按钮区域 -->
      <div class="button-group">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存设置</el-button>
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
        <div class="warter-lev">
          <div class="lev-pic"></div>
          <div class="lev-content">
            <p>①液位高度X>A时，不考虑是否在峰谷时间，自动开启水泵。</p>
            <p>如果未在峰谷期内液压高度X<=B时，关闭水泵。</p>
            <p>如果在峰谷期内液压高度X<=D时,关闭水泵。</p>
            <p>②A>=X（液压高度）X<=C时，等待峰谷期内，自动开启水泵。</p>
            <p>液压高度X<=D时，自动关闭水泵。</p>
          </div>
        </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { peakGetDra, peakEditDra } from "@/api/tyler/sys";

export default {
  name: 'AutomationControl',
  data() {
    return {
      open: false,
      formData: {
        status: "1", // 默认开启
        peakBeginTime: '',
        peakEndTime: '',
        draPeakSumpVos: []
      },
      timeRange: [],
      title:'液位高度设置说明：'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      peakGetDra().then(res => {
        const data = res.data;
        
        // 保存原始水泵顺序
        this.originalPumpOrder = new Map();
        data.draPeakSumpVos.forEach((sump, sumpIndex) => {
          this.originalPumpOrder.set(sumpIndex, sump.draPeakPumpVos.map(p => p.pumpId));
        });

        // 处理数据时保持原始顺序
        data.draPeakSumpVos = data.draPeakSumpVos.map((sump, sumpIndex) => {
          const orderedPumps = [];
          const originalOrder = this.originalPumpOrder.get(sumpIndex);
          
          // 按照原始顺序重新排列水泵
          originalOrder.forEach(pumpId => {
            const found = sump.draPeakPumpVos.find(p => p.pumpId === pumpId);
            if (found) {
              orderedPumps.push({
                ...found,
                pumpStatus: parseInt(found.pumpStatus, 10)
              });
            }
          });

          return {
            ...sump,
            draPeakPumpVos: orderedPumps
          };
        });

        this.formData = data;
        this.timeRange = [data.peakBeginTime, data.peakEndTime];
      });
    },
    handleStatusChange(value) {
      console.log('自动化控制状态已切换为:', value);
    },
    handleTimeRangeChange(value) {
      if (value && value.length === 2) {
        this.formData.peakBeginTime = value[0];
        this.formData.peakEndTime = value[1];
      }
    },
    handleCancel() {
      this.getList(); // 重新获取数据重置表单
    },
    handleSave() {
      // 深拷贝时保持数组顺序
      const postData = {
        ...this.formData,
        draPeakSumpVos: this.formData.draPeakSumpVos.map(sump => ({
          ...sump,
          draPeakPumpVos: sump.draPeakPumpVos.map(pump => ({
            ...pump,
            pumpStatus: pump.pumpStatus.toString()
          }))
        }))
      };

      peakEditDra(postData).then(res => {
        this.$message.success('设置保存成功');
        this.getList();
      });
    },
    setDis(){
      this.open = true;
    },
  }
};
</script>

<style lang="scss" scoped>
.pump-checkboxes {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.automation-control {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.control-header {
  display: flex;
  align-items: center;
  justify-content: start;
  gap: 20px;
  span{
    font-weight: bold;
  }
}

.section {
  margin-bottom: 20px;
}

.section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
  font-weight: bold;
}

.sump-item {
  margin-bottom: 20px;
}

.sump-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.threshold-inputs {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.threshold-item {
  display: flex;
  align-items: center;
}

.threshold-item span {
  width: 60px;
}

.pump-selection {
  display: flex;
  align-items: center;
  gap: 10px;
}

.button-group {
  display: flex;
  justify-content: start;
  gap: 15px;
  margin-top: 20px;
}
.warter-lev{
  display: flex;
  justify-content: center;
  .lev-pic{
    width: 105px;
    height: 343px;
    background: url("~@/assets/images/sys/warterSysSet.png") no-repeat center;
    background-size: 100%;
  }
  .lev-content{
    height: 343px;
    display: flex;
    justify-content: center;
    // align-items: center;
    flex-direction: column;
    font-weight: bold;
  }
}
::v-deep .el-date-editor .el-range-separator {
  width: 30px;
}
</style>