<template>
 <el-container>
  <el-main>
  <el-row>
  <el-col :xs="20" :sm="20" :md="20" :lg="5" :xl="5">
快速筛选: <el-select @change="selectRootDeviceChanged"  v-model="selectedRootDevice" placeholder="请选择天车">
    <el-option
      v-for="item in rootDevices"
      :key="item.id"
      :label="item.name"
      :value="item">
    </el-option>
  </el-select>
  </el-col>
  <el-col :xs="20" :sm="20" :md="20" :lg="15" :xl="15">
  设备:<el-cascader style="width:50%"
  filterable
    :options="selectedRootDevice.children"
    @change="selectDeviceChanged"
    :props="{ checkStrictly: true }"
    clearable></el-cascader>
  </el-col>
  <el-col :xs="20" :sm="20" :md="20" :lg="4" :xl="4">

  <el-button @click="showAddDataSource" type="success">添加设备</el-button>
  </el-col>
  </el-row>
  <el-divider></el-divider>

  <el-dialog
            title="添加设备"
            :visible.sync="addDialogVisible"
            width="70%" :close-on-click-modal="false" :show-close="false"
          >
    <el-card class="box-card">
    <el-form style="margin-top:10px" :inline="false" :model="addDevice"  status-icon :rules="rules" ref="addDeviceForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="父设备" prop="fatherId">
     <el-cascader style="width:50%"
  filterable
    :options="rootDevices"
    @change="selectDeviceChange"
    :props="{ checkStrictly: true }"
    clearable></el-cascader>
  </el-form-item>
  <el-form-item label="名称" prop="name">
    <el-input  v-model="addDevice.name" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="运行时间" >
  <el-row>
  <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input type="number" placeholder="请输入内容" v-model="wHour">
      <template slot="append">小时</template>
        </el-input>

      </el-col>
      <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input placeholder="请输入内容" v-model="wMinute">
      <template slot="append">分</template>
        </el-input>

      </el-col>
       <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input placeholder="请输入内容" v-model="wSecond">
      <template slot="append">秒</template>
        </el-input>

      </el-col>
      </el-row>
  </el-form-item>
  <el-form-item label="寿命时间" >
     <el-row>
  <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input placeholder="请输入内容" v-model="lHour">
      <template slot="append">小时</template>
        </el-input>

      </el-col>
      <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input placeholder="请输入内容" v-model="lMinute">
      <template slot="append">分</template>
        </el-input>

      </el-col>
       <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="4">
     <el-input placeholder="请输入内容" v-model="lSecond">
      <template slot="append">秒</template>
        </el-input>

      </el-col>
      </el-row>
  </el-form-item>
 


  <el-form-item label="备注" >
    <el-input v-model="addDevice.remark"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="addDeviceForm('addDeviceForm')">添加</el-button>
    <el-button @click="resetForm('addDeviceForm')">取消</el-button>
  </el-form-item>
</el-form>

</el-card>
  </el-dialog>
    <template >
<el-card style="margin-top:20px" class="box-card">
    <p>天车信息</p>
  <el-table
    :data="deviceList"
    style="width: 100%">
    <el-table-column
      label="ID"
      width="80">
      <template slot-scope="scope">
        <span>{{ scope.row.id }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="名称"
      width="100">
      <template slot-scope="scope">
        <span >{{ scope.row.name }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="全称"
      width="200">
      <template slot-scope="scope">
         <span >{{ scope.row.fullName }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="子设备数量"
      width="100">
      <template slot-scope="scope">
        <span >{{ scope.row.childrenCount }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="运行时间"
      width="150">
      <template slot-scope="scope">
        <span >{{ scope.row.workTime }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="备注"
      width="100">
      <template slot-scope="scope">
         <span >{{ scope.row.remark }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="创建时间"
      width="150">
      <template slot-scope="scope">
        <span >{{ scope.row.createTime }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="更新时间"
      width="150">
      <template slot-scope="scope">
        <span >{{ scope.row.updateTime }}</span>
      </template>
    </el-table-column>
     
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
      <el-dialog
            title="修改数据源"
            :visible.sync="dialogVisible"
            width="70%" :close-on-click-modal="false" :show-close="false"
          >
            <el-container>
              <el-main>
                <el-form ref="updatedataSourceForm" style="margin-top:10px" :model="editdataSource" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
                <el-form-item label="名称" prop="apiUrl">
                    <el-input v-model="editdataSource.name" autocomplete="off" />
                  </el-form-item>
                  <el-form-item label="公式" prop="username">
                    <el-input v-model="editdataSource.address" />
                  </el-form-item>
     
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="editdataSource.remark" autocomplete="off" />
                  </el-form-item>
                  <el-form-item label="采集方法" prop="method">
                    <el-select v-model="editdataSource.method">
                    <el-option label="全部" value="ALL"></el-option>
                    <el-option label="查看" value="GET"></el-option>
                    <el-option label="添加" value="PUT"></el-option>
                    <el-option label="修改" value="POST"></el-option>
                    <el-option label="删除" value="DELETE"></el-option>
                    </el-select>
                  </el-form-item>

                 
                  <el-form-item>
                    <el-button type="primary" @click="updatedataSource('updatedataSourceForm')">确认</el-button>
                    <el-button @click="cancel()">取消</el-button>
                  </el-form-item>
                </el-form>
              </el-main>
            </el-container>
          </el-dialog>
</el-card>
</template>

  </el-main>
</el-container>
  
</template>
<script>
  export default {
    computed: {
    allDataSources() {
      return this.$store.getters.allDataSources
    },
     rootDevices(){
      return this.$store.getters.rootDevices
    },
    deviceList(){
       return this.$store.getters.deviceList
    },
    
    allDataTypes() {
      return this.$store.getters.allDataTypes
    },
  },
    data() {
      return {
        dialogVisible: false,
        wHour:0,
        wMinute:0,
        wSecond:0,
        lHour:0,
        lMinute:0,
        lSecond:0,
        dataSources:[],
        clickedNode:{},
        selectedDeviceID:null,
        selectedRootDevice:{},
        addDialogVisible:false,
        addDevice:{
          name:'',
          workTime:'',
          lifeTime:'',
          remark:'',
          fatherId:'',
         
        },
        dataSource: {
          name: '',
          address:'',
          remark:'',
          publishTopic:'',
          enable:true,
          dataTypeId:'',
          deviceId:'',
        },
        editdataSource:{
          name: "",
          address: "",
          method: '',
          valueType:'' ,
          remark:'',
        },
        rules: {
           name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
           publishTopic: [
            { required: true, message: '请输入主题', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
           dataTypeId: [
            { required: true, message: '请选择数据类型', trigger: 'blur' },
          ],
            fatherId: [
            { required: true, message: '请选择父设备', trigger: 'blur' },
          ],
          workTime:[
            { required: true, message: '运行时间不能为空'},
            { type: 'number', message: '运行时间为数字值'},
            { pattern: "^\d+$", message: '不能小于0',trigger: 'blur'} 
  
          ],
           lifeTime:[
            { required: true, message: '运行时间不能为空'},
            { type: 'number', message: '运行时间为数字值'},
            { pattern: "^\d+$", message: '不能小于0',trigger: 'blur'} 
  
          ],
        
        },
      }
    },
    methods: {
      handleEdit(index, row) {
        console.log(index, row);
        this.editdataSource=row
        this.dialogVisible=true
      },
      showAddDataSource(){
        this.addDialogVisible=true
      },
        findDeviceById(devices,id){
        var tmp=null
        for(var i in devices){
          console.log('device id '+devices[i].id,id)
          if(devices[i].id===id){
            console.log('finded',devices[i])
            tmp=devices[i]
            
            return tmp
            
          }
          else{
            console.log('find children',devices[i])
            tmp= this.findDeviceById(devices[i].children,id)
            if(tmp!=null) break
          }
        }
        return tmp
       
      
      },
   
      selectDeviceChanged(data){
         console.log('select device change ',data)
        var selectedDeviceID=data[data.length-1]
        this.selectedDeviceID=selectedDeviceID

        console.log('selected deviceID ',data[data.length-1])
        var device=this.findDeviceById(this.rootDevices,selectedDeviceID)
        var tmpList=[]
        tmpList.push(device)
        this.$store.commit("device/SET_DEVICE_LIST",tmpList)
        // this.dataSources=device.dataSources
      },
      selectRootDeviceChanged(data){
        console.log('selectRootDeviceChanged',data)
        this.$store.commit("device/SET_DEVICE_LIST",data.allChildren)
        //this.dataSources=data.childrenDataSources

      },
      selectDeviceChange(data){
        console.log('select device change ',data)
        var selectedDeviceID=data[data.length-1]
        console.log('selected deviceID ',data[data.length-1])
        console.log('start to select  from devices',this.rootDevices)

        var device=this.findDeviceById(this.rootDevices,selectedDeviceID)
        console.log('selected device ',device)
        this.addDevice.fatherId=device.id
       
      },
      cancel() {
      // this.$store.dispatch('role/getAllRoles')
    //  this.$store.dispatch('user/getAllUsers')
      this.dialogVisible = false
    },

    updateDataSource(formName) {
      console.log('start to update dataSource-1', this.editdataSource)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('start to update dataSource0', this.editUser)

          this.$store.dispatch('dataSource/updateDataSource', this.editdataSource).then(res => {
            if (res.data.success) {
              this.$message({ message: '修改接口数据源成功', type: 'success' })
              this.editdataSource=res.data.data
              this.$store.dispatch('dataSource/getAllalldataSources')
            } else {
              console.log('修改数据源失败!', res)
              this.$message({ message: '修改数据源失败!' + res.data.info, type: 'error' })
            }
          }
          )
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

      handleDelete(index, row) {
        console.log(index, row);
         this.$confirm('此操作将永久删除此设备及其所有子设备和数据记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('device/deleteDevice',row).then(res=>{
            if(res.data.success){
               this.$message({
                type: 'success',
                message: '删除成功!'
              });
               this.selectedRootDevice={}
               this.$store.dispatch('device/getAllDevices')
              this.$store.dispatch('device/getRootDevices')      

            }
            else{
              this.$message({message:'删除失败!'+res.data.info,type:'error'});

            }
          }).catch(error=>{
              this.$message({message:'删除失败!'+res.data.info,type:'error'});

          })
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      addDeviceForm(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addDevice.workTime=this.wHour*60*60+this.wMinute*60+this.wSecond;
            this.addDevice.lifeTime=this.lHour*60*60+this.lMinute*60+this.lSecond;
            console.log('start to add device0',this.addDevice)
            this.$store.dispatch('device/addDevice',this.addDevice).then(res=>{
                if(res.data.success)
                {
                  this.$message({message: '添加设备成功',  type: 'success'});
                  // this.$store.dispatch("dataSource/getAllDataSources")
                 this.$store.dispatch('device/getAllDevices')
                 this.$store.dispatch('device/getRootDevices')
                  // this.selectedRootDevice={}
                  // this.selectedDeviceID=null
                }
                else{
                  console.log('添加设备失败!',res)
                  this.$message({message:'添加设备失败!'+res.data.info,type:'error'});
                }
            }
            )

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
       resetForm(formName) {
        this.$refs[formName].resetFields();
        this.addDialogVisible=false
      }
    },
    created() {
      console.log('created')
      // this.$store.dispatch("dataSource/getAllDataSources")
      this.$store.dispatch('device/getRootDevices')
      this.$store.dispatch('device/getAllDevices')
      // this.$store.dispatch("dataType/getAllDataTypes")


  },
  }
</script>