<template>
  <div class="context">
    <div class="panel">
      <h5>临时会员</h5>
      <div class="panel-body">
        <el-row :gutter="20">
          <el-col :span="5" style="width: 270px">
            <em>姓名:</em>
            <el-input style="margin-left:10px;width: 180px" v-model="panel.name" placeholder="请输入姓名"></el-input>
          </el-col>
          <el-col :span="5" style="width: 270px">
            <em>手机号:</em>
            <el-input style="margin-left:10px;width: 180px" v-model="panel.phone" placeholder="请输入手机号"
                      type="number"></el-input>
          </el-col>
          <el-col :span="3">
            <el-button size="" type="primary" @click="query" plain :disabled="searchBtnStatus">查询
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="change">
      <el-button @click="addMember" type="primary" size="mini">新增临时会员</el-button>
      <el-button @click="delMember" 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)" @selection-change="handleSelectionChange"
                @current-change="clickChange">
        >
        <el-table-column label="选择" width="55" fixed>
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" width="50" align="center" fixed>
          <template scope="scope">
            <span>{{ (start) + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="user_name" label="会员名" width="90" fixed/>
        <el-table-column prop="usercode" label="手机号" width="110" fixed/>
        <el-table-column prop="headurl" label="头像" width="50">
          <template slot-scope="scope">
            <div class="demo-image__preview" v-if="scope.row.headurl">
              <el-image style="width: 25px; height: 25px" :src="scope.row.headurl"
                        :preview-src-list="[scope.row.headurl]">
              </el-image>
            </div>
            <img src="../../assets/img/nav/head.png" alt="" v-else width="25px" height="25px">
          </template>
        </el-table-column>
        <el-table-column prop="static_hr" label="静态心率" width="110" align="center" sortable/>
        <el-table-column prop="height" label="身高(CM)" width="110" align="center" sortable/>
        <el-table-column prop="weight" label="体重(KG)" width="110" align="center" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.weight }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="类型" align="center" width="80px" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.sex == 1">男</span>
            <span v-if="scope.row.sex == 2">女</span>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="110" :formatter="filterFmtDate" sortable/>
        <el-table-column prop="memo" label="备注">
          <template slot-scope="scope">
            <el-popover placement="top" title="" width="200" trigger="hover" :content="scope.row.memo">
                            <span slot="reference" v-if="scope.row.memo.length > 6">{{ scope.row.memo.substr(0, 6) }}
                                ....</span>
            </el-popover>
            <span v-if="scope.row.memo.length <= 6">{{ scope.row.memo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UserInfo.Status" label="操作" width="160px">
          <template slot-scope="scope">
            <el-button class="btn" type="default" size="mini" @click="editMember(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination background :total="pageination.total" :page-size="pageination.pageItem"
                     @current-change="pageChange"
                     :current-page.sync="cur_page"
      ></el-pagination>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogMemberVisible" :width="form.btnType == 1 ?'650px':'650px'">
      <div class="dialogContent">
        <div :class="['pull-left',{'tabwild':form.btnType == 1}]">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="手机号" :required="true">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="会员名" :required="true">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.memo"></el-input>
            </el-form-item>
            <el-form-item label="身高" :required="true">
              <el-input v-model="form.height" placeholder="cm" type="number"></el-input>
            </el-form-item>
            <el-form-item label="体重" :required="true">
              <el-input v-model="form.weight" placeholder="kg" type="number"></el-input>
            </el-form-item>
            <el-form-item label="静态心率">
              <el-input v-model="form.staticHr" placeholder="请输入" type="number"></el-input>
            </el-form-item>
            <el-form-item label="性别" :required="true">
              <el-select v-model="form.sex " placeholder="">
                <el-option v-for="item in sexOptions" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出生年份" :required="true">
              <el-date-picker v-model="form.birthday" align="right" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="头像">
              <div class="upload">
                <el-upload class="avatar-uploader" :action=domain :http-request=upqiniu
                           :show-file-list="false" :before-upload="beforeUpload">
                  <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                </el-upload>
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <cropper :width="300" :height="300" :fixed-number="[1,1]"
                         @subUploadSucceed="getShopImages"></cropper>
                <!--<ImgCutter v-on:cutDown="cutDown"></ImgCutter>-->
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button :disabled="addDisabled" :loading="addDisabled" type="primary" size="small"
                   v-if="form.btnType == 0" @click="confirmMember">确定
        </el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditMember">确定
        </el-button>
        <el-button size="small" @click="dialogMemberVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import Global from '../../Global.js'
import ImgCutter from 'vue-img-cutter'

import cropper from '@/components/cropper.vue'
import {
  StandardRequest
} from "@/grpc/base_pb";

let qs = require('qs');
export default {
  data() {
    return {
      imageUrl: '',
      token: {}, // 七牛云的上传地址，根据自己所在地区选择，我这里是华南区
      domain: 'https://up-z1.qiniup.com', // 这是七牛云空间的外链默认域名
      qiniuaddr: 'xhead.beswell.com',//xhead.beswell.com 旧的 qjzpcd34v.hb-bkt.clouddn.com
      tableData: [],
      tableRadio: [],
      searchBtnStatus: false,
      addDisabled: false,
      start: 0,
      draw: 1,
      cur_page: 1,
      dialogTitle: '新增临时会员',
      dialogMemberVisible: false,//新增会员dialog
      sexOptions: [
        {value: 1, label: '男'},//性别 1：男， 2：女
        {value: 2, label: '女'},
      ],
      panel: {
        usercode: '',
        username: '',
        compname: '',
        keyword: '',
        USERCODE: '',
        endType: '',
        taskstatus: 99,
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        limit: '10',
        multipleSort: false,
        loading: false,
        fileList: [],
        multipleSelection: [],
        detectedmac: '',
        vipType: '',
        expDay: '',
        vipOptions: vipOptions(0),
        endTypeOptions: endTypeOptions(),
        time1: globalBt(),
      },
      multipleSelection: [],
      pageination: {
        pageItem: 10,
        pageoptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        phone: '',
        name: '',
        userCode: '',
        shopId: '',
        Id: '',
        userId: '',
        height: '',
        weight: '',
        staticHr: '',
        head: '',
        birthday: '',
        sex: 1,
        vipType: 1,
        normalhour: 0,
        newnormalhour: 0,
        gifthour: 0,
        newgifthour: 0,
        btnType: 0,//0新建，1编辑编辑
        memo: '',
        expTime: '',
        classlist: [],
        dialogdata: [],//穿梭待选
        dialogValue: [],//穿梭已选
      },
    }
  },
  mounted() {
    // 读取列表
    this.getTableQuery();
  },
  watch: {
    $route(to) {
      if (to.name == 'memberTemporary') {
        // 读取列表
        this.getTableQuery();
      }
    },
  },
  methods: {
    addMember() {
      this.clearForm();
      this.dialogMemberVisible = true;
      this.btnType = 0;
      this.form.btnType = 0;
      this.dialogTitle = '新增临时会员'
    },
    // 确认提交新增会员
    confirmMember() {
      let that = this;
      // checkNum
      if (!that.form.phone) {
        this.$message.error('错了哦，手机号不能为空');
        return false
      }
      if (!globalCheckPhone(that.form.phone)) {
        this.$message.error('错了哦，手机号格式不正确');
        return false
      }
      if (!that.form.name) {
        this.$message.error('错了哦，会员名不能为空');
        return false
      }
      if (that.form.name.length > 8) {
        this.$message.error('错了哦，会员名字数超过8个字');
        return false
      }
      if (that.form.memo) {
        if (that.form.memo.length > 200) {
          this.$message.error('错了哦，备注字数超过200个字');
          return false
        }
      }
      if (!that.form.height) {
        this.$message.error('错了哦，身高不能为空');
        return false
      }
      if (!that.form.weight) {
        this.$message.error('错了哦，体重不能为空');
        return false
      }
      if (!that.form.birthday) {
        this.$message.error('错了哦，出生年份不能为空');
        return false
      }
      const jsonStr = {
        shopId: localStorage.shopId,
        phone: that.form.phone,
        name: that.form.name,
        sex: that.form.sex,
        birthday: nonTfmtDatetoLength(that.form.birthday, 10),
        height: that.form.height,
        weight: that.form.weight,
        staticHr: that.form.staticHr,
        headIconUrl: that.form.head,
        memo: that.form.memo,
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      that.client.tempVipUserAdd(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          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);
        }
      });
    },
    delMember() {
      let that = this;
      if (this.tableRadio.length == 0) {
        that.$message.error("请先选中一条记录");
        return false
      }
      this.$confirm('此操作将永久删除该临时会员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        const jsonStr = {
          UuTuId: this.tableRadio.uu_tu_id,
          status: 9 //0:禁用  1：启用 9：删除
        };

        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));

        that.client.tempVipUserStatusEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
          if (err == null) {
            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);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    clickChange(item) {
      this.tableRadio = item
    },

    // 编辑
    editMember(row) {
      let that = this;
      this.clearForm();
      this.form.tuId = row.uu_tu_id;
      this.form.name = row.user_name;
      this.form.shopId = row.shop_id;
      this.form.phone = row.usercode;
      this.imageUrl = row.headurl;
      this.form.sex = row.sex;
      this.form.birthday = row.birthday;
      this.form.height = row.height;
      this.form.weight = row.weight;
      this.form.staticHr = row.static_hr;
      this.form.memo = row.memo;
      this.form.btnType = 1;
      this.dialogMemberVisible = true;
      this.dialogTitle = '编辑会员'
    },
    confirmEditMember() {
      let that = this;
      // checkNum
      if (!that.form.phone) {
        this.$message.error('错了哦，手机号不能为空');
        return false
      }
      if (!globalCheckPhone(that.form.phone)) {
        this.$message.error('错了哦，手机号格式不正确');
        return false
      }
      if (!that.form.name) {
        this.$message.error('错了哦，会员名不能为空');
        return false
      }
      if (that.form.name.length > 8) {
        this.$message.error('错了哦，会员名字数超过8个字');
        return false
      }
      if (that.form.memo) {
        if (that.form.memo.length > 200) {
          this.$message.error('错了哦，备注字数超过200个字');
          return false
        }
      }
      if (!that.form.height) {
        this.$message.error('错了哦，身高不能为空');
        return false
      }
      if (!that.form.weight) {
        this.$message.error('错了哦，体重不能为空');
        return false
      }
      if (!that.form.birthday) {
        this.$message.error('错了哦，出生年份不能为空');
        return false
      }
      const jsonStr = {
        token: localStorage.token,
        UuTuId: that.form.tuId,
        name: that.form.name,
        phone: that.form.phone,
        memo: that.form.memo,
        birthday: nonTfmtDatetoLength(that.form.birthday, 10),
        sex: that.form.sex,
        staticHr: that.form.staticHr,
        headIconUrl: that.form.head,
        height: that.form.height,
        weight: that.form.weight
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      that.client.tempVipUserEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          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);
        }
      });
    },
    // 验证文件合法性
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 70;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 70MB!')
      }
      return isJPG && isLt2M
    },
    cutDown(e) {
      this.imageUrl = e.dataURL;
      this.upqiniu(e);
    },
    // 上传文件到七牛云
    upqiniu(req) {
      let that = this;
      const config = {
        headers: {'Content-Type': 'multipart/form-data'}
      };
      let filetype = '';
      if (req.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      // 重命名要上传的文件
      const keyname = 'GoAllOut' + new Date().valueOf() + Math.floor(Math.random() * 100) + '.' + filetype;
      // 从后端获取上传凭证token
      let param = {
        token: localStorage.token,
      };
      let postdata = qs.stringify(param);
      this.axios.post(headapi + 'v1/QiNiu/GetSimpleQiNiuToken', postdata).then(res => {
        const formdata = new FormData();
        formdata.append('file', req.file);
        formdata.append('token', res.data.QiNinToken);
        formdata.append('key', keyname);
        // 获取到凭证之后再将文件上传到七牛云空间
        this.axios.post(this.domain, formdata, config).then(res => {
          this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.key;
          this.form.head = 'http://' + this.qiniuaddr + '/' + keyname;
        })
      })
    },
    // 查询按钮
    query() {
      let that = this;
      that.start = 0;
      that.cur_page = 1;
      that.serachBtnStatus = true;
      that.getTableQuery();
      that.$message.success('查询完毕');
      let totalTime = 2
      let clock = window.setInterval(() => {
        totalTime--
        if (totalTime < 0) {
          totalTime = 2;
          that.serachBtnStatus = false;
        }
      }, 1000)
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;

      const jsonStr = {
        shopId: localStorage.shopId,
        name: that.panel.name,
        phone: that.panel.phone,
        start: that.start,
        tableMax: that.pageination.pageItem
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      that.client.tempVipUserQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.loading = false;
            if (res.rs) {
              that.allTableData = res.rs;
              that.recordsTotal = res.pagecount * that.pageination.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);
        }
      });
    },
    clearForm() {
      // clear
      this.form.name = '';
      this.form.head = '';
      this.imageUrl = '';
      this.form.phone = '';
      this.form.memo = '';
      this.form.normalhour = 0;
      this.form.gifthour = 0;
      this.form.height = '';
      this.form.weight = '';
      this.form.staticHr = '';
      this.form.sex = 1;
      this.form.birthday = '';
      this.form.userCode = '';
      this.form.shopId = '';
      this.form.classlist = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 设置分页数据
    setPagination() {
      // 分页属性
      let that = this;
      that.pageination.total = that.recordsTotal;

      // 默认分页
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pageination.pageItem;
      });
    },
    // 每页显示数量
    handleSizeChange() {
      let that = this;
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pageination.pageItem;
      });
      that.draw = that.pageination.pageItem;
      that.getTableQuery();
    },
    // 翻页
    pageChange(pageIndex) {
      let that = this;
      // 获取当前页
      let index = that.pageination.pageItem * (pageIndex - 1);
      // 数据总数
      let nums = that.pageination.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();
    },
    //过滤时间
    filterFmtDate(value, row, column) {
      return nonTfmtDatetoLength(column, 11);
    },
    // 海报上传成功
    getShopImages(url) {
      this.imageUrl = url;
      this.form.head = url;
    }
  },
  components: {
    cropper
  }
}
</script>

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

.context {
  border-radius: 12px;
  /* height: 770px; */
  overflow-y: scroll;
  display: block;
  margin: 0 auto;
  background-color: #fff !important;
  padding: 30px;
  padding-bottom: 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;
}

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

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

.el-form-item {
  width: 50%;
  float: left;
}
</style>