<template>
  <div class="page-container iotHardware-addPage">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">{{propsData.id?'编辑':'新增'}}</p>
      <p class="page-top-title-out-p" @click="backPage">返回</p>
      <p class="page-top-title-submit-p" @click="submitForm">提交</p>
    </div>
    <div class="content-box">
      <el-form class="add-form-box" :model="newData" ref="form" :rules="rules" label-width="200px">
        <div class="left-max-box">
          <p class="left-title-p">基础信息</p>
          <div class="left-big-box scrollbar-box">
            <el-form-item label="名称：" prop="deviceName">
              <el-input v-model="newData.deviceName" placeholder="请输入名称" maxLength="20" style="width:500px;"></el-input>
            </el-form-item>
            <el-form-item label="编号：" prop="deviceNo">
              <el-input v-model="newData.deviceNo" :disabled="!!propsData.id" placeholder="请输入编号" maxLength="50" style="width:500px;"></el-input>
            </el-form-item>
            <el-form-item label="设备类型：" prop="typeId">
              <el-select v-model="newData.typeId " @change="selectChange" placeholder="请选择设备类型" style="width: 500px">
                <el-option
                  v-for="dict in options"
                  :key="dict.typeId"
                  :label="dict.typeName"
                  :value="dict.typeId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="设备属性：" prop="attributeId">
              <el-select v-model="newData.attributeId " @change="selectChangeStats" placeholder="请选择设备属性" style="width: 500px">
                <el-option
                  v-for="dict in optionsStats"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="状态：" prop="state">
              <el-radio-group v-model="newData.state">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="楼栋楼层：" prop="address">
              <el-cascader
                style="width:500px;"
                v-model="newData.address"
                @change="cascaderChange"
                clearable
                @clear="cascaderClear"
                placeholder="请选择楼栋楼层"
                :props="{value: 'id', label: 'name',children:'buildFloorVoList'}"
                :options="treeOptions" :show-all-levels="false"></el-cascader>
            </el-form-item>
            <el-form-item label="实验室：" prop="subId">
              <el-select v-model="newData.subId" placeholder="请选择实验室"
                         clearable style="width: 500px">
                <el-option v-for="item in subOptions" :key="item.subId" :label="item.subName+'('+item.roomNum+')'" :value="item.subId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="说明：" prop="remark">
              <el-input style="width:500px;" v-model="newData.remark" placeholder="请输入说明"
                        maxLength='50' type="textarea" resize="none" show-word-limit :autosize="{ minRows: 2, maxRows: 4}">
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="right-max-box">
          <p class="right-title-p">{{forPropsData.modelList[0]?'配置信息':''}}</p>
          <div class="right-big-box scrollbar-box">
            <forElFormItem ref="forElFormItem" :forPropsData="forPropsData"></forElFormItem>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { systemBuildingGetTreeList,laboratorySubRelInfoGetListByFloor } from "@/api/commonality/permission";
  import { iotTypeGetAllTypes,iotTypeGetParamByTypeId,iotAttributeGetByTypeId,iotDeviceAdd,iotDeviceUpdate,iotDeviceDelete } from "@/api/iotDevice/index";
  import forElFormItem from "./forElFormItem.vue";
  export default {
    name: 'addPage',
    props:{
      propsData:{},
    },
    components: {
      forElFormItem
    },
    data(){
      return{
        options:[],
        optionsStats:[],
        subOptions:[],
        treeOptions:[],
        newData:{},
        rules:{
          deviceName: [
            { required: true, message: "请输入名称", trigger: "blur" },
            { required: true, message: "请输入名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          deviceNo: [
            { required: true, message: "请输入编号", trigger: "blur" },
            { required: true, message: "请输入编号", validator: this.spaceJudgment, trigger: "blur" }
          ],
          typeId: [
            { required: true, message: "请选择设备类型", trigger: "blur" },
          ],
          attributeId: [
            { required: true, message: "请选择设备属性", trigger: "blur" },
          ],
          state: [
            { required: true, message: "请选择状态", trigger: "blur" },
          ],
          address: [
            { required: true, message: "请选择楼栋楼层", trigger: "blur" },
          ],
        },
        noRules:{},
        modelList:[],
        forPropsData:{
          formData:{},
          rules:{},
          modelList:[]
        },
      }
    },
    created(){
      this.initialize();
    },
    mounted(){

    },
    methods:{
      //楼栋楼层选中
      cascaderChange(val){
        laboratorySubRelInfoGetListByFloor({floorId:val[val.length-1]}).then(response => {
          this.$set(this.newData,'subId','');
          this.$set(this,'subOptions',response.data);
        })
      },
      //清除楼层选中
      cascaderClear(){
        // this.$set(this.newData,'address',[]);
        this.$set(this.newData,'subId','');
        this.$set(this,'subOptions',[]);
      },
      //设备属性选中
      selectChangeStats(val){
        let self = this;
        for(let i=0;i<self.optionsStats.length;i++){
          if(val == self.optionsStats[i].id){
            self.$set(self.newData,'code',self.optionsStats[i].code);
            self.$set(self.newData,'networkId',self.optionsStats[i].networkId);
          }
        }
      },
      //设备类型选中
      selectChange(val){
        let self = this;
        for(let i=0;i<self.options.length;i++){
          if(val == self.options[i].typeId){
            self.$set(self.newData,'typeKey',self.options[i].typeKey);
            self.$set(self.newData,'typeName',self.options[i].typeName);
          }
        }
        this.$set(this.newData,'attributeId','');
        this.$set(this.newData,'code','');
        this.$set(this.newData,'networkId','');
        iotTypeGetParamByTypeId({typeId:val}).then(response => {
          //处理返回数据
          let formData = {};
          let rules = {};
          let modelList = [];
          for(let i=0;i<response.data.length;i++){
            //form数据
            if(response.data[i].type == 'checkbox' || response.data[i].type == 'datePickerRange'){
              formData[response.data[i].field] = [];
            }else if(response.data[i].type == 'timePickerRange'){
              formData[response.data[i].field] = null;
            }else if(response.data[i].type == 'number' || response.data[i].type == 'slider'){
              formData[response.data[i].field] = 1
            }else{
              formData[response.data[i].field] = '';
            }
            //验证数据处理
            if (response.data[i].required){
              if(response.data[i].type == 'text' || response.data[i].type == 'textarea' || response.data[i].type == 'password'){
                rules[response.data[i].field] = [
                  { required: true, message: "请输入" + response.data[i].label, trigger: "blur" },
                  { required: true, message: "请输入" + response.data[i].label, validator: this.spaceJudgment, trigger: "blur" }
                ];
              }else {
                rules[response.data[i].field] = [
                  { required: true, message: "请选择" + response.data[i].label, trigger: "blur" },
                ];
              }
            }
            //model数据处理
            let obj = {
              label:response.data[i].label,
              field:response.data[i].field,
              modelType:response.data[i].type,
              required: response.data[i].required,
              models:response.data[i].iotParamValueModels
            }
            modelList.push(obj)
          }
          this.$set(this,'forPropsData',{formData:formData,rules:rules,modelList:modelList});
          if(this.$refs.forElFormItem.$refs["form"]){
            this.$refs.forElFormItem.$refs["form"].resetFields();
          }
        });
        iotAttributeGetByTypeId({typeId:val}).then(response => {
          this.$set(this,'optionsStats',response.data);
        });
      },
      //初始化
      initialize(){
        //设备类型列表
        iotTypeGetAllTypes({}).then(response => {
          this.$set(this,'options',response.data);
        });
        //楼栋楼层
        systemBuildingGetTreeList({}).then(response => {
          let list = JSON.parse(JSON.stringify(response.data));
          pushNode(list)
          function pushNode(list){
            for(let i=0;i<list.length;i++){
              if(list[i].type != 3 && !list[i].buildFloorVoList[0]){
                list.splice(i,1)
                i--
              }else if(list[i].type == 3){
                delete list[i].buildFloorVoList;
              }else{
                pushNode(list[i].buildFloorVoList)
              }
            }
          }
          this.$set(this,'treeOptions',list);
        })
        //编辑
        if(this.propsData.id){
          this.$set(this,'newData',{
            deviceName:this.propsData.deviceName,
            deviceNo:this.propsData.deviceNo,
            typeId:this.propsData.typeId,
            typeKey:this.propsData.typeKey,
            typeName:this.propsData.typeName,
            attributeId:this.propsData.attributeId,
            code:this.propsData.code,
            networkId:this.propsData.networkId,
            state:this.propsData.state,
            address:[this.propsData.schoolId,this.propsData.buildId,this.propsData.floorId],
            subId:this.propsData.subjectId,
            remark:this.propsData.remark,
          });
          let minData = this.propsData.reservedField?JSON.parse(this.propsData.reservedField):{};
          laboratorySubRelInfoGetListByFloor({floorId:this.propsData.floorId}).then(response => {
            this.$set(this,'subOptions',response.data);
          })
          iotTypeGetParamByTypeId({typeId:this.propsData.typeId}).then(response => {
            //处理返回数据
            let formData = {};
            let rules = {};
            let modelList = [];
            for(let i=0;i<response.data.length;i++){
              //form数据
              formData[response.data[i].field] = minData[response.data[i].field];
              //验证数据处理
              if (response.data[i].required){
                if(response.data[i].type == 'text' || response.data[i].type == 'textarea' || response.data[i].type == 'password'){
                  rules[response.data[i].field] = [
                    { required: true, message: "请输入" + response.data[i].label, trigger: "blur" },
                    { required: true, message: "请输入" + response.data[i].label, validator: this.spaceJudgment, trigger: "blur" }
                  ];
                }else {
                  rules[response.data[i].field] = [
                    { required: true, message: "请选择" + response.data[i].label, trigger: "blur" },
                  ];
                }
              }
              //model数据处理
              let obj = {
                label:response.data[i].label,
                field:response.data[i].field,
                modelType:response.data[i].type,
                required: response.data[i].required,
                models:response.data[i].iotParamValueModels
              }
              modelList.push(obj)
            }
            this.$set(this,'forPropsData',{formData:formData,rules:rules,modelList:modelList});
            if(this.$refs.forElFormItem.$refs["form"]){
              this.$refs.forElFormItem.$refs["form"].resetFields();
            }
          })
          iotAttributeGetByTypeId({typeId:this.propsData.typeId}).then(response => {
            this.$set(this,'optionsStats',response.data);
          });
        }else{
          this.$set(this,'newData',{
            deviceName:'',
            deviceNo:'',
            typeId:'',
            typeKey:'',
            typeName:'',
            attributeId:'',
            code:'',
            networkId:'',
            state:true,
            address:[],
            subId:'',
            remark:'',
          });
        }
      },
      // 返回按钮
      backPage(){
        this.$parent.tableButton(6);
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(maxValid => {
          if (maxValid) {
            if(this.forPropsData.modelList[0]){
                this.$refs.forElFormItem.$refs["form"].validate(valid => {
                  if (valid) {
                    this.dataProcessing('1');
                  }
                })
            }else{
              this.dataProcessing('2');
            }
          }
        })
      },
      //处理数据并提交
      dataProcessing(type){
        let self = this;
        let obj = {
          deviceName:this.newData.deviceName,
          deviceNo:this.newData.deviceNo,
          typeId:this.newData.typeId,
          typeKey:this.newData.typeKey,
          typeName:this.newData.typeName,
          attributeId:this.newData.attributeId,
          code:this.newData.code,
          networkId:this.newData.networkId,
          state:this.newData.state,
          remark:this.newData.remark,
          reservedField:type==1?JSON.stringify(this.$refs.forElFormItem.formData):'',
          // reservedField:type==1 ? (this.$refs.forElFormItem.formData?JSON.stringify(this.$refs.forElFormItem.formData):''):'',
        };
        //获取校区-楼栋-楼层数据
        if(self.newData.address[0]){
          for(let i=0;i<self.treeOptions.length;i++){
            if(self.treeOptions[i].id == self.newData.address[0]){
              for(let o=0;o<self.treeOptions[i].buildFloorVoList.length;o++){
                if(self.treeOptions[i].buildFloorVoList[o].id == self.newData.address[1]){
                  for(let x=0;x<self.treeOptions[i].buildFloorVoList[o].buildFloorVoList.length;x++){
                    if(self.treeOptions[i].buildFloorVoList[o].buildFloorVoList[x].id == self.newData.address[2]){
                      obj.schoolId = self.treeOptions[i].id;
                      obj.schoolName = self.treeOptions[i].name;
                      obj.buildId = self.treeOptions[i].buildFloorVoList[o].id;
                      obj.buildName = self.treeOptions[i].buildFloorVoList[o].name;
                      obj.floorId = self.treeOptions[i].buildFloorVoList[o].buildFloorVoList[x].id;
                      obj.floorName = self.treeOptions[i].buildFloorVoList[o].buildFloorVoList[x].name;
                    }
                  }
                }
              }
            }
          }
        }else{
          obj.schoolId = '';
          obj.schoolName = '';
          obj.buildId = '';
          obj.buildName = '';
          obj.floorId = '';
          obj.floorName = '';
        }
        //获取实验室数据
        if(this.newData.subId){
          for(let i=0;i<self.subOptions.length;i++){
            if(self.subOptions[i].subId == self.newData.subId){
              obj.subjectId = self.subOptions[i].subId
              obj.subjectName = self.subOptions[i].subName
              obj.room = self.subOptions[i].roomNum
            }
          }
        }else{
          obj.subjectId = ''
          obj.subjectName = ''
          obj.room = ''
        }
        if(this.propsData.id){
          // 编辑
          obj.id = this.propsData.id;
          iotDeviceUpdate(obj).then(response => {
            this.msgSuccess(response.message)
            this.backPage();
          });
        }else{
          // 新增
          iotDeviceAdd(obj).then(response => {
            this.msgSuccess(response.message)
            this.backPage();
          });
        }
      },
    },
  }
</script>

<style scoped lang="scss">
  .iotHardware-addPage{
    .content-box{
      flex:1;
      display: flex;
      overflow: hidden;
      .add-form-box{
        flex:1;
        display: flex;
        overflow: hidden;
        .left-max-box{
          flex:1;
          display: flex;
          flex-direction: column;
          .left-title-p{
            line-height:40px;
            padding-left:40px;
            margin-top:10px;
          }
          .left-big-box{
            flex:1;
          }
        }
        .right-max-box{
          flex:1;
          display: flex;
          flex-direction: column;
          .right-title-p{
            line-height:40px;
            padding-left:40px;
            margin-top:10px;
          }
          .right-big-box{
            flex:1;
          }
        }
      }
    }
  }
</style>
