<!--网络组件-->
<template>
  <div class="app-container networkComponent">
    <div class="page-container networkComponentPage">
      <div class="page-form-title-box">
        <el-form :model="queryParams" class="form-box" ref="queryForm"
                 :inline="true" style="width:100%;">
          <el-form-item label="" prop="searchValue" >
            <el-input
              maxLength="30"
              v-model="queryParams.searchValue"
              placeholder="请输入名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="" prop="moduleType">
            <el-select v-model="queryParams.moduleType" clearable placeholder="请选择设备类型" style="width: 200px">
              <el-option
                v-for="dict in options"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          <p class="page-submit-common-style-button"
             style="float: right;"
             @click="dialogOpen"
             v-hasPermiRouter="['iot:network:add']"
          >新增</p>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="dataList">
          <el-table-column label="名称" align="left" prop="moduleName" show-overflow-tooltip/>
          <el-table-column label="类型" align="left" prop="moduleType" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-for="(item,index) in options" :key="index" v-if="item.value == scope.row.moduleType">{{item.label}}</span>
            </template>
          </el-table-column>
          <el-table-column label="本地地址" align="left" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.localIp&&scope.row.localPort?scope.row.localIp+':'+scope.row.localPort:'-'}}
            </template>
          </el-table-column>
          <el-table-column label="公网地址" align="publicIp" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.publicIp&&scope.row.publicPort?scope.row.publicIp+':'+scope.row.publicPort:'-'}}
            </template>
          </el-table-column>
          <el-table-column label="说明" align="left" prop="remark" width="220" show-overflow-tooltip/>
          <el-table-column label="状态" align="left" prop="state" width="100" show-overflow-tooltip>
            <template slot-scope="scope">{{scope.row.state?'可用':'不可用'}}</template>
          </el-table-column>
          <el-table-column label="创建时间" align="left" prop="createTime" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d} {h}:{i}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="200" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="tableButton(2,scope.row)"
                   v-hasPermiRouter="['iot:network:detail']"
                >详情</p>
                <p class="table-button-p"
                   @click="tableButton(3,scope.row)"
                   v-hasPermiRouter="['iot:network:edit']"
                >编辑</p>
                <p class="table-button-p"
                   @click="tableButton(4,scope.row)"
                   v-hasPermiRouter="['iot:network:del']"
                >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <!--新增弹窗-->
    <el-dialog class="networkComponent-dialog" :title='dialogTitle' width="540px" append-to-body
               :visible.sync="dialogType" v-if="dialogType" @close="dialogOff()"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="networkComponent-dialog-box scrollbar-box">
        <el-form :model="dialogForm" ref="dialogForm"  label-width="110px"
                 :inline="true" :rules="dialogLookType?rules:dialogRules">
          <el-form-item label="名称：" prop="moduleName">
            <el-input
              :disabled="dialogLookType"
              v-model="dialogForm.moduleName"
              maxLength="20"
              placeholder="请输入名称"
              style="width:360px;"
            />
          </el-form-item>
          <el-form-item label="类型：" prop="moduleType">
            <el-select v-model="dialogForm.moduleType"
                       placeholder="请选择类型"
                       :disabled="dialogLookType"
                       clearable style="width:360px;">
              <el-option
                v-for="dict in options"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <div v-if="dialogForm.moduleType == 1 || dialogForm.moduleType == 2 || dialogForm.moduleType == 3">
            <el-form-item label="本地地址：" prop="localIp">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.localIp"
                maxLength="20"
                placeholder="请输入地址"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="本地端口：" prop="localPort">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.localPort"
                maxLength="10"
                placeholder="请输入端口"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="公网地址：" prop="publicIp">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.publicIp"
                maxLength="50"
                placeholder="请输入地址"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="公网端口：" prop="publicPort">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.publicPort"
                maxLength="10"
                placeholder="请输入端口"
                style="width:360px;"
              />
            </el-form-item>
          </div>
          <div v-if="dialogForm.moduleType == 1">
            <el-form-item label="认证key：" prop="authKey">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.authKey"
                maxLength="200"
                placeholder="请输入认证key"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="密匙：" prop="authPassword">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.authPassword"
                maxLength="200"
                placeholder="请输入密匙"
                style="width:360px;"
              />
            </el-form-item>
          </div>
          <div v-if="dialogForm.moduleType == 2">
            <el-form-item label="粘拆包：" prop="dataPacket">
              <el-select v-model="dialogForm.dataPacket"
                         :disabled="dialogLookType"
                         placeholder="请选择粘拆包类型"
                         clearable style="width:360px;">
                <el-option label="不处理" :value="0"></el-option>
                <el-option label="分隔符" :value="1"></el-option>
                <el-option label="自定义脚本" :value="2"></el-option>
                <el-option label="固定长度" :value="3"></el-option>
                <el-option label="长度字段" :value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="dialogForm.dataPacket != 0" label="粘拆包字符：" prop="dataPacketContent">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.dataPacketContent"
                maxLength="200"
                placeholder="请输入粘拆包字符"
                :show-word-limit="true"
                style="width:360px;"
                type="textarea"
                resize="none"
                :rows="2"
              />
            </el-form-item>
          </div>
          <div v-if="dialogForm.moduleType == 4">
            <el-form-item label="远程地址：" prop="publicIp">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.publicIp"
                maxLength="50"
                placeholder="请输入地址"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="远程端口：" prop="publicPort">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.publicPort"
                maxLength="10"
                placeholder="请输入端口"
                style="width:360px;"
              />
            </el-form-item>
            <!--<el-form-item label="clientId：" prop="clientId">-->
              <!--<el-input-->
                <!--:disabled="dialogLookType"-->
                <!--v-model="dialogForm.clientId"-->
                <!--maxLength="30"-->
                <!--placeholder="请输入clientId"-->
                <!--style="width:360px;"-->
              <!--/>-->
            <!--</el-form-item>-->
            <el-form-item label="用户名：" prop="authKey">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.authKey"
                maxLength="30"
                placeholder="请输入用户名"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="密码：" prop="authPassword">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.authPassword"
                maxLength="20"
                placeholder="请输入密码"
                style="width:360px;"
              />
            </el-form-item>
            <el-form-item label="订阅前缀：" prop="prefix">
              <el-input
                :disabled="dialogLookType"
                v-model="dialogForm.prefix"
                maxLength="30"
                placeholder="请输入订阅前缀"
                style="width:360px;"
              />
            </el-form-item>
          </div>
          <div v-if="dialogForm.moduleType == 3 || dialogForm.moduleType == 4">
            <el-form-item label="消息长度：" prop="messageLength">
              <el-input-number v-model="dialogForm.messageLength"
                               :disabled="dialogLookType"
                               clearable style="width:360px;"
                               controls-position="right"
                               :min="10" :max="1000"></el-input-number>
            </el-form-item>
          </div>
          <!--<el-form-item label="自定义参数：">-->
            <div class="for-params-max-box">
              <p class="for-params-title-p">自定义参数：</p>
              <div class="for-params-big-box">
                <div class='for-params-box' v-for="(item,index) in dialogForm.params">
                  <el-form-item label="" :prop="'params.'+index+'.key'" :rules="dialogRules.key">
                    <el-input
                      :disabled="dialogLookType"
                      v-model="item.key"
                      maxLength="30"
                      placeholder="请输入键"
                      style="width:140px;"
                    />
                  </el-form-item>
                  <el-form-item label="" :prop="'params.'+index+'.value'" :rules="dialogRules.value">
                    <el-input
                      :disabled="dialogLookType"
                      v-model="item.value"
                      maxLength="30"
                      placeholder="请输入值"
                      style="width:140px;"
                    />
                  </el-form-item>
                  <span class="el-icon-remove del-span" @click="delItem(index)" v-if="!dialogLookType"></span>
                </div>
              </div>
              <span class="null-span" v-if="!dialogForm.params[0]">未配置</span>
              <span class="el-icon-circle-plus add-span" @click="addItem" v-if="!dialogLookType && !dialogForm.params[4]"></span>
            </div>
          <!--</el-form-item>-->
          <el-form-item label="说明：" prop="remark">
            <el-input
              :disabled="dialogLookType"
              v-model="dialogForm.remark"
              maxLength="200"
              placeholder="请输入说明"
              :show-word-limit="true"
              style="width:360px;"
              type="textarea"
              resize="none"
              :rows="4"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="dialogOff()">{{dialogLookType?'关闭':'取消'}}</p>
        <p class="dialog-footer-button-primary" v-if="!dialogLookType" @click="dialogSubmit">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { iotNetworkList,iotNetworkAdd,iotNetworkUpdate,iotNetworkDelete,iotNetworkDetail } from "@/api/iotDevice/index";
  export default {
    name: 'index',
    data(){
      const doubleCheck = (rule, value, callback) => {
        let self = this;
        let num = 0;
        for(let i=0;i<self.dialogForm.params.length;i++){
          if(value == self.dialogForm.params[i].key){
            num++
          }
        }
        if(num > 1){
          return callback(new Error('参数重复'));
        }else{
          callback();
        }
      };
      return{
        tableButtonType:this.hasPermiDom(['iot:network:detail','iot:network:edit','iot:network:del',]),
        loading:false,
        options:[{label:'HTTP服务',value:1},{label:'TCP服务',value:2},{label:'MQTT服务',value:3},{label:'MQTT客户端',value:4}],
        queryParams:{
          page:1,
          pageSize:20,
          searchValue:"",
          jobGroup:null,
          moduleType:null,
        },
        dataList:[],
        total:0,
        dialogTitle:null,
        dialogType:false,
        dialogForm:{},
        dialogRules:{
          moduleName: [
            { required: true, message: "请输入名称", trigger: "blur" },
            { required: true, message: "请输入名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          moduleType: [
            { required: true, message: "请选择类型", trigger: "blur" },
          ],
          localIp: [
            { required: true, message: "请输入地址", trigger: "blur" },
            { required: true, message: "请输入地址", validator: this.spaceJudgment, trigger: "blur" }
          ],
          localPort: [
            { required: true, message: "请输入端口", trigger: "blur" },
            { required: true, message: "请输入端口", validator: this.spaceJudgment, trigger: "blur" }
          ],
          publicIp: [
            { required: true, message: "请输入地址", trigger: "blur" },
            { required: true, message: "请输入地址", validator: this.spaceJudgment, trigger: "blur" }
          ],
          publicPort: [
            { required: true, message: "请输入端口", trigger: "blur" },
            { required: true, message: "请输入端口", validator: this.spaceJudgment, trigger: "blur" }
          ],
          authKey: [
            { required: true, message: "请输入认证key", trigger: "blur" },
            { required: true, message: "请输入认证key", validator: this.spaceJudgment, trigger: "blur" }
          ],
          authPassword: [
            { required: true, message: "请输入密匙", trigger: "blur" },
            { required: true, message: "请输入密匙", validator: this.spaceJudgment, trigger: "blur" }
          ],
          dataPacket: [
            { required: true, message: "请选择粘拆包类型", trigger: "blur" },
            { required: true, message: "请选择粘拆包类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
          dataPacketContent: [
            { required: true, message: "请输入粘拆包字符", trigger: "blur" },
            { required: true, message: "请输入粘拆包字符", validator: this.spaceJudgment, trigger: "blur" }
          ],
          clientId: [
            { required: true, message: "请输入clientId", trigger: "blur" },
            { required: true, message: "请输入clientId", validator: this.spaceJudgment, trigger: "blur" }
          ],
          username: [
            { required: true, message: "请输入用户名", trigger: "blur" },
            { required: true, message: "请输入用户名", validator: this.spaceJudgment, trigger: "blur" }
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { required: true, message: "请输入密码", validator: this.spaceJudgment, trigger: "blur" }
          ],
          prefix: [
            { required: true, message: "请输入订阅前缀", trigger: "blur" },
            { required: true, message: "请输入订阅前缀", validator: this.spaceJudgment, trigger: "blur" }
          ],
          messageLength: [
            { required: true, message: "请输入消息长度", trigger: "blur" },
            { required: true, message: "请输入消息长度", validator: this.spaceJudgment, trigger: "blur" }
          ],
          key: [
            { required: true, message: "请输入键", trigger: "blur" },
            { required: true, message: "请输入键", validator: this.spaceJudgment, trigger: "blur" },
            { required: true, message: "参数重复", validator: doubleCheck, trigger: "blur" }
          ],
          value: [
            { required: true, message: "请输入值", trigger: "blur" },
            { required: true, message: "请输入值", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        dialogLookType:false,
        rules:{},
      }
    },
    created(){

    },
    mounted(){
      this.getList();
    },
    methods:{
      //弹层关闭
      dialogOff(){
        this.$set(this,'dialogType',false);
      },
      //弹层开启
      dialogOpen(){
        this.$set(this,'dialogForm',{
          moduleName:'',
          moduleType:'',
          localIp:'',
          localPort:'',
          publicIp:'',
          publicPort:'',
          authKey:'',
          authPassword:'',
          dataPacket:'',
          dataPacketContent:'',
          // clientId:'',
          username:'',
          password:'',
          prefix:'',
          messageLength:'',
          params:[],
          remark:'',
        });
        this.$set(this,'dialogTitle','新增');
        this.$set(this,'dialogLookType',false);
        this.$set(this,'dialogType',true);
      },
      //弹层确定
      dialogSubmit(){
        this.$refs["dialogForm"].validate(valid => {
          if (valid) {
            let obj = this.dataProcessing(this.dialogForm,'set');
            if(obj.id){
              iotNetworkUpdate(obj).then(response => {
                this.$set(this,'dialogType',false);
                this.msgSuccess(response.message)
                this.getList();
              });
            }else{
              iotNetworkAdd(obj).then(response => {
                this.$set(this,'dialogType',false);
                this.msgSuccess(response.message)
                this.getList();
              });
            }
          }
        })
      },
      handleQuery(){
        this.$set(this.queryParams,'page',1);
        this.getList();
      },
      resetQuery(){
        this.$set(this,'queryParams',{
          page:1,
          pageSize:20,
          searchValue:"",
          moduleType:null,
        });
        this.getList();
      },
      //获取数据列表
      getList(){
        this.$set(this,'loading',true);
        iotNetworkList(this.queryParams).then(response => {
          this.$set(this,'loading',false);
          this.$set(this,'dataList',response.data.records);
          this.$set(this,'total',response.data.total);
        });
      },
      tableButton(type,row){
        let self = this;
        if(type == 2){
          this.$set(this,'dialogForm',this.dataProcessing(row,'get'));
          this.$set(this,'dialogTitle','详情');
          this.$set(this,'dialogLookType',true);
          this.$set(this,'dialogType',true);
        }else if(type == 3){
          this.$set(this,'dialogForm',this.dataProcessing(row,'get'));
          this.$set(this,'dialogTitle','编辑');
          this.$set(this,'dialogLookType',false);
          this.$set(this,'dialogType',true);
        }else if(type == 4){
          //删除
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            iotNetworkDelete({id:row.id}).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }
      },
      //数据处理
      dataProcessing(data,type){
        let newData = {
          moduleName:data.moduleName,
          moduleType:data.moduleType,
          publicIp:data.publicIp,
          publicPort:data.publicPort,
          remark:data.remark,
          localIp:data.moduleType == 1 || data.moduleType == 2 || data.moduleType == 3?data.localIp:'',
          localPort:data.moduleType == 1 || data.moduleType == 2 || data.moduleType == 3?data.localPort:'',
          authKey:data.moduleType == 1 || data.moduleType == 4?data.authKey:'',
          authPassword:data.moduleType == 1 || data.moduleType == 4 ?data.authPassword:'',
          dataPacket:data.moduleType == 2 ?data.dataPacket:'',
          dataPacketContent:data.moduleType == 2 && data.dataPacket != 0 ?data.dataPacketContent:'',
          // clientId:data.moduleType == 4 ?data.clientId:'',
          // authKey:data.moduleType == 4 ?data.username:'',
          // authPassword:data.moduleType == 4 ?data.password:'',
          prefix:data.moduleType == 4 ?data.prefix:'',
          messageLength:data.moduleType == 3 || data.moduleType == 4 ?data.messageLength:'',
        }
        if(type == 'get'){
          if(data.params){
            let obj = data.params?JSON.parse(data.params):{};
            let list = [];
            Object.keys(obj).forEach((key) => {
              const value = obj[key];
              list.push({
                key:key,
                value:value
              })
            });
            newData.params = list[0]?list:[];
          }else{
            newData.params = [];
          }
        }else if(type == 'set'){
          let obj = {};
          for(let i=0;i<data.params.length;i++){
            obj[data.params[i].key] = data.params[i].value
          }
          newData.params = data.params[0]?JSON.stringify(obj):'';
        }
        if(data.id){
          newData.id = data.id;
        }
        return JSON.parse(JSON.stringify(newData))
      },
      //添加自定义项
      addItem(){
        this.dialogForm.params.push({key:'',value:''})
      },
      //删除自定义项
      delItem(index){
        this.dialogForm.params.splice(index,1);
      },
    },
  }
</script>

<style scoped lang="scss">
  .networkComponent{
    .networkComponentPage{

    }
  }
</style>
<style lang="scss">
  .networkComponent-dialog{
    .networkComponent-dialog-box{
      height:660px;
      .for-params-max-box{
        display: flex;
        .for-params-title-p{
          line-height:40px;
          text-align: right;
          font-size:14px;
          color:#333;
          width:100px;
          margin:0 12px 20px 0;
        }
        .for-params-big-box{
          .for-params-box{
            .del-span{
              font-size:18px;
              color:#FF6666;
              line-height:40px;
              width:30px;
              text-align: center;
              cursor: pointer;
            }
          }
        }
        .add-span{
          font-size:18px;
          color:#0183FA;
          line-height:40px;
          height:40px;
          width:30px;
          text-align: center;
          cursor: pointer;
        }
        .null-span{
          font-size:14px;
          line-height:40px;
          height:40px;
        }
      }
      .el-input__inner,.el-textarea__inner{
        cursor: default!important;
        color:#666!important;
      }
    }
  }
</style>
