<template>
  <div class="page-container hardwareClassification-functionPage">
    <div class="table-title-box">
      <el-form :model="queryParams" class="form-box" ref="queryForm"
               :inline="true" style="width:100%;">
        <el-form-item label="" prop="title" style="float: right">
          <el-col :span="1.5" style="margin-right:10px;">
            <p class="page-submit-common-style-button"
               @click="dialogOpen"
            >新增</p>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-content-box">
      <el-table class="table-box" v-loading="loading" border :data="dataList">
        <el-table-column label="名称"  prop="name" width="150" show-overflow-tooltip/>
        <el-table-column label="接口"  prop="reqApi" show-overflow-tooltip/>
        <el-table-column label="参数"  prop="reqParams" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="clickCopy" @click="clickCopy(scope.row.reqParams)">{{scope.row.reqParams}}</span>
          </template>
        </el-table-column>
        <el-table-column label="请求方式"  prop="reqMethod" width="150" show-overflow-tooltip/>
        <el-table-column label="说明"  prop="remark" width="150" show-overflow-tooltip/>
        <el-table-column label="状态"  prop="state" width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-switch
              @click.native="tableButton(4,scope.row)"
              class="switch captcha-img"
              :active-value="true"
              :inactive-value="false"
              active-color="#0183FA"
              inactive-color="#999"
              v-model="scope.row.state"
              active-text="启用"
              inactive-text="停用"
              disabled
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间"  prop="createTime" width="160" 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="操作"  class-name="small-padding fixed-width" width="140">
          <template slot-scope="scope">
            <div class="table-button-box">
              <p class="table-button-null"></p>
              <!--<p class="table-button-p"-->
              <!--@click="tableButton(1,scope.row)"-->
              <!--&gt;详情</p>-->
              <p class="table-button-p"
                 @click="tableButton(2,scope.row)"
              >编辑</p>
              <p class="table-button-p"
                 @click="tableButton(3,scope.row)"
              >删除</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>
    <!--新增弹窗-->
    <el-dialog class="hardwareClassification-functionPage-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">
      <el-form :model="dialogForm" ref="dialogForm" :inline="true" :rules="dialogRules" class="addCheckPage-min" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入名称" maxLength="20" style="width:320px;"/>
        </el-form-item>
        <el-form-item label="接口" prop="reqApi">
          <el-input v-model="dialogForm.reqApi" placeholder="请输入接口" maxLength="100" style="width:320px;"/>
        </el-form-item>
        <el-form-item label="请求方式" prop="reqMethod">
          <el-select v-model="dialogForm.reqMethod " placeholder="请选择请求方式" style="width: 320px">
            <el-option label="get" value="GET"/>
            <el-option label="post" value="POST"/>
          </el-select>
        </el-form-item>
        <div class="form-flex-box">
          <p class="form-title"><span>*</span>输入参数</p>
          <div class="form-for-max-box">
            <div class="form-for-box" v-for="(item,index) in dialogForm.reqParams">
              <p class="form-index-p">{{index+1}}</p>
              <div class="form-for-big-box">
                <div class="form-for-min-box">
                  <el-form-item label="" :prop="'reqParams.'+ index +'.keyName'" :rules="dialogRules.keyName">
                    <el-input v-model="item.keyName" placeholder="请输入键" maxLength="20" style="width:150px;"/>
                  </el-form-item>
                  <el-form-item label="" :prop="'reqParams.'+ index +'.keyType'" :rules="dialogRules.keyType">
                    <el-select v-model="item.keyType " placeholder="请选择类型" style="width: 120px">
                      <el-option v-for="(optionItem,optionIndex) in optionList" :key="optionItem.value" :label="optionItem.label" :value="optionItem.value"/>
                    </el-select>
                  </el-form-item>
                  <span class="el-icon-remove for-button-icon"
                        style="color:#FF6666;"
                        @click="delMin(index)"></span>
                </div>
                <el-form-item label="" v-if="item.keyType === 'argument'" :prop="'reqParams.'+ index +'.keyArgument'" :rules="dialogRules.keyArgument">
                  <el-input v-model="item.keyArgument" placeholder="请输入参数" maxLength="100" style="width:280px;"/>
                </el-form-item>
                <el-form-item label="" v-if="item.keyType === 'file'" :prop="'reqParams.'+ index +'.keyFile'" :rules="dialogRules.keyFile">
                  <el-upload
                    class="hardwareClassification-functionPage-dialog-upload"
                    style="height:40px;"
                    :action="uploadFile"
                    :show-file-list="false"
                    :on-success="(res)=>handleAvatarSuccess(res,index)"
                    :headers="headers"
                    :before-upload="(file)=>beforeAvatarUpload(file)">
                    <div class="up-box">
                      <p class="up-text-p">{{item.keyFile}}</p>
                      <p class="up-text-p" v-if="!item.keyFile">请点击上传文件</p>
                    </div>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
          </div>
          <span class="el-icon-circle-plus for-button-icon"
                style="color:#0183FA;"
                v-if="dialogForm.reqParams.length<5" @click="addMin"></span>
        </div>
        <el-form-item label="说明" prop="remark">
          <el-input placeholder="请输入说明" maxLength='100' type="textarea" style="width:320px;"
                    resize="none" v-model="dialogForm.remark" show-word-limit :autosize="{ minRows: 2, maxRows: 2}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="dialogOff()">取消</p>
        <p class="dialog-footer-button-primary" @click="dialogSubmit">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { iotHardwareFunctionList,iotHardwareFunctionAdd,iotHardwareFunctionUpdate,iotHardwareFunctionDelete } from "@/api/iotDevice/index";
  import { getToken } from "@/utils/auth";
  export default {
    name: 'functionPage',
    data(){
      const doubleCheck = (rule, value, callback) => {
        let self = this;
        let num = 0;
        for(let i=0;i<self.dialogForm.reqParams.length;i++){
          if(value == self.dialogForm.reqParams[i].keyName){
            num++
          }
        }
        if(num > 1){
          return callback(new Error('参数重复'));
        }else{
          callback();
        }
      };
      return{
        //上传相关
        uploadFile: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization:getToken(),
        },
        loading:false,
        queryParams:{
          typeId:this.$parent.propsData.hardwareTypeId,
          page:1,
          pageSize:20,
          searchValue:"",
          state :null,
        },
        dataList:[],
        total:0,
        //弹层
        dialogTitle:null,
        dialogType:false,
        dialogForm:{
          typeId:this.$parent.propsData.hardwareTypeId,
          name:"",
          reqApi:"",
          reqMethod:null,
          reqParams:[{
            keyName:'',
            keyType:'',
            keyArgument:'',
            keyFile:'',
          }],
          files:"",
          remark:"",
        },
        dialogRules:{
          name: [
            { required: true, message: "请输入名称", trigger: "blur" },
            { required: true, message: "请输入名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          reqApi: [
            { required: true, message: "请输入接口", trigger: "blur" },
            { required: true, message: "请输入接口", validator: this.spaceJudgment, trigger: "blur" }
          ],
          reqMethod: [
            { required: true, message: "请选择请求方式", trigger: "blur" },
            { required: true, message: "请选择请求方式", validator: this.spaceJudgment, trigger: "blur" }
          ],
          keyName: [
            { required: true, message: "请输入键", trigger: "blur" },
            { required: true, message: "请输入键", validator: this.spaceJudgment, trigger: "blur" },
            { required: true, message: "参数重复", validator: doubleCheck, trigger: "blur" }
          ],
          keyType: [
            { required: true, message: "请选择类型", trigger: "blur" },
            { required: true, message: "请选择类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
          keyFile: [
            { required: true, message: "请上传文件", trigger: "blur" },
            { required: true, message: "请上传文件", validator: this.spaceJudgment, trigger: "blur" }
          ],
          keyArgument: [
            { required: true, message: "请输入参数", trigger: "blur" },
            { required: true, message: "请输入参数", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        optionList:[
          { value:'data',label:'数据' },
          { value:'argument',label:'参数' },
          { value:'file',label:'文件' },
        ],
      }
    },
    created(){
      this.getList();
    },
    mounted(){

    },
    methods:{
      addMin(){
        if(this.dialogForm.reqParams.length>4){
          this.msgError('最多可添加5个参数')
        }else{
          this.dialogForm.reqParams.push({
            keyName:'',
            keyType:'',
            keyArgument:'',
            keyFile:'',
          });
        }
      },
      delMin(index){
        this.dialogForm.reqParams.splice(index,1);
      },
      //弹层关闭
      dialogOff(){
        this.$set(this,'dialogType',false);
      },
      //弹层开启
      dialogOpen(){
        this.dialogFormReset();
        this.$set(this,'dialogTitle','新增');
        this.$set(this,'dialogType',true);
      },
      dialogFormReset(){
        this.$set(this,'dialogForm',{
          typeId:this.$parent.propsData.hardwareTypeId,
          name:"",
          reqApi:"",
          reqMethod:null,
          reqParams:[{
            keyName:'',
            keyType:'',
            keyArgument:'',
            keyFile:'',
          }],
          files:"",
          remark:"",
        });
      },
      //dialog提交按钮
      dialogSubmit(){
        this.$refs["dialogForm"].validate(valid => {
          if (valid) {
            let obj = JSON.parse(JSON.stringify(this.dialogForm))
            obj.reqParams = JSON.stringify(obj.reqParams);
            if(obj.id){
              iotHardwareFunctionUpdate(obj).then(response => {
                this.msgSuccess(response.message)
                this.dialogOff();
                this.getList();
              });
            }else{
              iotHardwareFunctionAdd(obj).then(response => {
                this.msgSuccess(response.message)
                this.dialogOff();
                this.getList();
              });
            }
          }
        })
      },
      //功能
      getList(){
        let obj = JSON.parse(JSON.stringify(this.queryParams))
        iotHardwareFunctionList(obj).then(response => {
          this.$set(this,'dataList',response.data.records);
          this.$set(this,'total',response.data.total);
        });
      },
      handleQuery(){
        this.$set(this.queryParams,'page',1);
        this.getList();
      },
      resetQuery(){
        this.$set(this,'queryParams',{
          typeId:this.$parent.propsData.hardwareTypeId,
          page:1,
          pageSize:20,
          searchValue:"",
          state :null,
        });
        this.getList();
      },
      //按钮
      tableButton(type,row){
        let self = this;
        if(type == 1){
          //详情
        }else if(type == 2){
          //编辑
          let obj = JSON.parse(JSON.stringify(row));
          obj.reqParams = JSON.parse(obj.reqParams);
          this.$set(this,'dialogForm',obj);
          this.$set(this,'dialogTitle','编辑');
          this.$set(this,'dialogType',true);
        }else if(type == 3){
          //删除
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            iotHardwareFunctionDelete({id:row.id}).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }else if(type == 4){
          let text = row.state  ? "停用" : "启用";
          this.$confirm('是否确认' + text + '?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            let obj = JSON.parse(JSON.stringify(row));
            obj.state = !obj.state;
            iotHardwareFunctionUpdate(obj).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }
      },
      //上传相关
      handleAvatarSuccess(res,index) {
        this.$set(this.dialogForm.reqParams[index],'keyFile',res.data.url);
      },
      beforeAvatarUpload(file) {
        return new Promise((resolve, reject) => {
          if(file.size > 10500000){
            this.msgError('上传大小不能超过10M')
            reject();
          }else{
            resolve()
          }
        })
      },
    },
  }
</script>

<style scoped lang="scss">
  .hardwareClassification-functionPage{
    flex:1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .table-title-box{
      margin-top:20px;
    }
    .table-content-box{
      flex:1;
      margin:0 20px 20px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
</style>
<style lang="scss">
  .hardwareClassification-functionPage-dialog{
    .form-flex-box{
      display: flex;
      .form-title{
        width:90px;
        font-size:14px;
        color:#333;
        line-height:40px;
        text-align: right;
        margin-right:10px;
        margin-bottom:20px;
        span{
          color:#FF6666;
          margin-right:4px;
        }
      }
      .form-for-max-box{
        .form-for-box{
          display: flex;
          .form-index-p{
            width:20px;
            height:20px;
            line-height:22px;
            font-size:16px;
            margin:10px;
            border-radius:50%;
            text-align: center;
            color:#fff;
            background-color: #00a0e9;
          }
          .form-for-big-box{
            .form-for-min-box{
              display: flex;
            }
            .hardwareClassification-functionPage-dialog-upload{
              .up-box{
                border:1px solid #dedede;
                border-radius:4px;
                padding:0 15px;
                color:#C0C4CC;
                width:280px;
                .up-text-p{
                  text-align: left;
                  width:250px;
                  line-height:40px;
                  display:block;
                  overflow:hidden;
                  text-overflow:ellipsis;
                  white-space:nowrap;
                }
              }
            }
          }
        }
      }
      .for-button-icon{
        font-size:16px;
        text-align: center;
        line-height:20px;
        width:20px;
        height:20px;
        margin:10px 10px 0 0;
        cursor: pointer;
      }
    }
  }
</style>
