<template>
 <el-container>
  <el-main>
  <el-row>
  <el-col :xs="20" :sm="20" :md="20" :lg="6" :xl="6">
 天车: <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="8" :xl="8">
  设备:<el-cascader style="width:50%"
  filterable
    :options="selectedRootDevice.children"
    @change="selectDeviceChangeForDataSource"
    :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">
    <p>添加数据源</p>
    <el-form style="margin-top:10px" :inline="false" :model="dataSource"  status-icon :rules="rules" ref="dataSourceForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="名称" prop="name">
    <el-input  v-model="dataSource.name" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="地址" prop="address">
    <el-input  v-model="dataSource.address" autocomplete="off"></el-input>
  </el-form-item>

  <!-- <el-form-item label="主题" prop="publishTopic">
    <el-input  v-model="dataSource.publishTopic" autocomplete="off"></el-input>
  </el-form-item> -->
 
    <el-form-item label="状态">
    <el-switch v-model="dataSource.enable" active-color="#13ce66" inactive-color="#ff4949">
    </el-switch>
   </el-form-item>
  <el-form-item label="绑定设备" prop="deviceId">
     <el-cascader style="width:50%"
  filterable
    :options="rootDevices"
    @change="selectDeviceChange"
    :props="{ checkStrictly: true }"
    clearable></el-cascader>
  </el-form-item>
    <el-form-item label="数据类型" prop="dataTypeId">
                    <el-select v-model="dataSource.dataTypeId" style="width:50%">
                    <el-option v-for="type in allDataTypes" :key="type.id" :label="type.name+';'+type.remark" :value="type.id"></el-option>
                   
                    </el-select>
                  </el-form-item>
  <el-form-item label="备注" >
    <el-input v-model="dataSource.remark"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="addDataSource('dataSourceForm')">添加</el-button>
    <el-button @click="resetForm('dataSourceForm')">取消</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="dataSources"
    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.address }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="主题"
      width="100">
      <template slot-scope="scope">
         <span >{{ scope.row.publishTopic }}</span>
      </template>
    </el-table-column>
      <el-table-column
      label="状态"
      width="100">
      <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949">
    </el-switch>      </template>
    </el-table-column>
    <el-table-column
      label="所属设备"
      width="200">
      <template slot-scope="scope">
         <span >{{ scope.row.deviceInfo }}</span>
      </template>
    </el-table-column>
     <el-table-column
      label="数据类型"
      width="100">
      <template slot-scope="scope">
         <span >{{ scope.row.dataTypeInfo }}</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="备注"
      width="280">
      <template slot-scope="scope">
        <span >{{ scope.row.remark }}</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
    },
    
    allDataTypes() {
      return this.$store.getters.allDataTypes
    },
  },
    data() {
      return {
        dialogVisible: false,
        dataSources:[],
        clickedNode:{},
        selectedDeviceID:null,
        selectedRootDevice:{},
        addDialogVisible:false,
        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' },
          ],
            deviceId: [
            { required: true, message: '请选择设备', 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 
        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
        
      
      },
      selectDeviceChangeForDataSource(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)
        
        this.dataSources=device.dataSources
      },
      selectRootDeviceChanged(data){
        console.log('selectRootDeviceChanged',data)
        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 d=this.findDeviceById(this.rootDevices,selectedDeviceID)
        console.log('selected device ',d)
        this.clickedNode=d
        this.dataSource.deviceId=d.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('dataSource/deleteDataSource',row).then(res=>{
            if(res.data.success){
               this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.$store.dispatch('device/getRootDevices').then(res=>{
                if(this.selectedDeviceID!=null){
                  console.log('deleteed ,refresh rootDevice',res.data.data)
                  var device= this.findDeviceById(res.data.data,this.selectedDeviceID)
                  this.dataSources=device.dataSources
                }
                else{
                  console.log('not selected deviceId')
                  var device= this.findDeviceById(res.data.data,this.selectedRootDevice.id)
                  this.dataSources=device.childrenDataSources
                }
              
              })
              // this.$store.dispatch("dataSource/getAllDataSources")

            }
            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: '已取消删除'
          });          
        });
      },
      addDataSource(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('start to add dataSource0',this.dataSource)
            this.$store.dispatch('dataSource/addDataSource',this.dataSource).then(res=>{
                if(res.data.success)
                {
                  this.$message({message: '添加数据源成功',  type: 'success'});
                  this.$store.dispatch("dataSource/getAllDataSources")
                  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("dataType/getAllDataTypes")


  },
  }
</script>