<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='null'  />
              <el-option :label='item.label' :value='item.value'  :key="item.value" 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-col :span="1.5">
            <el-button
                type="info"
                plain
                icon="Upload"
                @click="handleImport"
                v-hasPermi="['system:user:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['system:user:export']"
            >导出</el-button>
          </el-col>
        </el-row>
        <div class="dev_control_table">
          <el-table :data="data.timingList" height="500px">
            <el-table-column label="序号" align="center" prop="deviceId" width="50"/>
            <el-table-column label="设备名称" align="center" prop="deviceName"/>
            <el-table-column label="是否可控" align="center" prop="isControl" />
            <el-table-column label="设备位置" align="center" prop="deviceAddress"/>
            <el-table-column label="设备状态" align="center" prop="devStatus"/>
            <el-table-column label="设备Sn" align="center" prop="deviceSn"/>
            <el-table-column label="当前功率" align="center" prop="totp"/>
            <el-table-column label="总用电量" align="center" prop="totWh"/>
            <el-table-column label="温度" align="center" prop="temp"/>
            <el-table-column label="进水温度" align="center" prop="tempIn"/>
            <el-table-column label="出水温度" align="center" prop="tempOut"/>
            <el-table-column label="操作" align="center" prop="handle" width="380">
              <template v-slot="scope" style="display: flex">
                <el-upload
                    class="upload-demo"
                    :action="data.url"
                    :headers="data.headers"
                    :on-preview="handlePreview1"
                    :on-remove="handleRemove1"
                    :before-remove="beforeRemove1"
                    :data="data.getId"
                    :on-success="success"
                    multiple
                    :limit="3"
                    :on-exceed="handleExceed1"
                    :file-list="data.fileList1">
                  <el-button size="small" type="info" @click="getId(scope.row.deviceId)">点击上传图片</el-button>
<!--                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
                </el-upload>
                <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.deviceId)">删除</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="data.upload.title" v-model="data.upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="data.upload.headers"
          :action="data.upload.url"
          :disabled="data.upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="data.upload.updateSupport" />是否更新已经存在的设备数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="timingForm"  ref="userRef" label-width="88px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称:" prop="deviceName" >
              <el-input v-model="timingForm.deviceName" placeholder="请输入设备名称"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型列表:"  >
              <el-select v-model="timingForm.deviceModel" placeholder="模型列表">
                <el-option v-for="item in data.queryParams" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否可控:"  >
              <el-select v-model="timingForm.isControl" placeholder="是否可控">
                <el-option label="可控" :value=2></el-option>
                <el-option label="不可控" :value=1></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备Sn:" prop="deviceSn" >
              <el-input v-model="timingForm.deviceSn" placeholder="请输入设备Sn" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="开始时间:" prop="startTime" >-->
<!--              <el-input v-model="timingForm.startTime" placeholder="示例：2023-05-11 10:40:29" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="设备地址:" prop="deviceAddress">
              <el-input v-model="timingForm.deviceAddress" placeholder="请输入设备地址"  />
            </el-form-item>
          </el-col>
        </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="600px" append-to-body>
      <el-form :model="timingForm1"  ref="userRef" label-width="88px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称:" prop="deviceName" >
              <el-input v-model="timingForm1.deviceName" placeholder="请输入设备名称"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型列表:"  >
              <el-select v-model="timingForm1.deviceModel" placeholder="模型列表">
                <el-option v-for="item in data.queryParams" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否可控:"  >
              <el-select v-model="timingForm1.isControl" placeholder="是否可控">
                <el-option label="可控" :value=2></el-option>
                <el-option label="不可控" :value=1></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备Sn:" prop="deviceSn" >
              <el-input v-model="timingForm1.deviceSn" placeholder="请输入设备Sn" />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="开始时间:" prop="startTime" >-->
          <!--              <el-input v-model="timingForm.startTime" placeholder="示例：2023-05-11 10:40:29" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="设备地址:" prop="deviceAddress">
              <el-input v-model="timingForm1.deviceAddress" placeholder="请输入设备地址"  />
            </el-form-item>
          </el-col>
        </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, getSbTab, postNew1, getSb, postXg1, postDel1, getYh, getMx,} from '../../../api/emonitor/api'
import {getToken} from "@/utils/auth";
onMounted(()=>{
  // getSb().then((res)=>{
  //   var arr = []
  //   for(var i in res.data){
  //     arr=arr.concat(res.data[i].children)
  //   }
  //   console.log('sblb',arr)
  //   data.sblb=arr
  // })
  getMx().then((res)=>{
    console.log(res)
    data.queryParams=res.data
  })
  // getYh().then((res)=>{
  //   console.log(res)
  //   data.queryParams=res.data
  // })
  getSbTab({
    "deviceId":0,

    "deviceModel":data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
  // postNew().then((res)=>{
  //   console.log(res)
  // })
})

/** 筛选处理 */
const data = reactive({

  url:import.meta.env.VITE_APP_BASE_API + "/system/device/index/daoruDevTuPian",
  headers: { Authorization: "Bearer " + getToken() },
  getId:{
    deviceId:1
  },
  fileList1:[],
  form:{},
  upload:{
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/device/index/daoruDevData"
  },
  MxList:[],
  sblb:[],
  total:'',
  timingList:[],
  queryParams: '',
  queryParams1: {
    "deviceModel": null
  },
  sceneCode:null,
  dateRange:[],
});
const { queryParams1, form, rules } = toRefs(data);
function success(response){
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", { dangerouslyUseHTMLString: true });
}
function getId(Id){
  console.log(Id)
  data.getId.deviceId=Id
}
function handleRemove1(file, fileList) {
  console.log(file, fileList);
}
function handlePreview1(file) {
  console.log(file);
}
function handleExceed1(files, fileList) {
  this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
}
function beforeRemove1(file, fileList) {
  return this.$confirm(`确定移除 ${ file.name }？`);
}
//改变
function changeSl(){
  console.log(data.sceneCode)
}
//搜索按钮
function handleQuery(){
  getSbTab({
    "deviceId":0,

    "deviceModel":data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
}
//重置按钮
function resetQuery(){
  data.sceneCode=null
  currentPage.value=1
  pageSize.value=10
  getSbTab({
    "deviceId":0,

    "deviceModel":null,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
}


/** 数据表格处理 */

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}`)
  getSbTab({
    "deviceId":0,

    "deviceModel":data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
}
const handleCurrentChange = (val) => {
  console.log(`${val}`)
  getSbTab({
    "deviceId":0,

    "deviceModel":data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
}
const { proxy } = getCurrentInstance();
function handleImport() {
  data.upload.title = "设备导入";
  data.upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/device/index/downloadDevTemplate",{
  }, `device_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  data.upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  data.upload.open = false;
  data.upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getSbTab({
    "deviceId":0,

    "deviceModel":data.sceneCode,

    "pageNum": currentPage.value,

    "pageSize": pageSize.value
  }).then((res)=>{
    console.log(res)
    data.timingList=res.rows
    data.total=res.total
    for(let i in res.rows){
      if(res.rows[i].isControl==2){
        res.rows[i].isControl='可控'
      }else if(res.rows[i].isControl==1){
        res.rows[i].isControl='不可控'
      }
    }
  })
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 重置操作表单 */
function reset() {
  data.form = {
    userId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    roleIds: []
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel2() {
  data.upload.open = false;
  reset();
};

/** 导出按钮操作 */
function handleExport() {
  data.queryParams1.deviceModel = data.sceneCode
  proxy.download("system/device/index/daochuDevs",{
    ...queryParams1.value
  },`device_${new Date().getTime()}.xlsx`);
};
/** 新增策略处理 */
const open = ref(false);
const title = ref();
const open1 = ref(false);
const title1= ref();
const activeName = ref('1')
const timingForm = reactive({
  "parentId": 0,
  "userId": 1,
  "isControl":'',
  "deviceType": 2,
  "deviceSn": "",
  "deviceName": "",
  "hardVersion": "2.23",
  "softVersion": "2.24",
  "deviceAddress": '',
  "startTime": null,
  "deviceModel": "",
  "photoUrl": null
})
const timingForm1 = reactive({
  "deviceId":'',
  "parentId": 0,
  "userId": 1,
  "isControl": '',
  "deviceType": 2,
  "deviceSn": "",
  "deviceName": "",
  "hardVersion": "2.23",
  "softVersion": "2.24",
  "deviceAddress": '',
  "startTime": null,
  "deviceModel": "",
  "photoUrl": null

})

// 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() {
  open.value = true;
  title.value = "新增设备";
};
function submitForm() {
  open.value = false;
  console.log(timingForm)
  postNew1(timingForm).then((res)=>{
    console.log(res)
    ElMessage({type:"success",message:'新增成功！'})
    handleQuery()
        timingForm.isControl='',
        timingForm.deviceSn='',
        timingForm.deviceName='',
        timingForm.deviceAddress='',
        timingForm.deviceModel=''
  })
};
function cancel() {
  open.value = false;
      timingForm.isControl='',
      timingForm.deviceSn='',
      timingForm.deviceName='',
      timingForm.deviceAddress='',
      timingForm.deviceModel=''
};
function handleXg(data) {
  open1.value = true;
  title1.value = "修改设备";
  console.log(data)
  timingForm1.isControl=data.isControl
  timingForm1.deviceSn=data.deviceSn
  timingForm1.deviceName=data.deviceName
  timingForm1.deviceAddress=data.deviceAddress
  timingForm1.deviceModel=data.deviceModel
  timingForm1.deviceId = data.deviceId
  // if(sceneContext=='出水温度'){
  //   timingForm1.outtemp=sceneValue
  // }else if (sceneContext=='进水温度'){
  //   timingForm1.intemp=sceneValue
  // }else{
  //   timingForm1.temp=sceneValue
  // }
};
function submitForm1() {
  open1.value = false;
  if(timingForm1.isControl=='可控'){
    timingForm1.isControl=2
  }else if (timingForm1.isControl=='不可控'){
    timingForm1.isControl=1
  }
  console.log(timingForm1)
  postXg1({
    "deviceId": timingForm1.deviceId,
    "parentId": 0,
    "userId": 1,
    "deviceType": 2,
    "deviceSn": timingForm1.deviceSn,
    "deviceModel": timingForm1.deviceModel,
    "deviceName": timingForm1.deviceName,
    "deviceAddress": timingForm1.deviceAddress,
    "isControl":timingForm1.isControl,
    "photoUrl": null,
    "createBy": null,
    "createTime": null,
  }).then((res)=>{
    console.log(res)
    ElMessage({type:"success",message:'修改成功！'})
    handleQuery()
    timingForm1.isControl=''
    timingForm1.deviceSn=''
    timingForm1.deviceName=''
    timingForm1.deviceAddress=''
    timingForm1.deviceModel=''
    timingForm1.deviceId=''
  })
};
function cancel1() {
  open1.value = false;
  timingForm1.isControl=''
  timingForm1.deviceSn=''
  timingForm1.deviceName=''
  timingForm1.deviceAddress=''
  timingForm1.deviceModel=''
  timingForm1.deviceId=''
};
function handleDel(data) {
  ElMessageBox.confirm("是否确认删除此设备？", "提示",{
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    console.log(data)
    postDel1([data]).then((res) => {
      console.log(res)
      ElMessage({type:"success",message:'删除成功！'})
      handleQuery()
    });
  })
}




const { queryParams } = toRefs(data);
</script>

<style scoped lang="scss">
.dev_control_table{
  position: relative;
  width: 100%;
  min-height: 745px;
  background-color: #2F3D8A;
}

::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;
}
.upload-demo{
  width: 10px;
  height: 0px;
  align-items: center;
  position: center;
}
</style>