<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="88px">
          <el-form-item label="策略名称:" prop="name">
            <el-select v-model="data.sceneCode" placeholder="请选择" style="width: 240px" @change="changeSl">
              <el-option label='所有' :value='0'  />
              <el-option :label='item.label' :value='item.sceneCode'  :key="item.sceneCode" v-for="item in queryParams"/>
            </el-select>
          </el-form-item>
          <el-form-item>

            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
        <div class="dev_control_table">
          <el-table :data="data.timingList" height="500px">
            <el-table-column label="序号" align="center"  width="50"  type="index"/>
            <el-table-column label="策略名称" align="center" prop="strategyName" width="300"/>
            <el-table-column label="策略描述" align="center" prop="strategyInfo"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
<!--            <el-table-column label="温度" align="center" prop="sceneValue"/>-->
            <el-table-column label="操作" align="center" prop="handle">
              <template v-slot="scope">
                <el-button type="primary" size="small" icon="Edit" v-hasPermi="['system:cl:edit']" @click="handleXg(scope.row)">修改</el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDel(scope.row.strategyCode)">删除</el-button>
              </template>
            </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="data.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
        </div>
      </el-col>
    </el-row>



    <!-- 新增对话框 -->
    <el-dialog :title="title" v-model="open" width="1100" append-to-body>
      <el-form :model="timingForm"  ref="userRef" label-width="88px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="策略名称:" prop="sceneName" >
              <el-input v-model="addForm.strategyName" placeholder="请输入策略名称"  />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="策略描述:" prop="sceneRemark" >
              <el-input v-model="addForm.strategyInfo" placeholder="请输入策略描述"  />
            </el-form-item>
          </el-col>



          <el-collapse v-model="activeNames" accordion>
            <el-collapse-item v-for="item in data.items" :key="item.id" :title="item.title" :name="item.id">
              <span style="width: 50px; margin-left: 20px;margin-bottom: 50px ">步骤名称：</span>
              <el-input v-model="item.sceneName"  placeholder="请输入步骤名称"  style="width: 950px;margin-bottom: 10px "/>
              <span style="width: 50px; margin-left: 20px ">步骤描述：</span>
              <el-input v-model="item.sceneRemark"  placeholder="请输入步骤描述"  style="width: 950px"/>
              <span style="width: 120px;display: inline-block ;margin: 20px">是否有限制条件</span>
              <el-radio-group v-model="item.isJudge">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
              <el-collapse v-model="item.isJudge" style="width: 1000px">
                <el-collapse-item title="限制条件" :name="1">
                  <span>限制设备：</span>
                  <el-select v-model="item.judgeDevice" placeholder="请选择" style="width: 240px">
                    <el-option :label='item.deviceName' :value='item.deviceId'  :key="item.deviceId" v-for="item in data.allsblb"/>
                  </el-select>
                  <span style="width: 4.7rem;display: inline-block ;margin: 20px">限制属性：</span>
                  <el-radio-group v-model="item.judgeElement">
                    <el-radio label="thermometer_value">温度</el-radio>
                    <el-radio label="thermometer_value_in">进水温度</el-radio>
                    <el-radio label="thermometer_value_out">出水温度</el-radio>
                  </el-radio-group>
                  <span style="width: 4.7rem;display: inline-block ;margin-left: 50px">限制值：</span>
                  <el-input type="number" v-model="item.judgeData" placeholder="请输入" style="width: 80px ; height: 25px" />
                </el-collapse-item>
              </el-collapse>

<!--              <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="handleCheckAllChange">全选</el-checkbox>-->
              <el-checkbox-group :max="1" v-model="item.checkedSblb" @change="handleCheckedCitiesChange" style="white-space: normal;display: inline-block">
                <el-checkbox v-for="it in item.sblb" :label="it.deviceId" :key="it.deviceId"  style="margin-bottom: 10px;width: 560px;">
                  <span  style="width: 160px;display: inline-block">{{it.deviceName}}</span>
                  <span  v-for="control in it.controlKey" style="margin-left: 20px">
                <span style="width: 80px;display: inline-block">{{control.label}}</span>
               <template v-if="control.label === '控制启停'">
                <el-radio-group v-model="control.value">
                <el-radio label="1">开启</el-radio>
                <el-radio label="0">关闭</el-radio>
                </el-radio-group>
               </template>
        <template v-else>
         <el-input type="number" v-model="control.value" style="width: 120px ;margin: 10px;height: 25px"/>
        </template>
              </span>
                </el-checkbox>
              </el-checkbox-group>

              <el-button type="danger" @click="removeStep(item.id)">删除</el-button>
            </el-collapse-item>
          </el-collapse>
          <el-button type="primary"  @click="addStep">添加步骤+</el-button>



        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog :title="title1" v-model="open1" width="1100px" append-to-body>
      <el-form :model="timingForm1"  ref="userRef" label-width="88px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="策略名称:" prop="sceneName">
              <el-input v-model="addForm1.strategyName" placeholder="请输入策略名称" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="策略描述:" prop="sceneRemark" >
              <el-input v-model="addForm1.strategyInfo" placeholder="请输入策略描述"  />
            </el-form-item>
          </el-col>


          <el-collapse v-model="activeNames1" accordion>
            <el-collapse-item v-for="item in data.items1" :key="item.id" :title="item.title" :name="item.id">
              <span style="width: 50px; margin-left: 20px;margin-bottom: 50px ">步骤名称：</span>
              <el-input v-model="item.sceneName"  placeholder="请输入步骤名称"  style="width: 950px;margin-bottom: 10px "/>
              <span style="width: 50px; margin-left: 20px ">步骤描述：</span>
              <el-input v-model="item.sceneRemark"  placeholder="请输入步骤描述"  style="width: 950px"/>
              <span style="width: 120px;display: inline-block ;margin: 20px">是否有限制条件</span>
              <el-radio-group v-model="item.isJudge">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
              <el-collapse v-model="item.isJudge" style="width: 1000px">
                <el-collapse-item title="限制条件" :name="1">
                  <span>限制设备：</span>
                  <el-select v-model="item.judgeDevice" placeholder="请选择" style="width: 240px">
                    <el-option :label='item.deviceName' :value='item.deviceId'  :key="item.deviceId" v-for="item in data.allsblb"/>
                  </el-select>
                  <span style="width: 4.7rem;display: inline-block ;margin: 20px">限制属性：</span>
                  <el-radio-group v-model="item.judgeElement">
                    <el-radio label="thermometer_value">温度</el-radio>
                    <el-radio label="thermometer_value_in">进水温度</el-radio>
                    <el-radio label="thermometer_value_out">出水温度</el-radio>
                  </el-radio-group>
                  <span style="width: 4.7rem;display: inline-block ;margin-left: 50px">限制值：</span>
                  <el-input type="number" v-model="item.judgeData" placeholder="请输入" style="width: 80px ; height: 25px" />
                </el-collapse-item>
              </el-collapse>

              <!--              <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="handleCheckAllChange">全选</el-checkbox>-->
              <el-checkbox-group :max="1" v-model="item.checkedSblb" @change="handleCheckedCitiesChange" style="white-space: normal;display: inline-block">
                <el-checkbox v-for="it in item.sblb" :label="it.deviceId" :key="it.deviceId"  style="margin-bottom: 10px;width: 560px;">
                  <span  style="width: 160px;display: inline-block">{{it.deviceName}}</span>
                  <span  v-for="control in it.controlKey" style="margin-left: 20px">
                <span style="width: 80px;display: inline-block">{{control.label}}</span>
               <template v-if="control.label === '控制启停'">
                <el-radio-group v-model="control.value">
                <el-radio label="1">开启</el-radio>
                <el-radio label="0">关闭</el-radio>
                </el-radio-group>
               </template>
        <template v-else>
         <el-input type="number" v-model="control.value" style="width: 120px ;margin: 10px;height: 25px"/>
        </template>
              </span>
                </el-checkbox>
              </el-checkbox-group>

              <el-button type="danger" @click="removeStep1(item.id)">删除</el-button>
            </el-collapse-item>
          </el-collapse>
          <el-button type="primary"  @click="addStep1">添加步骤+</el-button>


        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm1">确 定</el-button>
          <el-button @click="cancel1">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Index">
import {ElMessage,ElMessageBox} from 'element-plus'
import {Delete} from '@element-plus/icons-vue'
import {ref,reactive,watch,onMounted} from "vue";
import {getXl,getTb,postNew,getSb1,postXg,postDel,getSb} from '../../../api/emonitor/api'
onMounted(()=>{
  getSb().then((res)=>{
    console.log('111',res)
    var arr = []
    for(var i in res.data){
      arr=arr.concat(res.data[i].children)
    }
    console.log('Allsblb',arr)
    data.allsblb=arr
  })
  getSb1().then((res)=>{
    console.log('222',res)
    var arr = []
    for(var i in res.data){
      arr=arr.concat(res.data[i].children)
    }
    console.log('sblb',arr)
    data.sblb=arr
    var brr = []
    for(let a in arr){
      brr.push(arr[a].deviceId)
    }
    data.AllName=brr
   console.log(brr)
  })
  getXl().then((res)=>{
    console.log(res)
    data.queryParams=res.data
  })
  getTb({
    "sceneCode": data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
  })
  // postNew().then((res)=>{
  //   console.log(res)
  // })
})
/** 筛选处理 */
const data = reactive({
  items:[
    { id: 1, title: '第1步', content: `步骤1的内容`,
    sblb:[],
    isIndeterminate:false,
    checkedSblb: [],
    checkAll:false,
    sceneName:'',
    sceneRemark:'',
    deviceVos:[],
    isJudge:null,
    judgeDevice:null,
    judgeElement:null,
    judgeData:null }
  ],
  items1:[],
  num:1,
  activeNames:0,
  checkAll: false,
  checkedSblb: [],
  checkAll1: false,
  checkedSblb1: [],
  sblb: [],
  allsblb:[],
  AllName:[],
  isIndeterminate: false,
  isIndeterminate1: false,
  total:'',
  timingList:[],
  queryParams: '',
  sceneCode:0,
  dateRange:[],
  postData:[],
});
// const wat = watch(()=> data.sblb,(val) =>{
//   console.log(val)
// })
//改变
function changeSl(){
  console.log(data.sceneCode)
}
//搜索按钮
function handleQuery(){
  getTb({
    "sceneCode": data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
  })
}
//重置按钮
function resetQuery(){
  data.sceneCode=0
  currentPage.value=1
  pageSize.value=10
  getTb({
    "sceneCode": data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
  })
}
function handleCheckAllChange(val) {
  data.checkedSblb = val ? data.AllName : [];
  data.isIndeterminate = false;
  console.log(data.checkedSblb)
}

function  handleCheckedCitiesChange(value) {
  let checkedCount = value.length;
  data.checkAll = checkedCount === data.sblb.length;
  data.isIndeterminate = checkedCount > 0 && checkedCount < data.sblb.length;
}
function handleCheckAllChange1(val) {
  data.checkedSblb1 = val ? data.AllName : [];
  data.isIndeterminate1 = false;
  console.log(data.checkedSblb1)
}

function  handleCheckedCitiesChange1(value) {
  let checkedCount = value.length;
  data.checkAll1 = checkedCount === data.sblb.length;
  data.isIndeterminate1 = checkedCount > 0 && checkedCount < data.sblb.length;
}
/** 数据表格处理 */

const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val) => {
  console.log(`${val}`)
  getTb({
    "sceneCode": data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
  })
}
const handleCurrentChange = (val) => {
  console.log(`${val}`)
  getTb({
    "sceneCode": data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
  })
}


/** 新增策略处理 */
const open = ref(false);
const title = ref();
const open1 = ref(false);
const title1= ref();
const activeName = ref('1')
const addForm = reactive({
  strategyInfo:'',
  strategyName:'',
  scenesList:[]
})
const addForm1 = reactive({
  strategyCode:'',
  strategyInfo:'',
  strategyName:'',
  scenesList:[]
})
const timingForm = reactive({
  sceneName:'',
  sceneRemark:'',
  deviceVos:[],
  isJudge:null,
  judgeDevice:null,
  judgeElement:null,
  judgeData:null
})
const timingForm1 = reactive({
  sceneName:'',
  sceneRemark:'',
  sceneCode:'',
  deviceVos:[],
  isJudge:null,
  judgeDevice:null,
  judgeElement:null,
  judgeData:null
  // deviceId:'',
  // temp:'',
  // intemp:'',
  // outtemp:''
})

// const watchTime = watch(()=> timingForm.executeTime, (val) => {
//   // console.log(val.toLocaleString())
//   let date = new Date(val)
//   let hours = date.getHours()
//   let minutes = date.getMinutes()
//   let seconds = date.getSeconds()
//   console.log(`${hours}:${minutes}:${seconds}`)
// })



function handleAdd() {
  getSb1().then((res)=>{
    console.log('222',res)
    var arr = []
    for(var i in res.data){
      arr=arr.concat(res.data[i].children)
    }
    console.log('sblb',arr)
    data.sblb=arr
    addForm.strategyName=''
    addForm.strategyInfo=''
    data.items=[{ id: 1, title: '第1步', content: `步骤1的内容`,
      sblb:data.sblb,
      isIndeterminate:false,
      checkedSblb: [],
      checkAll:false,
      sceneName:'',
      sceneRemark:'',
      deviceVos:[],
      isJudge:null,
      judgeDevice:null,
      judgeElement:null,
      judgeData:null }]
    open.value = true;
    title.value = "新增策略";
  })
};
function submitForm() {

  for(let i in data.items){
    let tempCheckedSblb = [];
    data.items[i].checkedSblb.forEach(item => {
      let tempItem = {
        deviceId: item,
        tempList:[]
      };
      // 根据 item 从 data.sblb 中找到对应的设备信息
      let deviceInfo = data.items[i].sblb.find(sblbItem => sblbItem.deviceId === item);
      if (deviceInfo) {
        console.log('11111',deviceInfo)
        tempItem.tempList = deviceInfo.controlKey
      }
      tempCheckedSblb.push(tempItem);
      data.items[i].deviceVos=tempCheckedSblb
    });
  }
  console.log('??????????',data.items)
  addForm.scenesList=data.items
  console.log(addForm)
  postNew(addForm).then((res)=>{
    console.log(res)
    ElMessage({type:"success",message:'新增成功！'})
    handleQuery()
    getXl().then((res)=>{
      console.log(res)
      data.queryParams=res.data
    })

    open.value = false;
  })
};
function cancel() {
  open.value = false;
};
function handleXg(dat) {
  open1.value = true;
  title1.value = "修改策略";
  console.log('101111',dat)
  addForm1.strategyCode=dat.strategyCode
  addForm1.strategyName=dat.strategyName
  addForm1.strategyInfo=dat.strategyInfo
  data.items1=dat.scenesList
  console.log(data.items1)
 //  var arr = []
 //  for(let i in dat.deviceVos){
 //    arr.push(dat.deviceVos[i].deviceId)
 //  }
 // data.checkedSblb1=arr
 //  for (let i = 0;i < data.sblb.length ;i++ ){
 //    var deviceId = data.sblb[i].deviceId
 //    for (let j = 0;j < dat.deviceVos.length ;j++ ) {
 //      if ( deviceId === dat.deviceVos[j].deviceId){
 //        console.log(dat.deviceVos[j].tempValue)
 //        data.sblb[i].controlKey = dat.deviceVos[j].tempValue;
 //      }
 //    }
 //  }
 //  timingForm1.sceneName=dat.sceneName
 //  timingForm1.sceneRemark=dat.sceneRemark
 //  timingForm1.sceneCode = dat.sceneCode
 //  timingForm1.isJudge=dat.isJudge
 //  timingForm1.judgeDevice=dat.judgeDevice
 //  timingForm1.judgeElement=dat.judgeElement
 //  timingForm1.judgeData=dat.judgeData
};
function submitForm1() {
  for(let i in data.items1){
    let tempCheckedSblb = [];
    data.items1[i].checkedSblb.forEach(item => {
      let tempItem = {
        deviceId: item,
        tempList:[]
      };
      // 根据 item 从 data.sblb 中找到对应的设备信息
      let deviceInfo = data.items1[i].sblb.find(sblbItem => sblbItem.deviceId === item);
      if (deviceInfo) {
        tempItem.tempList = deviceInfo.controlKey
      }
      tempCheckedSblb.push(tempItem);
      data.items1[i].deviceVos=tempCheckedSblb
    });
  }
  console.log('??????????',data.items1)
  addForm1.scenesList=data.items1
  console.log(addForm1)
  postXg(addForm1).then((res)=>{
    console.log(res)
    ElMessage({type:"success",message:'修改成功！'})
    getXl().then((res)=>{
      console.log(res)
      data.queryParams=res.data
    })
    handleQuery()
    open1.value = false;
    // data.sblb.map(item => {
    //   item.controlKey.map(temp => {
    //     temp.value = '';
    //   });
    // });
  })
};
function cancel1() {
  open1.value = false;
  // handleQuery()
  // data.sblb.map(item => {
  //   item.controlKey.map(temp => {
  //     temp.value = '';
  //   });
  // })
};
function handleDel(strategyCode) {
  ElMessageBox.confirm("是否确认删除此策略？", "提示",{
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    console.log(strategyCode)
    postDel({
      "strategyCode":strategyCode
    }).then((res) => {
      console.log(res)
      ElMessage({type:"success",message:'删除成功！'})
      getXl().then((res)=>{
        console.log(res)
        data.queryParams=res.data
      })
      handleQuery()
    });
  })
}


//添加步骤
const activeNames =reactive([1])
const addStep = () => {
  getSb1().then((res)=>{
    console.log('222',res)
    var arr = []
    for(var i in res.data){
      arr=arr.concat(res.data[i].children)
    }
    console.log('sblb',arr)
    data.sblb=arr
    const newId = data.items.length + 1
    data.items.push({ id: newId, title: `第${newId}步`, content: `步骤${newId}的内容`,
      sblb:data.sblb,
      isIndeterminate:false,
      checkedSblb: [],
      checkAll:false,
      sceneName:'',
      sceneRemark:'',
      deviceVos:[],
      isJudge:null,
      judgeDevice:null,
      judgeElement:null,
      judgeData:null})
    activeNames.push(`${newId}`)
  })
}
const removeStep = (id) => {
  const index = data.items.findIndex(item => item.id === id)
  if (index !== -1) {
    data.items.splice(index, 1)
    activeNames.splice(activeNames.indexOf(`${id}`), 1)
  }
  console.log(data.items)
  console.log(activeNames)
}


//修改步骤
const activeNames1 =reactive([1])
const addStep1 = () => {
  getSb1().then((res)=>{
    console.log('222',res)
    var arr = []
    for(var i in res.data){
      arr=arr.concat(res.data[i].children)
    }
    console.log('sblb',arr)
    data.sblb=arr
    const newId1 = data.items1.length + 1
    data.items1.push({ id: newId1, title: `第${newId1}步`, content: `步骤${newId1}的内容`,
      sblb:data.sblb,
      isIndeterminate:false,
      checkedSblb: [],
      checkAll:false,
      sceneName:'',
      sceneRemark:'',
      deviceVos:[],
      isJudge:null,
      judgeDevice:null,
      judgeElement:null,
      judgeData:null})
    activeNames1.push(`${newId1}`)
  })
}
const removeStep1 = (id) => {
  const index = data.items1.findIndex(item => item.id === id)
  if (index !== -1) {
    data.items1.splice(index, 1)
    activeNames1.splice(activeNames1.indexOf(`${id}`), 1)
  }
  console.log(data.items1)
  console.log(activeNames1)
}
const { queryParams } = toRefs(data);
</script>

<style scoped lang="scss">

.dev_control_table{
  position: relative;
  width: 100%;
  min-height: 745px;
  background-color: #2F3D8A;
}
.taber{
  width: 400px;
  margin-left: 52px;
  display: flex;
  justify-content: flex-start;
  line-height: 32px;
  span{
    width: 120px;
    &:nth-child(2),&:nth-child(3){
      margin-left: 20px;
    }
  }
}
::v-deep .el-button{
  border-radius: 2px;
}
::v-deep .el-pagination{
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}
::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 .el-table__body-wrapper{
  background-color: #2F3D8A;
}
::v-deep .el-form-item__content{
  //display: flex;
}
::v-deep .el-checkbox {
  width: 560px;
}
//::v-deep .el-dialog:not(.is-fullscreen){
//  width: auto;
//}
</style>

