<template>
  <div class="context">
    <div class="panel">
      <h5> 商家设备管理 </h5>
      <div class="panel-body">
        <el-row :gutter="20">
          <el-col :span="5" style=" width: 260px">
            <em>设备编号:</em>
            <el-input style="margin-left:10px; width: 140px" v-model="panel.eqSn" placeholder="请输入设备编号"/>
          </el-col>
          <el-col :span="5" style="width: 260px">
            <em>所属区域:</em>
            <el-select style="margin-left:10px; width: 150px" v-model="panel.region">
              <el-option v-for="item in regionList" :key="item.value" :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5" style="width: 260px">
            <em>设备类型:</em>
            <el-select style="margin-left:10px; width: 150px" v-model="panel.equipType">
              <el-option v-for="item in equipSearchOptions" :key="item.value" :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2">
            <el-button size="" type="primary" @click="query" plain :disabled="searchBtnStatus">查询</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="change">
      <el-button @click="addRegionEquip" type="primary" size="mini">新增区域设备</el-button>
      <el-button @click="editRegionEquip" size="mini">编辑区域设备</el-button>
    </div>
    <div class="table">
      <el-table
          :data="tableData"
          border
          is-horizontal-resize
          :default-sort="{prop: 'date', order: 'descending'}"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          class=""
          @selection-change="handleSelectionChange" @current-change="clickChange"
      >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
          </template>
        </el-table-column>
        <el-table-column
            type="index"
            label="序号"
            align="center"
            width="50">
        </el-table-column>

        <el-table-column
            prop="eq_name"
            label="设备名"
        />
        <el-table-column
            prop="eqsn"
            label="序列号"
        />
        <el-table-column
            prop="version"
            label="版本"
            sortable
        />
        <el-table-column
            prop="equip_type"
            label="类型"
            sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.equip_type == 1">TVBox</span>
            <span v-if="scope.row.equip_type == 2">BLEHub</span>
            <span v-if="scope.row.equip_type == 3">演示设备</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            sortable
        >
          <!--1：启用  8：暂停  9：删除-->
          <template slot-scope="scope">
            <span v-if="scope.row.status == 1" style="color: yellowgreen">启用</span>
            <span v-if="scope.row.status == 0" style="color: red">暂停</span>
            <span v-if="scope.row.status == 9" style="color: purple">删除</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="address"
            label="操作">
          <template slot-scope="scope">
            <el-button type="success" @click="run(scope.row)" v-if="scope.row.status == 0" size="mini">开启</el-button>
            <el-button type="warning" @click="pause(scope.row)" v-if="scope.row.status == 1" size="mini">暂停</el-button>
            <el-button type="danger" @click="pauseRowDel(scope.row)" size="mini" v-if="scope.row.equip_type !== 3">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination
          background
          :total="pagination.total"
          :page-size="pagination.pageItem"
          @current-change="pageChange"
      ></el-pagination>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogMemberVisible" width="650px">
      <div class="dialogContent">
        <div class="">
          <el-form ref="form" :model="form" label-width="160px">
            <el-form-item label="选择区域">
              <el-select v-model="form.uuSvId">
                <el-option v-for="item in regionList" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备序列号">
              <el-input v-model="form.eqSn "></el-input>
            </el-form-item>
            <el-form-item label="版本号">
              <el-input v-model="form.version"></el-input>
            </el-form-item>
            <el-form-item label="设备类型">
              <el-select v-model="form.equipType" placeholder="请选择">
                <el-option
                    v-for="item in equipOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" @click="confirmAddEquip">确定</el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditEquip">确定</el-button>
        <el-button size="small" @click="dialogMemberVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Global from '../../Global.js'
import {
  StandardRequest
} from "@/grpc/base_pb";

let qs = require('qs');
export default {
  data() {
    return {
      regionName: '',
      dialogVisible: false,
      dialogMemberVisible: false,
      dialogTitle: '新增区域设备',
      multipleSelection: [],
      tableRadio: [],
      pagination: {
        pageItem: 10,
        pageOptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      // panel 配置项目
      regionList: [],
      panel: {
        equipType: -99
      },
      equipSearchOptions: [
        {value: -99, label: '全部'},
        {value: 1, label: 'TVBox'},
        {value: 2, label: 'BLEHub'},
        {value: 3, label: '演示设备'},
      ],
      form: {
        eqId: '',
        eqSn: '',
        name: '',
        version: '',
        userCode: '',
        shopId: '',
        btnType: 0,
        equipType: 1,
      },
      equipOptions: [
        {value: 1, label: 'TVBox'},
        {value: 2, label: 'BLEHub'},
        {value: 3, label: '演示设备'},
      ],
      shops: [],
      tableData: [],
      searchBtnStatus: false
    }
  },
  mounted() {
    this.regionName = this.$route.query.name;
    this.panelSelect();
    this.getTableQuery();
  },
  methods: {
    goBack() {
      this.$router.push({
        path: '/hrSensor', query: {}
      });
    },
    clickChange(item) {
      this.tableRadio = item
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    clearForm() {
      // clear
      this.form.name = '';
      this.form.userCode = '';
      this.form.shopId = '';
      this.form.eqSn = '';
      this.form.version = '';
      this.form.equipType = 1;
    },
    // 新增区域设备
    addRegionEquip() {
      this.clearForm();
      this.dialogMemberVisible = true;
      this.btnType = 0;
      this.uuSvId = '';
      this.dialogTitle = '新增区域设备'
    },
    // 确认提交新增区域设备
    confirmAddEquip() {
      let that = this;
      // checkNum
      if (!that.form.eqSn) {
        this.$message.error('错了哦，设备序列号不能为空');
        return false
      }
      if (that.form.version.length > 10) {
        this.$message.error('错了哦，版本号字符不能超过10位');
        return false
      }

      const jsonStr = {
        shopId: localStorage.shopId,
        eqsn: this.form.eqSn,
        eqType: this.form.equipType,
        version: this.form.version,
        UuSvId: this.form.region,
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.shopVenueEquipAdd(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogMemberVisible = false;
            // 重载列表
            that.getTableQuery();
            that.$message({
              showClose: true,
              message: '所属设备添加成功！',
              type: 'success'
            });
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    //修改设备
    editRegionEquip() {
      let that = this;
      this.clearForm();
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      this.form.uuSvId = row.uu_sv_id;
      this.form.eqSn = row.eqsn.trim();
      this.form.version = row.version.trim();
      this.form.equipType = row.equip_type;
      this.dialogVisible = true;
      this.dialogTitle = '编辑区域设备';
      this.form.btnType = 1;
      this.dialogMemberVisible = true
    },
    //确认提交修改
    confirmEditEquip() {
      let that = this;
      console.log(that.form.version.length);
      // checkNum
      if (!that.form.eqSn) {
        this.$message.error('错了哦，设备序列号不能为空');
        return false
      }
      if (that.form.version.length > 10) {
        this.$message.error('错了哦，版本号字符不能超过10位');
        return false
      }
      let param = {
        key: localStorage.ServiceKey,

      };
      const jsonStr = {
        eqSn: this.form.eqSn,
        shopId: localStorage.shopId,
        eqType: this.form.equipType,
        version: this.form.version,
        UuSvId: this.form.uuSvId
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.shopVenueEquipAdd(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogMemberVisible = false;
            // 重载列表
            that.getTableQuery();
            that.$message({
              showClose: true,
              message: '区域设备信息编辑成功！',
              type: 'success'
            });
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    //删除
    pauseRowDel(row) {
      let that = this;

      this.$confirm('此操作将永久删除该区域设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          UuEqId: row.uu_eq_id,
          status: 1//1启用 0禁用 9删除
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.shopVenueEquipStatusEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
          if (err == null) {
            console.log(StandardReply.getJsonrst());
            let res = JSON.parse(StandardReply);
            if (res.code === 0) {
              that.$message({
                showClose: true,
                message: '选中的区域设备已删除！',
                type: 'success'
              });
              // 重载列表
              that.getTableQuery();
            } else {
              that.$message.error(res.memo + ',错误代码：' + res.code);
            }
          } else {
            let res = err;
            that.$message.error(res.message + ',错误代码：' + res.code);
            console.log(res);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 暂停
    pause(row) {
      let that = this;
      console.log(row);
      this.$confirm('是否暂停设备' + row.eqsn + '？', '暂停操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          UuEqId: row.uu_eq_id,
          status: 0 //1启用 0禁用 9删除
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.shopVenueEquipStatusEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
          if (err == null) {
            console.log(StandardReply.getJsonrst());
            let res = JSON.parse(StandardReply);
            if (res.code === 0) {
              that.$message({
                showClose: true,
                message: row.eqsn + '暂停成功！',
                type: 'success'
              });
              // table 重载
              that.getTableQuery();
            } else {
              that.$message.error(res.memo + ',错误代码：' + res.code);
            }
          } else {
            let res = err;
            that.$message.error(res.message + ',错误代码：' + res.code);
            console.log(res);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消暂停'
        });
      });
    },
    // 开启
    run(row) {
      let that = this;
      this.$confirm('是否开启设备' + row.eqsn + '？', '开启操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          UuEqId: row.uu_eq_id,
          status: 1//1启用 0禁用 9删除
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.shopVenueEquipStatusEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
          if (err == null) {
            console.log(StandardReply.getJsonrst());
            let res = JSON.parse(StandardReply);
            if (res.code === 0) {
              that.$message({
                showClose: true,
                message: row.eqsn + '开启成功！',
                type: 'success'
              });
              // table 重载
              that.getTableQuery();
            } else {
              that.$message.error(res.memo + ',错误代码：' + res.code);
            }
          } else {
            let res = err;
            that.$message.error(res.message + ',错误代码：' + res.code);
            console.log(res);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消开启'
        });
      });
    },
    panelSelect() {
      let that = this;
      that.loading = true;
      const jsonStr = {
        shopId: localStorage.shopId
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.shopVenueQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.loading = false;
            if (res.rs) {
              that.regionList = turnResToOptionByShopRegion(res.rs);
            } else {
              that.regionList = [];
            }
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 查询按钮
    query() {
      let that = this;
      that.start = 0;
      that.cur_page = 1;
      that.searchBtnStatus = true;
      that.getTableQuery();
      this.pageshow = false;//让分页隐藏
      this.$nextTick(() => {//重新渲染分页
        this.pageshow = true;
      });
      that.$message.success('查询完毕');
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.searchBtnStatus = false;
        }
      }, 1000)
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;

      const jsonStr = {
        shopId: localStorage.shopId,
        eqsn: that.panel.eqSn,
        eqType: that.panel.equipType//1：TVBox  2：蓝牙心率Hub 3：演示Pad  -99全部
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.shopVenueEquipQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.loading = false;
            if (res.rs) {
              that.allTableData = res.rs;
              that.recordsTotal = res.rs.length;
            } else {
              that.allTableData = [];
              that.recordsTotal = 0;
            }
            // 设置分页数据
            that.setPagination();
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 设置分页数据
    setPagination() {
      // 分页属性
      let that = this;
      that.pagination.total = that.recordsTotal;
      // 默认分页
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
    },
    // 每页显示数量
    handleSizeChange() {
      let that = this;
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
      that.draw = that.pagination.pageItem;
      that.getTableQuery();
    },
    // 翻页
    pageChange(pageIndex) {
      let that = this;
      // 获取当前页
      let index = that.pagination.pageItem * (pageIndex - 1);
      // 数据总数
      let nums = that.pagination.pageItem * pageIndex;
      // 容器
      let tables = [];
      for (var i = index; i < nums; i++) {
        if (that.allTableData[i]) {
          tables.push(that.allTableData[i])
        }
        this.tableData = tables;
      }
      that.start = index * that.draw;
      // that.getTableQuery();
    },
    // 自动排序
    sortChange(params) {
      console.log(params)
    },
    // 过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      return nonTfmtDate(column, 11);
    },
  },
  watch: {
    $route(to) {
      if (to.name == 'shopDevice') {
        this.regionName = this.$route.query.name;
        this.getTableQuery();
        console.log(this.regionName);
      }
    },
  },
}
</script>

<style scoped>
@import "../../assets/css/panel.css";

.context {
  /* height: 770px; */
  overflow-y: scroll;

  display: block;
  margin: 0 auto;
  background-color: #fff !important;
  padding: 30px;
  padding-bottom: 60px;
}

.panel-body {
  padding: 20px;
  background: #F0F2F5;
}

.change {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px;
}

.change button {
  float: left;
}

.change button.pull-right {
  float: right;
}

.dialogTitle {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  color: #000000;
  font-size: 18px;
  text-align: center;
}

.dialogTitle em {
  float: none;
  font-style: normal;
  color: #3799FF;
  margin: 0;
}

/deep/ .el-transfer-panel__item .el-checkbox__input {
  left: 40px;
}

.dialogFooter {
  width: 90%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-top: 10px;
}

.dialogFooter button {
  float: right;
  margin-left: 10px;
}

/deep/ .el-date-editor .el-range__icon {
  line-height: 22px;
}

.panel /deep/ .el-date-editor .el-range-separator {
  line-height: 22px;
}

/deep/ .el-select {
  width: 100%;
}

.panel h5 {
  font-size: 24px;
}

/*ipad only*/
@media only screen and (max-width: 1366px) {
  .panel /deep/ .el-date-editor--daterange {
    width: 100%;
  }
}

</style>
