<template>
  <div class="app-container home">
    <el-button type="primary" :icon="Download" @click="drawerIshow = true">策略导入</el-button>
    <div class="dev_control_wrapper">


      <div class="dev_control_item" v-for="item in deviceArr" :key="item.deviceId">
        <div class="item_header">
          <span>{{ item.deviceName}}</span>
          <el-switch :disabled="item.isControl == 2 ? flase : true"
                     v-model="item.deviceRunstatus"
                     @change="handleDevChangeFun(item.deviceId,item.deviceRunstatus)"
                     class="switch" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dddddd"/>
        </div>
        <div class="item_bottom">
          <div class="item_bottom_img">
            <img :src="item.photoUrl" alt="">
          </div>
          <div class="item_bottom_form">
            <el-form :model="form1">
              <el-form-item label="当前状态" label-width="96px">
                <span :class="{'green':item.deviceRunstatus === true,'red':item.deviceRunstatus === false}">
                  {{ item.deviceRunstatus === true ? '正在运行' : '停止运行'}}
                </span>
              </el-form-item>

              <el-form-item v-for="inputs in item.control_elements" :label="inputs.controlRemark"><input class="tempInput" v-model="inputs.tempValue"/></el-form-item>
<!--              <el-form-item v-for="inputs in item.control_elements" :label="inputs.controlRemark"><input class="tempInput"/></el-form-item>-->

              <div class="submit" v-show="item.control_elements.length > 0 ? true : false"  @click="getSetTemperatureFun(item)">确定</div>

            </el-form>
          </div>
        </div>
      </div>


    </div>
    <div class="dev_control_table">
      <div class="control_header"><span>调控日志</span></div>
      <div class="control_table">
        <el-table :data="controlLogList" height="305px">
          <el-table-column label="序号" type="index" :index="indexMethod1" width="60"></el-table-column>
          <el-table-column label="设备名称" align="center" prop="deviceName"/>
          <el-table-column label="操作内容" align="center" prop="controlValue" width="700" :formatter="formatControlKeyValue"/>
          <el-table-column label="操作时间" align="center" prop="createTime"/>
          <el-table-column label="操作人员" align="center" prop="createBy"/>
          <el-table-column label="操作结果" align="center" prop="controlContext"  :formatter="formatControlResult"></el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableLength"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
      </div>
    </div>

    <el-drawer v-model="drawerIshow">
      <template #header><h4>策略导入</h4></template>
      <template #default>
          <el-radio v-for="(item,index) in celueList" :key="index" class="celueBox" v-model="radio" :label="item.sceneName" size="large" @change="selectCeLue(item)">
          <span style="font-weight: bold; display: inline-block; margin-bottom: 20px;">{{ item.sceneName }}</span>
          <div class="celueItem" v-for="items in item.data" :key="items.device_id">
            <span>{{ items.device_name }}</span>
            <div class="itemsValue">
              <span class="txtInput" v-for="itemsValue in items.value" :key="itemsValue.sceneKey">
                <span class="txt">{{ itemsValue.sceneContext }}：</span>
                <input type="text" :value="`${itemsValue.sceneValue}℃`" disabled/>
              </span>
            </div>
          </div>
        </el-radio>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="confirmClick">执行</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Index">
import { Download } from '@element-plus/icons-vue'  //element字体图标
import { ref,reactive,onMounted } from 'vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import { getDevice,getControlLogList,getStrategyList,getStartAndStop,getSetTemperature,getSenceControl,getControlDeviceList } from '@/api/control/manual'

onMounted(()=>{
  getDeviceFun();
  getControlLogListFun();
  getStrategyListFun()
})

/** 获取所有设备*/
const deviceArr = ref([])
function getDeviceFun(){
  getControlDeviceList().then((res)=>{
    deviceArr.value = res.data;
    //拼接温度单位
    // for(let i = 0;i < res.data.length;i++){
    //   for(let j = 0;j < res.data[i].control_elements.length;j++){
    //     console.log(res.data[i].control_elements[j].tempValue)
    //     res.data[i].control_elements[j].tempValue = res.data[i].control_elements[j].tempValue + '℃'
    //   }
    // }
  })
}
/** 设备控制处理*/
const form1 = reactive({
  intemp:'',
  outtemp:'',
  now:''
})

/** 数据表格处理*/
const controlLogList = ref([])
const tableLength = ref()
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val) => {
  getControlLogListFun()
}
const handleCurrentChange = (val) => {
  getControlLogListFun()
}

function getControlLogListFun(){
  getControlLogList({
    "deviceId": null,
    "deviceName": null,
    "deviceSn": null,
    "controlKey": null,
    "controlValue": null,
    "controlResult": null,
    "controlContext": null,
    "pageNum": currentPage.value,
    "pageSize": pageSize.value
  }).then((res)=>{
    tableLength.value = res.total
    controlLogList.value = res.rows
    for(let i = 0;i < res.rows.length;i++){
      if(res.rows[i].controlResult == 1){
        res.rows[i].controlResult = '控制中'
      }else if(res.rows[i].controlResult == 2){
        res.rows[i].controlResult = '控制成功'
      }else if(res.rows[i].controlResult == 3){
        res.rows[i].controlResult = '控制失败'
      }
    }
  })
}

//拼接操作内容
function formatControlKeyValue(row){
  // console.log(row)
  if(!isNaN(row.controlValue)){
    row.controlValue = row.controlValue + '℃'
  }
  return row.controlKey + '：' + row.controlValue
}

//操作结果样式
// function formatControlResult(row){
//   if(row.controlResult == '控制成功'){
//     return '<span style="color: #14FF00">控制成功</span>';
//   }
//   if(row.controlResult == '控制失败'){
//     return '<span style="color: red">控制失败</span>';
//   }
// }

//翻页时不刷新序号
function indexMethod1(index){
  return index+(currentPage.value-1)*pageSize.value+1
}

/** 策略导入处理*/
const drawerIshow = ref(false)
const radio = ref()
const celueList = ref([])
function getStrategyListFun(){
  getStrategyList().then((res)=>{
    celueList.value = res.data
  })
}
//选择策略
const SenceControlArr = ref([])
function selectCeLue(item){
  //拼数组对象
  //1、
  let dataArr = [];
  for(let i = 0;i < item.data.length;i++){
    //2、
    let dataObject = {};
    // deviceId = item.data[i].device_id;
    dataObject.deviceId = item.data[i].device_id;

    //3、
    let tempArr = [];
    for(let j = 0;j < item.data[i].value.length;j++){
      //4、
      let tempObject = {};
      tempObject.controlKey = item.data[i].value[j].sceneKey
      tempObject.controlValue = item.data[i].value[j].sceneValue

      //5、
      tempArr.push(tempObject)
      dataObject.data = tempArr
    }
    //6、
    dataArr.push(dataObject);
  }

  //最终要传参的格式
  // console.log(JSON.stringify(dataArr, null, 4));
  SenceControlArr.value = JSON.stringify(dataArr, null, 4)
}
//执行
function confirmClick() {
  ElMessageBox.confirm(`确定执行 ${radio.value} ?`).then(() => {
    drawerIshow.value = false;
    getSenceControl(SenceControlArr.value).then((res)=>{
      if(res.code == 200){
        ElMessage.success('策略导入成功')
        getControlLogListFun()
      }
    })
  })
}

/** 控制设备启停*/
const loading = ref(false)
function handleDevChangeFun(id,sta){
  // console.log(id,sta)
  //1开启，2关闭
  sta = sta === true ? 1 : 2
  getStartAndStop({
    "deviceId": id,
    "runStatus": sta
  }).then((res)=>{
    // beforeChange()
    if(res.code == 200){
      ElMessage({
        type:'success',
        message:'控制成功！'
      })
    }
  })
  getControlLogListFun()
}
// function beforeChange(){
//   loading.value = true
//   return new Promise((resolve) => {
//     setTimeout(() => {
//       loading.value = false
//       // ElMessage.success('111!')
//       return resolve(true)
//     }, 1000)
//   })
// }

/** 设置温度*/
function getSetTemperatureFun(item){
  let dataArr = [];
  for(let i = 0;i < item.control_elements.length;i++){
    let dataObject = {
      "controlKey": item.control_elements[i].controlElement,
      "controlValue": item.control_elements[i].tempValue
    };
    dataArr.push(dataObject)
  }
  getSetTemperature({
    "deviceId":item.deviceId,
    "data": dataArr
  }).then((res)=>{
    if(res.code == 200){
      ElMessage.success('设置温度成功！')
      getControlLogListFun()
    }
  })

}

</script>

<style scoped lang="scss">
.home {
  height: calc(100vh - 118px);
  .dev_control_wrapper{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    width: 100%;
    height: 50%;
    overflow-y: auto;
    .dev_control_item{
      width: 24%;
      height: 47%;
      margin-right: 12px;
      margin-bottom: 12px;
      background-color: #2F3D8A;
      overflow: hidden;
      &:nth-child(4n){
        margin-right: 0px;
      }

      .item_header{
        width: 100%;
        height: 20%;
        background-color: #374590;
        padding: 0 10px;
        span{
          font-size: 16px;
          font-weight: bold;
          line-height: 37px;
        }
        .switch{
          float: right;
          line-height: 37px;
          height: 37px;
        }
      }
      .item_bottom{
        display: flex;
        width: 100%;
        height: 80%;
        .item_bottom_img{
          width: 40%;
          height: 100%;
          //border: 1px solid red;
          padding: 10px;
          img{
            width: 100%;
            height: 100%;
          }
        }
        .item_bottom_form{
          width: 60%;
          height: 100%;
          //border: 1px solid red;
          padding: 0 10px 0 0;
          .green{
            color: #14FF00;
          }
          .red{
            color: red;
          }
          .submit{
            padding: 3px 15px;
            border-radius: 2px;
            background-color: #2F8EED;
            float: right;
            margin-top: 8px;
            cursor: pointer;
            &:hover{
              background-color: #5ba2f3;
            }
          }
        }
      }
    }
  }
  .dev_control_table{
    width: 100%;
    height: 50%;
    background-color: #2F3D8A;
    .control_header{
      width: 100%;
      height: 10%;
      background-color: #374590;
      padding: 0 10px;
      span{
        font-size: 16px;
        font-weight: bold;
        line-height: 37px;
      }
    }
    .control_table{
      position: relative;
      width: 100%;
      height: 90%;
    }
  }
}

.celueBox{
  width: 100%;
  height: auto;
  padding: 10px;
  margin-bottom: 12px;
  border: 1px solid #ddd;
  &:hover{
    border: 1px solid #409EFF;
  }
  .celueItem{
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;
    padding: 10px 0;
    border-bottom: 1px solid #dddddd50;
    .itemsValue{
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
      width: 80%;
      .txtInput{
        margin-right: 10px;
        .txt{
          display: inline-block;
          width: 80px;
          text-align: right;
        }
        input{
          padding: 3px 3px;
          width: 100px;
          border: 1px solid #ddd;
        }
      }
    }
  }
}


.success {
  color: green;
}

.failure {
  color: red;
}
.tempInput{
  width: 100%;
  line-height: 28px;
  padding: 0 5px;
  color: #F5901A;
  font-weight: bold;
  &:focus{
    border: 0px;
    outline: none;
  }
}
::v-deep .el-button{
  border-radius: 2px;
  margin-bottom: 12px;
}
::v-deep .el-switch__core .el-switch__action{
  top: 1px;
  width: 17px;
  height: 17px;
}
::v-deep .el-form-item--default{
  margin-bottom: 3px;
}
::v-deep .el-input__inner{
  //color: #F5901A;
  //font-weight: bold;
}
::v-deep .el-pagination{
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
}
::v-deep .el-pagination__total{
  color: #f3ffff;
}
::v-deep .el-pagination__jump{
  color: #f3ffff;
}
::v-deep .el-pager{
  margin: 0 5px;
}
::v-deep .el-table--fit{
  background-color: #2D3D88;
}
::v-deep .el-radio{
  display: inline-block;
}
::v-deep .el-drawer__body{
  overflow-x: hidden;
  overflow-y: auto;
}
::v-deep .el-input__wrapper{
  padding: 0 10px;
  border-radius: 0px !important;
}
</style>

