<template>
  <div class="context">
    <div class="panel">
      <h5>商家区域管理</h5>
    </div>
    <div class="change">
      <el-button @click="addRegion" type="primary" size="mini">新增区域</el-button>
      <el-button @click="editRegion" size="mini">编辑区域</el-button>
      <!--<el-button @click="deleteRegion" 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)"
          @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 label="序号" type="index" width="50" align="center">
          <template scope="scope">
            <span>{{ (start) + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="区域名称"
            width="240">
        </el-table-column>
        <el-table-column
            prop="create_at"
            label="创建日期"
            :formatter="filterFmtDate"
            width="180"
            sortable
        >
        </el-table-column>

        <el-table-column prop="id" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="deleteRegion(scope.row)">删除</el-button>
<!--            <el-button type="text" @click="goPage(scope.row)">设备管理</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="dialogRegionVisible" 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.name"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" @click="confirmAddRegion">确定</el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditRegion">确定
        </el-button>
        <el-button size="small" @click="dialogRegionVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Global from '../../Global.js'
import {
  AddShopVenue,
  EditShopVenue,
  ShopVenueStatusEdit,
} from "../../api/getApiRes";
import {
  StandardRequest
} from "@/grpc/base_pb";

let qs = require('qs');
export default {
  data() {
    return {
      dialogVisible: false,//其他dialog
      dialogRegionVisible: false,//新增区域dialog
      dialogTitle: '新增区域',
      tableRadio: [],
      start: 0,
      draw: 1,
      // panel 配置项目
      panel: {
        name: '',
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        loading: false,
        time1: globalBt(),
      },
      multipleSelection: [],
      pagination: {
        pageItem: 10,
        pageOptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        name: '',
        shopId: '',
        svId: '',
        btnType: 0,//0新建，1编辑编辑
      },
      tableData: []
    }
  },
  mounted() {
    this.getTableQuery();
  },
  methods: {
    clickChange(item) {
      this.tableRadio = item
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    clearForm() {
      this.form.name = '';
      this.form.svId = '';
      this.form.shopId = '';
    },
    // 关闭所有弹出框
    allDialogClose() {
      this.dialogVisible = false;
    },
    // 新增区域
    addRegion() {
      this.clearForm();
      this.dialogRegionVisible = true;
      this.btnType = 0;
      this.dialogTitle = '新增区域'
    },
    // 确认提交新增区域
    confirmAddRegion() {
      let that = this;
      // checkNum
      if (!that.form.name) {
        this.$message.error('错了哦，区域名称不能为空');
        return false
      }
      if (that.form.name.length > 16) {
        this.$message.error('错了哦，区域名称不能超过16个字符');
        return false
      }

      const jsonStr = {
        shopId: localStorage.shopId,
        venueName: this.form.name
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      that.client.shopVenueAdd(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogRegionVisible = 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);
        }
      });
    },
    // 编辑
    editRegion() {
      let that = this;
      this.clearForm();
      console.log(this.tableRadio);
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = this.tableRadio;
      this.form.name = row.name;
      this.form.shopid = row.shop_id;
      this.form.svId = row.uu_sv_id;
      this.dialogVisible = true;
      this.dialogTitle = '编辑区域';
      this.form.btnType = 1;
      this.dialogRegionVisible = true
    },
    //确认编辑区域
    confirmEditRegion() {
      let that = this;
      // checkNum
      if (!that.form.name) {
        this.$message.error('错了哦，区域名不能为空');
        return false
      }
      if (that.form.name.length > 16) {
        this.$message.error('错了哦，区域名字数超过16个字');
        return false
      }
      const jsonStr = {
        UUSvId: this.form.svId,
        venueName: this.form.name,
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.shopVenueEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            // 关闭弹窗
            that.dialogRegionVisible = 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);
        }
      });
    },
    //删除
    deleteRegion(row) {
      let that = this;


      this.$confirm('此操作将永久删除该区域设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        const jsonStr = {
          shopId: localStorage.shopId,
          UUSvId: row.uu_sv_id,
          status: 9,// 1：启用 8：暂停 9：删除
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.shopVenueStatusEdit(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: '已取消删除'
        });
      });
    },
    //设备管理页面
    goPage(row) {
      this.$router.push({
        path: '/shopDevice', query: {
          name: row.name,
          svId: row.uu_sv_id
        }
      });
    },
    // 查询按钮
    query() {
      this.getTableQuery();
      this.$message.success('查询完毕');
    },
    // 页面数据查询
    getTableQuery() {
      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.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 (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;
      return nonTfmtDate(column, 11);
    },
  },
}
</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;
}

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