<template>
  <div class="videoManage manage-page deviceManage">
    <div class="flex-view flex-title">
      <div class="table-title">
        <img src="../../assets/manageImg/deviceManage.png" alt="">设备管理
      </div>
      <div class="table-title-btn blue" @click="openAddModel1">
        <img src="../../assets/manageImg/add-btn.png" alt="">添加
      </div>
    </div>
    <div class="flex-view ">
      <div class="manage-input  w-180">
        <span class="input-title">用户名查询</span>
        <input class="search-input" type="text" v-model="searchName" placeholder="">
      </div>
      <div class="manage-input  w-180">
        <span class="input-title">设备code码查询</span>
        <input class="search-input" type="text" v-model="searchID" placeholder="">
      </div>
      <div class="table-title-btn blue" @click="dataInit">
        查询
      </div>
    </div>
    <div class="table-view">
      <el-table :data="tableData" :row-class-name="tableRowClassName" height="540" style="width: 100%">
        <el-table-column prop="deviceId" label="设备code码">
        </el-table-column>
        <el-table-column prop="deviceTypeName" label="设备名称">
        </el-table-column>
        <el-table-column prop="cameraSerialNumber" label="设备关联摄像头名称">
        </el-table-column>
        <el-table-column prop="cameraChannelNumber" label="设备关联摄像头通道">
        </el-table-column>
        <el-table-column prop="userName" label="设备关联用户名称">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="table-flex">
              <div class="table-operate blue" @click="openRoleModel(scope.row.deviceId)"
                v-if="scope.row.deviceName == 10">
                <img src="../../assets/manageImg/table-edit.png" alt="">权限
              </div>
              <el-popconfirm @confirm="confirmDel(scope.row)" title="这一段内容确定删除吗？" icon-color="red">
                <div class="table-operate red" slot="reference">
                  <img src="../../assets/manageImg/table-delete.png" alt="">删除
                </div>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200, 500, 1000, 1500]" :page-size="pageSize"
        layout="->,total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog  :close-on-click-modal="false" title="控制器权限管理" :append-to-body="true" :visible.sync="roleModel" width="70%">
      <div class="model-title">控制器权限管理</div>
      <div class="model-sel scroll">
        <div v-for="item, index in selDevicestatus" :key="index">
          <div @click="selClick(item)" :class="item.select ? 'sel' : 'no-sel'"></div>
          {{ item.name }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn" @click="addpermissionall">添加标准控制器</div>
        <div class="vrcode-btn cancle-btn w-100" @click="roleModel = false">确定</div>
      </span>
    </el-dialog>

    <el-dialog  :close-on-click-modal="false" title="提示" top="10vh" :visible.sync="addModel1" width="564px" class="vrcode-model manage-model"
      :append-to-body="true">
      <div class="vrcode-model-title">
        添加设备
      </div>
      <div class="vrcode-content">
        <div class="manage-left">
          <div class="manage-input">
            <div class="input-title">设备code码</div>
            <input type="text" v-model="nowData1.deviceId" placeholder="请输入设备code码">
          </div>
          <div class="manage-input-sel" style="margin-right: 0;">
            <div class="input-title">设备类型</div>
            <el-dropdown @command="handleCommand1">
              <div class="el-dropdown-link">
                <input v-model="deviceType" type="text" class="input-input" placeholder="请选择设备类型">
                <div class="arrow"><img src="../../assets/image/arrow.png" alt=""></div>
              </div>
              <el-dropdown-menu slot="dropdown" class="manage-dropdown">
                <el-dropdown-item v-for="item, index in deviceSel
                " :key="index" :command="item.label">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="manage-input">
            <div class="input-title">关联摄像头名称</div>
            <input type="number" v-model="nowData1.cameraSerialNumber" placeholder="请输入摄像头名称">
          </div>
          <div class="manage-img-small">
            <label for="sel-img">
              <img class="" :src="nowData1.hls" alt="">
            </label>
            <input ref="fileInput1" type="file" :multiple="false" id="sel-img" accept="image/*"
              @change="handleImageChange($event,1)" />
          </div>
        </div>
        <div class="manage-right">
          <div class="manage-input">
            <div class="input-title">设备名称</div>
            <input type="text" v-model="nowData1.deviceTypeName" placeholder="请输入设备名称">
          </div>

          <div class="manage-input">
            <div class="input-title">关联摄像头通道</div>
            <input type="number" v-model="nowData1.cameraChannelNumber" placeholder="请输入摄像机通道号">
          </div>
        
          <div class="manage-text">
            如果有摄像机则每小时都会定时更新<br>
            小程序摄像机主页面图片，<br>
            如果没有摄像机则可以自定义更改图片<br>
            地址信息。
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="addDevice">确定</div>
        <div class="vrcode-btn cancle-btn w-100" @click="addModel1 = false">取消</div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      searchName: '',
      searchID: '',
      total: 0,
      roleModel: false,
      selDevicestatus: [],
      allDevicestatus: [],
      nowDevicestatus: [],
      nowDeviceId:'',

      //添加设备
      addModel1:false,
      nowData1:{
        deviceState:0,
      },

      deviceType:'',
      deviceSel: [{ label: '控制器', value: 10, },
       { label: '施肥机', value: 1, }, 
       { label: '气象站', value:30, }, 
       { label: '智能灌溉控制器', value:20, }],
    }
  },
  mounted() { this.dataInit() },
  methods: {
    dataInit() {
      // var user = JSON.parse(localStorage.getItem('userInfo'))
      // this.api.selUserbyid(user.userid).then(res => {
      //   if (res.data.code == 200) {
      //     this.deviceList = res.data.data.devices
      //   }
      // })
      this.pageSize = 10
      this.currentPage = 1
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    getDeviceType(e) {
      if (e == '控制器') {
        return 10
      } else if(e == '施肥机'){
        return 1
      } else if(e == '气象站'){
        return 30
      } else if(e == '智能灌溉控制器'){
        return 20
      }
    },
    handleCommand1(e) {
      this.nowData1.deviceName = this.getDeviceType(e)
      this.deviceType = e
    },
    openRoleModel(deviceId) {
      this.loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.selDevicestatus = []
      this.nowDeviceId=deviceId
      var data = { deviceId: deviceId }
      // 线调取全部权限
      this.api.selectallPermissions().then(res => {
        if (res.data.code == 200) {
          this.allDevicestatus = res.data.data
          // this.roleModel=true
          // 再根据deviceId调取单个设备权限 并且查询共同name
          this.getcontrol_cpermission()
        } else {
          this.loading.close()
          this.$message.error(res.data.msg);
        }
      })
    },
    openAddModel1(){
      this.nowData1={
        deviceState:0,
      }
      this.addModel1=true
    },
    addDevice(){
      if (!this.nowData1.deviceId) {
        this.$message.error('设备code码还未填写');
        return
      }
      if (!this.nowData1.deviceName) {
        this.$message.error('设备类型还未选择');
        return
      }
      if (!this.nowData1.deviceTypeName) {
        this.$message.error('设备名称还未填写');
        return
      }
      var data={...this.nowData1,stationName:this.nowData1.deviceTypeName}
      this.api.addDevice(data).then(res=>{
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        this.dataInit()
        this.addModel1=false
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    handleImageChange(event) {
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const imageData = e.target.result;
        const convertedFile = new File([imageData], file.name, { type: file.type });
        // 处理转换后的文件...

        var data = { file: convertedFile }
        this.api.manageUploadImage(data).then(res => {
          this.loading.close()
        if (res.data.code == 200) {
            this.nowData1.hls=res.data.msg 
            this.$refs.fileInput1.value = '';
        } else {
          this.$message.error(res.data.msg);
        }
        })
      };
      reader.readAsArrayBuffer(file);

    },
    addpermissionall(){
      this.api.addpermissionall(this.nowDeviceId).then(res=>{
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.getcontrol_cpermission()
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    getcontrol_cpermission(){
      this.api.getcontrol_cpermission(this.nowDeviceId).then(res1 => {
            this.loading.close()
            if (res1.data.code == 200) {
              this.nowDevicestatus = res1.data.data
              var list1 = this.allDevicestatus
              var list2 = this.nowDevicestatus
              var resultArray = []
              // 遍历 list1
              for (const item1 of list1) {
                // 查找在 list2 中是否有相同 id 的对象
                const matchingItem = list2.find(item2 => item2.id === item1.id);
                // 如果找到匹配的对象，则在 list1 对应的对象中添加 select 属性
                if (matchingItem) {
                  item1.select = true;
                } else {
                  // 如果没找到匹配的对象，则添加 select 属性并设置为 false
                  item1.select = false;
                }
                // 将处理后的对象添加到结果数组中
                resultArray.push(item1);
              }
              this.selDevicestatus = resultArray
              this.roleModel = true
            } else {
              this.$message.error(res1.data.msg);
            }
          })
    },
    selClick(item) {
            var store = this.$store.state
            var deviceId = this.nowDeviceId
            var statusId = item.id
            if (item.select) {
                item.select = false
                this.$forceUpdate();
                this.api.delpermission(deviceId, statusId).then((res => {
                    if (res.data.code == 200) {
                        this.$message({
                            message: '修改成功',
                            type: "success",
                        });
                        this.getcontrol_cpermission()
                    } else {
                        this.$message({
                            message: res.data.msg,
                            type: "warning",
                        });
                    }
                }))
            } else {
                item.select = true
                this.$forceUpdate();
                this.api.addpermission(deviceId, statusId).then((res => {
                    if (res.data.code == 200) {
                        this.$message({
                            message: '修改成功',
                            type: "success",
                        });
                        this.getcontrol_cpermission()
                    }
                }))
            }
        },
    confirmDel(item) {
      var data = { id: item.deviceId }
      this.api.deldevice(data).then(res => {
        if (res.data.code == 200) {
          this.dataInit()
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    getData() {
      var data = {
        page: this.currentPage,
        pageSize: this.pageSize,
        userName: this.searchName,
        deviceId: this.searchID
      }
      this.loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.api.seldevice(data).then(res => {
        this.loading.close()
        if (res.data.code == 200) {
          this.tableData = res.data.data.data
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row';
      } else if (rowIndex % 2 == 0) {
        return 'success-row';
      }
      return '';
    }
  },

}
</script>
<style lang="scss"></style>