<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="厂商名称：" prop="storeName">
        <el-input
          v-model.trim="queryParams.storeName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传输方式" prop="transferType">
        <el-select v-model="queryParams.transferType"   placeholder="请选择传输方式">
          <el-option
            v-for="item in transferTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:admin:add']"
        >新增</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:admin:export']"
        >导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="adminList" key="Math.random()" height="calc(100vh - 28vh)">
      <el-table-column label="接口名称" align="center" prop="interfaceName"  show-overflow-tooltip />
      <el-table-column label="接口路径" align="center" prop="interfaceRoute"  show-overflow-tooltip />
      <el-table-column label="接口参数" align="center" prop="interfaceParameter"  show-overflow-tooltip />
      <el-table-column label="接口传输方式" align="center" prop="interfaceTransmissionMode"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span>{{scope.row.interfaceTransmissionMode=="1"?"NB-IOT" : scope.row.interfaceTransmissionMode=="2"?"Lord-IOT" : "2G/4G/5G" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口说明" align="center" prop="interfaceExplain"  show-overflow-tooltip />
      <el-table-column label="接口文档" align="center" prop="interfaceFileRoute"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span style="color:#1890ff" v-if="scope.row.interfaceFileRoute"  @click="FileDownload(`https://smartpark.caih.com/dmapi/archive/${scope.row.interfaceFileRoute}`)">下载</span>
        </template>
      </el-table-column>
      <el-table-column label="厂家（商家）" align="center" prop="business"  show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="addPeople"  show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="addTime"  show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:admin:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改、新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接口名称" prop="interfaceName">
              <el-input v-model.trim="form.interfaceName" placeholder="请填写接口名称" @input="onInput()" maxlength="15" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="接口路径" prop="interfaceRoute">
              <el-input v-model.trim="form.interfaceRoute" placeholder="请填写接口路径" @input="onInput()" maxlength="15" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接口参数" prop="interfaceParameter">
              <el-input v-model.trim="form.interfaceParameter" placeholder="请填写接口参数" @input="onInput()" maxlength="15" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="接口传输方式" prop="interfaceTransmissionMode" >
              <el-select v-model="form.interfaceTransmissionMode"   placeholder="请选择接口传输方式">
                <el-option
                  v-for="item in transferTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属厂家" prop="business">
              <el-input v-model.trim="form.business" placeholder="请填写所属建筑" @input="onInput()" maxlength="15" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="所属单位" prop="companyCode">
              <el-select v-model="form.companyCode"  placeholder="请选择所属单位">
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件上传" prop="interfaceFileRoute">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :limit = 1
                  :on-change="handleChange"
                  :file-list="fileList"
                  >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口说明" prop="interfaceExplain">
              <el-input type="textarea" v-model.trim="form.interfaceExplain" placeholder="请填写接口说明" @input="onInput()" rows="5" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 导出-->
    <a href="" download="" id="xz" style="position: absolute;z-index: -1;opacity: 0;"></a>
  </div>
</template>
<script>
import { addCommunicationApi, delCommunicationApi, updateCommunicationApi, getCommunicationApi, exportCommunicationApi } from "@/api/business/deviceMange";
import { fileUpload } from "@/api/business/uploadfile.js";
import { listChannel } from "@/api/system/product";
import { BASEPATH } from "@/assets/js/common.js";
export default {
  name: "Device",
  data() {
    return {
      fileList:[],
      loading:true,
      exportLoading:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 20,
        storeName: undefined,
        transferType:undefined,
      },
      dateRange:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        interfaceName: [
          { required: true, message: "接口名称不能为空", trigger: "blur" }
        ],
        interfaceRoute: [
          { required: true, message: "接口路径不能为空", trigger: "blur" }
        ],
        interfaceParameter: [
          { required: true, message: "接口参数不能为空", trigger: "blur" }
        ],
        business: [
          { required: true, message: "所属厂家不能为空", trigger: "blur" }
        ],
        interfaceExplain: [
          { required: true, message: "接口说明不能为空", trigger: "blur" }
        ],
        interfaceTransmissionMode: [
          { required: true, message: "接口传输方式不能为空", trigger: ["blur",'change'] }
        ],
        companyCode: [
          { required: true, message: "所属单位不能为空", trigger: ["blur",'change'] }
        ],
        interfaceFileRoute: [
          { required: true, message: "文件不能为空", trigger: ["blur",'change'] }
        ],

      },
      // 整个省市县数据
      // addr1: city,
      // 被选中的市数据
      addr2: [],
      // 被选中的县数据
      addr3: [],
      selectProvince: {},
      selectCity: {},
      selectArea: {},
      transferTypeList:[
        {id:1,name:"NB-IOT",},
        {id:2,name:"Lord-IOT",},
        {id:3,name:"2G/4G/5G",},
      ],
      dwtypeList:[
        {id:1,name:"火系统",},
        {id:2,name:"水系统",},
        {id:3,name:"烟感系统",},
        {id:4,name:"消防栓",},
        {id:5,name:"液位",},
        {id:6,name:"rtu",},
        {id:7,name:"电气火灾",},
        {id:8,name:"防火门",},
        {id:9,name:"气体灭火",},
        {id:10,name:"人脸识别",},
        {id:16,name:"视频监控",},
        {id:128,name:"井盖",},
      ],
      companyList:[],
      num:0,
    };
  },
  created() {
    this.getList();//初始化table
    this.init()
  },
  methods: {
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.fileList = []
      this.open = false;
      this.reset();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        storeName: undefined,
        transferType:undefined,
        current:1,
        size:20
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 查询参数列表 */
    getList() {
      // let data = this.addDateRange(this.queryParams,this.dateRange)
      // if(JSON.stringify(data.params) == "{}"){
      //   delete data.params
      // }else{
      //   data.endTime = data.params.endTime
      //   data.startTime = data.params.beginTime
      // }
      getCommunicationApi(this.queryParams).then(response => {
        this.adminList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改";
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 提交按钮 */
    submitForm(row) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id != undefined) {
            updateCommunicationApi(this.form).then(response => {
              this.loading = false,
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false
            })
          } else {
            addCommunicationApi(this.form).then(response => {
              this.loading = false,
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCommunicationApi(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      let queryParams = {...this.queryParams};
      delete queryParams.current
      delete queryParams.size
      this.exportLoading = true;
      exportCommunicationApi(queryParams).then(response =>{
        this.exportLoading = false;
        document.getElementById("xz").href = BASEPATH() + "archive/" + response.data
        console.log( BASEPATH() + "archive/" + response.data)
        document.getElementById("xz").download = response.data
        document.getElementById("xz").click()
      })
    },
    init(){
      /* 公司列表 */
      listChannel(this.queryParams).then(response => {
        if(response.data.records.length>0){
          this.companyList = response.data.records.map(val =>{
            return {
              id:val.ownerId,
              name:val.ownerName,
              address:val.ownerAddress,
            }
          })
        }
      });
    },
    handleChange(param){
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        const formData = new FormData();
        formData.append('file', param.raw)
        formData.append('multipart', param.raw)
        fileUpload(formData).then(response => {
          this.msgSuccess("上传成功");
          this.form.interfaceFileRoute = response.data
        });
      }
    },
    /** 文件下载 */
    FileDownload(url){
      let link = document.createElement('a')
      fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob)
          link.download = ''
          document.body.appendChild(link)
          link.click()
      })
    }
  }
};
</script>
