<template>
  <div class="context">
    <div class="panel">
      <h5>私有心率设备</h5>
      <div class="likeTab">
        <el-button type @click="goType('hrSensor')" size="mini">场馆心率设备</el-button>
        <el-button type="primary" @click="goType('hrSensorPrivate')" size="mini">私有心率设备</el-button>
      </div>
      <div class="panel-body">
        <div class="panel_control">
          <el-row :gutter="2">
            <el-col :span="5">
              <em style="line-height: 40px; margin-right: 10px">心率设备:</em>
              <el-input v-model="panel.str" placeholder="请输入编号" type="number" style="width: 120px"/>
            </el-col>

            <el-col :span="2">
              <el-button size type="primary" @click="query" plain>查询</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="change">
      <el-button @click="addHrSensor" type="primary" size="mini">新增心率设备</el-button>
      <el-button @click="editHrSensor" 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 prop="sn" label="序列号" align="InVenueNo" width="100px" sortable></el-table-column>
        <el-table-column prop="owner_user_name" label="用户" align="center" sortable>
          <template slot-scope="scope">
            {{ scope.row.owner_user_name == "" ? "暂未绑定" : scope.row.owner_user_name }}
          </template>
        </el-table-column>
        <el-table-column prop="power_percent" label="电量" align="center" width="80px" sortable>
          <template slot-scope="scope">
            <span style="color: red" v-if="parseInt(scope.row.power_percent) <= 20">{{ scope.row.power_percent }}</span>
            <span style="color: gold"
                  v-if="parseInt(scope.row.power_percent) > 20 && parseInt(scope.row.power_percent) < 80">{{
                scope.row.power_percent
              }}</span>
            <span style="color: #67C23A" v-if="parseInt(scope.row.power_percent) >= 80">{{
                scope.row.power_percent
              }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="power_update_at" label="电量更新时间" align="center" width="150" :formatter="filterFmtDate"/>

        <el-table-column prop="id" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="pauseRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <el-pagination background :total="pagination.total" :page-size="pagination.pageItem"
                     @current-change="pageChange" :current-page.sync="cur_page"/>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogSensorVisible" width="550px" align="center">
      <div class="dialogContent">
        <div class>
          <el-form ref="form" :model="form" >
            <el-form-item label="会员账号" :required="true" label-width="120px">
              <!--userId-->
              <el-select v-model="form.uu_user_id" placeholder="请选择" :disabled="form.btnType == 1" filterable style="width: 350px">
                <el-option v-for="item in form.userList" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序列号" :required="true" label-width="110px">
              <el-input v-model="form.sn" style="width: 350px;margin-left: 10px"/>
            </el-form-item>

          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" @click="confirmAddSensor">确定</el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditSensor">确定</el-button>
        <el-button size="small" @click="dialogSensorVisible = 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 {
      activeName: 'comm',
      dialogVisible: false,//其他dialog
      BtnGetAllPower: false,//
      dialogSensorVisible: false,//新增心率设备dialog
      dialogTitle: '新增心率设备',
      tableRadio: [],
      multipleSelection: [],
      draw: 1,
      start: 0,
      recordsTotal: 0,
      cur_page: 1,
      // panel 配置项目
      panel: {
        str: '',
        tableData: [],
        allTableData: [],
        loading: false
      },
      pagination: {
        pageItem: 10,
        pageOptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        sn: '',
        hrId: '',
        venueNo: '',
        shopId: '',
        userList: [],
        btnType: 0,//0新建，1编辑编辑
        memo: '',
      },
      tableData: []
    }
  },
  mounted() {
    this.vipSelect();
    this.getTableQuery();
  },
  methods: {
    handleClick(tab, event) {
      let that = this;
      if (tab.name == "personal") {
        // 私有
        that.$router.push({path: '/hrSensorPrivate'});
      } else {
        // 公共
        that.$router.push({path: '/hrSensor'});
      }
    },
    goType(url) {
      this.$router.push({path: '/' + url});
    },
    clickChange(item) {
      this.tableRadio = item
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    vipSelect() {
      let that = this;

      const jsonStr = {
        shopId: localStorage.shopId,
        classId: -99,//-99代表查询全部
        isAcross: 0 //0：不跨店 1跨店 -99是全部
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      that.client.vipUserSimpleQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply);
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            if (res.rs) {
              that.form.userId = '';
              that.form.userList = turnResToOptionBySimViper(res.rs);
            } else {
              return false;
            }
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
        }
      });
    },
    // 新增心率设备
    addHrSensor() {
      this.clearForm();
      this.dialogSensorVisible = true;
      this.form.btnType = 0;
      this.dialogTitle = '新增心率设备'
    },
    // 确认提交新增心率设备
    confirmAddSensor() {
      let that = this;
      if (!that.form.sn) {
        this.$message.error('错了哦，编号不能为空');
        return false
      }
      if (that.form.sn.length > 20) {
        this.$message.error('错了哦，编号不能超过20个字符');
        return false
      }

      const jsonStr = {
        shopId: localStorage.shopId,
        sn: that.form.sn,
        UUUserID: that.form.uu_user_id,
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.addPvtHrSensors(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogSensorVisible = 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);
        }
      });
    },
    // 编辑
    editHrSensor() {
      let that = this;
      this.clearForm();
      if (this.tableRadio == null || this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      this.form.shopid = row.shop_id;
      this.form.hrId = row.uu_hr_id;
      this.form.sn = row.sn;
      this.form.uu_user_id = row.uu_user_id;
      this.form.venueNo = row.venue_no;
      this.dialogVisible = true;
      this.dialogTitle = '编辑心率设备';
      this.form.btnType = 1;
      this.dialogSensorVisible = true
    },
    //确认编辑心率设备
    confirmEditSensor() {
      let that = this;
      // checkNum
      if (!that.form.sn) {
        this.$message.error('错了哦，编号不能为空');
        return false
      }
      if (that.form.sn.length > 20) {
        this.$message.error('错了哦，编号不能超过20个字符');
        return false
      }
      const jsonStr = {
        shopId: localStorage.shopId,
        sn: that.form.sn,
        UUhrId: that.form.hrId,
        venueNo: that.form.venueNo
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.editHrSensors(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogSensorVisible = 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 = {
          shopId: localStorage.shopId,
          UUhrId: row.uu_hr_id
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.hrSensorsDel(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: '已取消删除'
        });
      });
    },
    // 关闭所有
    allDialogClose() {
      this.dialogVisible = false;
    },
    // 查询按钮
    query() {
      let that = this;
      that.start = 0;
      that.cur_page = 1;
      this.getTableQuery();
      this.$message.success('查询完毕');
    },
    clearForm() {
      // clear
      this.form.name = '';
      this.form.sn = '';
      this.form.venueNo = '';
      this.form.userCode = '';
      this.form.shopId = '';
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;

      const jsonStr = {
        shopId: localStorage.shopId,
        snOrNO: that.panel.str,
        start: that.start,
        tableMax: that.pagination.pageItem
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.hrSensorsPvtQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          that.loading = false;
          if (res.code === 0) {
            if (res.rs) {
              that.allTableData = res.rs;
              that.recordsTotal = res.pagecount * that.pagination.pageItem;
            } 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 (let 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;
      if (column == 0) {
        return '未获得'
      } else {
        return nonTfmtDatetoLength(column, 16);
      }
    },
  },
}
</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;
}

.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;
}

.likeTab {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 0;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

.likeTab button {
  float: left;
  border-radius: 0;
}

.likeTab 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;
}

.dialogContent {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

.dialogContent .pull-left {
  width: 30%;
  float: left;
}

.dialogContent .pull-right {
  width: 70%;
  float: right;
}

.panel_control /deep/ .el-input {
  width: 90px;
  float: left;
}
</style>