<template>
  <div class="context">
    <el-page-header @back="goBack" content="关联手机号"></el-page-header>
    <div class="panel">
      <br>
      <h5> {{ regionName }}</h5>
    </div>
    <div class="change">
      <el-button @click="addPhone" type="primary">新增手机号</el-button>
      <el-button @click="editPhone" type="info">编辑手机号</el-button>
      <el-button @click="enablePhone" type="success">启用手机号</el-button>
      <el-button @click="disablePhone" type="warning">禁用手机号</el-button>
      <el-button @click="deletePhone" type="danger">删除手机号</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="user_name"
            label="用户名"
        >
        </el-table-column>
        <el-table-column
            prop="user_phone"
            label="手机号"
        >
        </el-table-column>

        <el-table-column
            prop="is_main"
            label="类型"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.is_main == 1">主手机号</span>
            <span v-else>关联手机</span>
          </template>
        </el-table-column>

        <el-table-column
            prop="memo"
            label="备注"
        >
        </el-table-column>

        <el-table-column
            prop="status"
            label="状态"
        >
          <!--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>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination
          background
          :total="pageination.total"
          :page-size="pageination.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-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.memo" placeholder="姓名或家庭关系"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" @click="confirmAdd">确定</el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEdit">确定</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: '新增手机号',
      // panel 配置项目
      multipleSelection: [],
      tableRadio: [],
      pageination: {
        pageItem: 10,
        pageoptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        pId: '',
        shopId: '',
        name: '',
        phone: '',
        memo: '',
        btnType: 0
      },
      shops: [],
      tableData: [],
      serachBtnStatus: false,
    }
  },
  mounted() {
    this.regionName = this.$route.query.name;
    this.getTableQuery();
  },
  methods: {
    goBack() {
      this.$router.push({
        path: '/memberFull', query: {}
      });
    },
    clearForm() {
      // clear
      this.form.name = '';
      this.form.phone = '';
      this.form.memo = '';
      this.form.userCode = '';
      this.form.shopId = '';
      this.form.eqSn = '';
      this.form.pId = '';
      this.form.equipType = 1;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    clickChange(item) {
      this.tableRadio = item
    },
    // 新增手机号
    addPhone() {
      this.clearForm();
      this.dialogMemberVisible = true;
      this.form.btnType = 0;
      this.dialogTitle = '新增手机号'
    },
    // 编辑
    editPhone() {
      this.clearForm();
      if (this.tableRadio == null || this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      if (row.is_main === 1) {
        this.$message.error("主手机信息请在会员管理页修改");
        return false
      }
      this.form.shopid = this.$route.query.shopId;
      this.form.userId = this.$route.query.userId;
      this.form.name = row.user_name;
      this.form.phone = row.user_phone;
      this.form.pId = row.p_id;
      this.form.userCode = row.usercode;
      this.form.memo = row.memo;
      this.dialogVisible = true;
      this.dialogTitle = '编辑手机号';
      this.form.btnType = 1;
      this.dialogMemberVisible = true
    },
    // 确认提交新增手机号
    confirmAdd() {
      let that = this;
      if (!that.form.phone) {
        this.$message.error('错了哦，手机号码不能为空');
        return false
      }
      if (!globalCheckPhone(that.form.phone)) {
        this.$message.error('错了哦，手机号格式不正确');
        return false
      }
      if (that.form.memo) {
        if (that.form.memo.length > 200) {
          this.$message.error('错了哦，备注字数超过200个字');
          return false
        }
      }
      const jsonStr = {
        UuUserId: this.$route.query.userId,
        shopId: this.$route.query.shopId,
        otherPhone: that.form.phone,
        memo: that.form.memo
      };
      console.log(jsonStr);
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.vipOtherPhoneAdd(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);
        }
      });
    },
    // 确认提交编辑手机号
    confirmEdit() {
      let that = this;
      if (!that.form.phone) {
        this.$message.error('错了哦，手机号码不能为空');
        return false
      }
      if (!globalCheckPhone(that.form.phone)) {
        this.$message.error('错了哦，手机号格式不正确');
        return false
      }
      if (that.form.memo) {
        if (that.form.memo.length > 200) {
          this.$message.error('错了哦，备注字数超过200个字');
          return false
        }
      }
      const jsonStr = {
        pid: that.form.pId,
        otherPhone: that.form.phone,
        memo: that.form.memo
      };
      console.log(jsonStr);
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.vipOtherPhoneEdit(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);
        }
      });
    },
    // 启用手机号
    enablePhone() {
      let that = this;
      if (this.tableRadio == null || this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      if (row.status === 1) {
        this.$message.error("该账号目前没有被禁用");
        return false
      }
      if (row.is_main === 1) {
        this.$message.error("主手机账号无法操作");
        return false
      }
      this.$confirm('是否开启' + row.user_phone + '？', '启用操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          pid: row.p_id,
          status: 1
        };
        console.log(jsonStr);
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.vipOtherPhoneStatusEdit(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.user_phone + '开启成功！',
                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: '已取消开启'
        });
      });
    },
    // 禁用手机号
    disablePhone() {
      let that = this;
      if (this.tableRadio == null || this.tableRadio.length === 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      if (row.status === 0) {
        this.$message.error("该账号目前没有被启用");
        return false
      }
      if (row.is_main === 1) {
        this.$message.error("主手机账号无法操作");
        return false
      }

      this.$confirm('是否禁用' + row.user_phone + '？', '禁用操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          pid: row.p_id,
          status: 0
        };
        console.log(jsonStr);
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.vipOtherPhoneStatusEdit(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.user_phone + '开启成功！',
                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: '已取消禁用'
        });
      });
    },
    // 删除
    deletePhone() {
      let that = this;
      if (this.tableRadio == null || this.tableRadio.length === 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      if (row.status === 9) {
        this.$message.error("该账号目前已被删除");
        return false
      }
      if (row.is_main === 1) {
        this.$message.error("主手机账号无法删除");
        return false
      }

      this.$confirm('是否删除' + row.user_phone + '？', '禁用操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          pid: row.p_id,
          status: 9
        };
        console.log(jsonStr);
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.vipOtherPhoneStatusEdit(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.user_phone + '删除成功！',
                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: '已取消删除'
        });
      });
    },
    // 查询按钮
    query() {
      // 按钮倒计时
      let that = this;
      that.serachBtnStatus = true;
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.serachBtnStatus = false;
        }
      }, 1000);

      this.getTableQuery();
      this.$message.success('查询完毕');
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;
      const jsonStr = {
        UuUserId: this.$route.query.userId,
        shopId: this.$route.query.shopId
      };
      console.log(jsonStr);
      let paraRequest = new StandardRequest();
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.vipPhoneQuery(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.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();
    },
    // 自动排序
    sortChange(params) {
      console.log(params)
    },
    // 过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      return nonTfmtDate(column, 11);
    },

  },
  watch: {
    $route(to) {
      if (to.name == 'relevancePhone') {
        this.getTableQuery();
      }
    },
  },
}
</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>
