<template>
  <div class="branchesManagePage H100">
    <div class="head_box">
      <h6>系统管理&nbsp;/&nbsp;网点管理</h6>
      <h4>网点管理</h4>
    </div>
    <div class="content_box">
      <div class="form_box h778px">
        <el-form :inline="true" :model="form" class="search-form" onsubmit="return false;">
          <el-form-item label="">
            <el-input  size="mini" placeholder="请输入网点名称"  v-model="form.name" @keyup.enter.native="Search" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini"  type="primary" class="btn_form_search" @click="Search">查询</el-button>
          </el-form-item>
          <el-form-item class="r-float">
            <el-button size="mini" type="primary" v-show="roleId == 1" class="btn_form_add" @click="handleSort()">点击排序</el-button>
            <el-button size="mini" type="primary" class="btn_form_add" icon="el-icon-plus" @click="addBank()">新&nbsp;&nbsp;&nbsp;建</el-button>
            <el-button size="mini" type="primary" class="btn_form_add" @click="exportExcel">下载模板</el-button>
            <el-button size="mini" type="primary" @click="handleImport" class="import btn_form_add">导入数据</el-button>
          </el-form-item>
        </el-form>
        <div class="scrool">
          <el-table style="width:100%;" ref="multipleTable" :data="tableData">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="网点名称" show-overflow-tooltip  prop="name" width="150"></el-table-column>
            <el-table-column label="地址" show-overflow-tooltip prop="address"></el-table-column>
            <el-table-column label="联系电话" show-overflow-tooltip  prop="phoneNum"></el-table-column>
            <el-table-column label="经度" prop="lon"></el-table-column>
            <el-table-column label="纬度" prop="lat"></el-table-column>
            <el-table-column label="状态" prop="status">
              <template slot-scope="scope">
                <div class="statusBox">
                <span class="active"
                      :style="{'backgroundColor':(scope.row.status ? 'rgba(82,196,26,1)' :'rgba(0,0,0,0.25)')}"></span>
                  <span class="openKey">{{scope.row.status ? '启用':'禁用'}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center" width="180">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button title="编辑" :disabled="scope.row.id == '0'" size="mini" type="text" @click="openEdit(scope.row)">编辑&nbsp;|&nbsp;</el-button>
                  <el-button title="删除" :disabled="scope.row.id == '0'" type="text" size="mini" @click="handleDelete(scope.row)">删除&nbsp;|&nbsp;
                  </el-button>
                  <el-button title="二维码" :disabled="scope.row.id == '0'" type="text" size="mini" @click="qrCode(scope.row)">二维码</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination small background
                       @current-change="handleCurrentChange"
                       :current-page="page.currentPage"
                       :page-size="page.pageSize"
                       layout="prev, pager, next"
                       :total="page.total">
        </el-pagination>
      </div>
      <el-dialog class="edit" :title="editorTitle" :visible.sync="dataEditorVisible"
                 :before-close="close1">
        <div class="form_box">
          <el-form ref="editForm" :model="editForm" :rules="formRules">
            <el-form-item label="网点名称:" prop="name" :label-width="formLabelWidth">
              <el-input v-model="editForm.name" size="small" clearable placeholder="请输入网点名称"
                        onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
            <el-form-item label="地址:" prop="address" :label-width="formLabelWidth">
              <el-input size="small" clearable  v-model="editForm.address"  placeholder="请输入地址"></el-input>
            </el-form-item>
            <div class="c">
              <el-form-item style="display: inline-flex;width: 40%; margin: 0px" label="经度:" :label-width="formLabelWidth1" prop="lon">
                <el-input  size="small"  type="number"  v-model.number="editForm.lon"  placeholder="请输入经度"></el-input>
              </el-form-item>
              <el-form-item style="display: inline-flex;width: 40%;margin: 0px" label="纬度:" :label-width="formLabelWidth1" prop="lat" >
                <el-input  size="small"  type="number"  v-model.number="editForm.lat"  placeholder="请输入纬度"></el-input>
              </el-form-item>
            </div>

            <el-form-item label="联系电话:" prop="phoneNum" :label-width="formLabelWidth">
              <el-input size="small" clearable v-model="editForm.phoneNum" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="状  态:" prop="status" :label-width="formLabelWidth">
              <el-radio v-model="editForm.status" label="1">启用</el-radio>
              <el-radio v-model="editForm.status" label="0">禁用</el-radio>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button class="r-float" type="primary" size="mini" @click="save()">确定</el-button>
            <el-button class="r-float" size="mini" @click="close1()">取 消</el-button>
          </div>
        </div>
      </el-dialog>
      <!--二维码弹框-->
      <el-dialog class="qr" title="二维码" :visible.sync="FormVisible" :before-close="close">
        <div class="form_box">
          <el-form :model="qrform" ref="qrform">
            <el-form-item label="网点名称：" prop="name" :label-width="formLabelWidth">
              <span>{{qrform.name}}</span>
            </el-form-item>
            <el-form-item label="网点二维码：" prop="config" :label-width="formLabelWidth">
              <template slot-scope="scope">
                <div id="qrcode">
                  <vue-qr :text="qrform.value" :size="200"></vue-qr>
                  <el-button size="mini" style="margin-left: 30%;" @click="download">下载二维码</el-button>
                </div>
              </template>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" class="r-float" @click="close">关闭</el-button>
          </div>
        </div>
      </el-dialog>
      <!--上传弹窗-->
      <el-dialog title="提示" :visible.sync="importVisible" width="30%">
        <el-upload class="upload-demo" drag :file-list="dataList"  action=""
                   :http-request="handleUploadImg"
                   :limit="1"
                   :on-exceed="handleExceed"
                   :before-remove="beforeRemove"
                   :on-remove="handleRemove"
                   accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text"><em>点击上传,只能上传.xls和.xlsx文件</em></div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="importVisible = false,dataList=[]">取 消</el-button>
          <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!--上传失败提示-->
      <el-dialog
        title="提示"
        :visible.sync="tipVisible"
        width="30%">
        <span style="padding: 10px 20px;display: inline-block;" v-html="tipMessage"></span>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="tipVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="tipVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="sort-dialog dialog-box">
      <el-dialog title="排序" :visible.sync="dialogVisible" width="48%">
        <span class="tips">Tips:拖动可改变业务列表在app端显示顺序！</span>
        <div class="hidden-box">
          <ul class="list">
            <li class="item" v-for="(item, i) in sortList" :key="item.id"
                v-dragging="{item: item, list: sortList, group: 'item' }">
              <span class="title">{{item.name}}</span>
              <span class="index">{{i+1}}</span>
            </li>
          </ul>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitSort">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import VueQr from 'vue-qr'

  export default {
    data() {
      let checkAddress = (rule, value, callback) => {
         let reg=/\s+/;
        if (reg.test(value)) {
          callback(new Error('请输入正确的地址!'));
        }else {
          callback()
        }
      };
      return {
        page: {
          currentPage: 1, //当前页
          pageSize: null, //每页条数
          total: null, //总条数
        },
        formLabelWidth: "100px",
        tableData: [],
        editorTitle: '新增网点',
        dataEditorVisible: false,
        FormVisible: false,
        formLabelWidth1: "130px",
        form: {
          name: '',
        },
        qrform: {
          name: '',
          value: '',
          headImage: '',
        },
        editForm: {
          id: null,
          name: '',
          address: '',
          phoneNum: '',
          lon: '',
          lat: '',
          status: '1',
        },
        formRules: {
          name: [
            {required: true, message: "网点名称不能为空"},
            {max: 20, message: "网点名称不能超过20个字符"},
            {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '请输入正确的网点名称'}
          ],
          phoneNum: [
            {pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的电话号码', trigger: 'blur'}
          ],
          lon: [
            {required: true, message: "经度不能为空"},
          ],
          lat: [
            {required: true, message: "纬度不能为空"},
          ],
          address: [
            {required: true, message: "网点地址不能为空"},
            { validator:checkAddress,trigger: 'blur' }
          ]
        },
        value: '',
        dialogVisible: false,
        importVisible: false,
        tipVisible: false,
        sortList: [],
        roleId: '',
        dataList: [],
        tipMessage:'',
      }
    },
    computed: {},
    mounted() {
      this.onSearch();
      this.roleId = localStorage.getItem('roleId');
    },
    components: {VueQr},
    methods: {
      exportExcel() {
        window.location.href = this.$baseUrl + 'bankBranchInfo/branchTemplateDownload';
      },
      handleUploadImg(file) {
        this.dataList.push(file.file);
      },
      handleExceed() {
        this.$message.warning(`当前限制选择 1 个文件，如需更改请删除后重选`);
      },
      beforeRemove(file, fileList) {
        let vm = this;
        vm.dataList = fileList;
      },
      handleRemove(file) {
        // this.contentForm.icon = '';
      },
      handleImport() {
        this.importVisible = true
        $('.el-dialog__title').html('上传');
      },
      //导入
      handleUpload(file, timeout) {
        let vm = this;
        let formData = new FormData();
        formData.append("excelFile", file);
        return new Promise(function (resolve, reject) {
          vm.$https({
            url: 'bankBranchInfo/branchImport?creator=' + localStorage.getItem('userId'),
            method: 'post'
          }, formData, "file").then((res) => {
            if (res.data.status == 200) {
              vm.$message({
                type: 'success',
                message: res.data.message
              });
            } else if (res.data.status == 405) {
              vm.tipVisible = true;
              $('.el-dialog__title').html('错误提示');
              vm.tipMessage = res.data.message;
            } else {
              vm.$message({
                type: 'error',
                message: res.data.message
              });
            }
            vm.dataList = []
            resolve(res)
          }, (error) => {
            console.log(error)
          })
        })
      },
      //导入提交
      onSubmit() {
        let vm = this
        let uploadList = vm.dataList.concat([]);
        if (uploadList.length == 0) {
          vm.$message({
            message: '请选择文件',
            type: 'warning'
          });
        } else {
          vm.handleUpload(uploadList[0]).then(function (response) {
            vm.importVisible = false;
            vm.dataList = [];
            vm.onSearch();
          })
        }
      },
      // 获得数据接口
      getTableData(param) {
        let vm = this;
        vm.$https({
          url: "bankBranchInfo/getList",
          method: 'get',
          authType: this.backToken
        }, param).then((res) => {
          let data = res.data;
          vm.page.pageSize = data.size;
          vm.page.total = data.total;
          vm.tableData = data.records;
        }).catch(function (err) {
          console.log(err);
        })
      },
      // 分页
      handleCurrentChange(val) {
        let _this = this;
        _this.page.currentPage = val;
        _this.onSearch();
      },
      onSearch() {
        let _this = this;
        let param = _this.getSearchQuery();
        _this.getTableData(param)
      },
      Search() {
        let _this = this;
        _this.page.currentPage = 1;
        let searchObj = {
          "_index": 1,
          "_size": _this.page.pageSize,
          "name": _this.form.name,
        };
        this.getTableData(searchObj);
      },
      // // 获取当前查询参数
      getSearchQuery() {
        let _this = this;
        let searchObj = {
          "_index": _this.page.currentPage,
          "_size": _this.page.pageSize
        };
        for (let key in _this.form) {
          if (_this.form[key]) {
            searchObj[key] = _this.form[key];
          }
        }
        return searchObj;
      },

      addBank() {
        let _this = this;
        $('.el-dialog__title').html('新建');
        for (let key in _this.editForm) {
          _this.editForm[key] = null;
        }
        this.editForm.status = '1';
        _this.dataEditorVisible = true;
      },
      // 编辑弹框
      openEdit(row) {
        $('.el-dialog__title').html('编辑');
        let _this = this;
        let id = row.id;
        _this.$https({
          url: "bankBranchInfo/getById?id=" + id,
          method: 'get',
          authType: this.backToken
        }).then((res) => {
          let data = res.data;
          _this.editForm = data;
          let status = data.status == 0 ? '0' : '1';
          _this.editForm.status = status;
        }).catch(function (err) {
          console.log(err);
        })
        this.dataEditorVisible = true;
      },
      cleanData() {
        let vm = this;
        vm.dataEditorVisible = false;
        for (let key in vm.editForm) {
          vm.editForm[key] = null;
        }
      },
      save() {
        let vm = this;
        if(vm.editForm.lon<0 || vm.editForm.lon>180 || vm.editForm.lat<0 || vm.editForm.lat>90){
          vm.$message({
            type: 'error',
            message: "经度为0 ~ 180之间，纬度为0 ~ 90之间！"
          });
        }else{
          vm.$refs.editForm.validate((valid) => {
            if (valid) {
              if (vm.editForm.id && vm.editForm.id != "") {
                //编辑
                vm.$https({
                  url: 'bankBranchInfo/edit',
                  method: 'put',
                  authType: this.backToken
                }, vm.$qs.stringify(vm.editForm)).then((res) => {
                  if (res.status == 200 || res.status == 201) {
                    vm.$message({
                      type: 'success',
                      message: res.data.message
                    });
                    //重新查询数据
                    vm.onSearch();
                  } else {
                    vm.$message({
                      type: 'error',
                      message: res.data.message
                    });
                  }
                  // //关闭窗口
                  vm.cleanData();
                  this.$refs['editForm'].resetFields();
                }, (error) => {
                  vm.$message({type: 'error', message: error});
                })
              } else {
                //新增
                vm.$https({
                  url: 'bankBranchInfo/add',
                  authType: vm.backToken,
                  method: 'post'
                }, vm.$qs.stringify(vm.editForm)).then((res) => {
                  if (res.status == 200 || res.status == 201) {
                    vm.$message({
                      type: 'success',
                      message: res.data.message
                    });
                    //重新查询数据
                    vm.onSearch();
                  } else {
                    vm.$message({
                      type: 'error',
                      message: res.data.message
                    });
                  }
                  // //关闭窗口
                  vm.cleanData();
                  vm.$refs['editForm'].resetFields();
                }, (error) => {
                })
              }
            }
          });
        }

      },
      close1() {
        this.dataEditorVisible = false;
        for (let key in this.editForm) {
          this.editForm[key] = null;
        }
        this.editForm.status = '1';
        this.$refs['editForm'].resetFields();

      },
      // 删除
      handleDelete(row) {
        let _this = this;
        this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          _this.$https({
            method: 'delete',
            url: 'bankBranchInfo/delete?id=' + row.id,
            authType: this.backToken
          }).then((res) => {
              if (res.status == 200 || res.status == 201) {
                this.$message({type: 'success', message: '删除成功!'});
                _this.Search();
                _this.cleanData();
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            }, (error) => {
              this.$message({
                type: 'error',
                message: "删除失败!" + error.response.data
              });
            }
          )
        })
      },
      qrCode(row) {
        $('.el-dialog__title').html('二维码');
        let _this = this;
        _this.qrform.name = row.name;
        _this.qrform.headImage = row.headImage;
        _this.qrform.value = this.$appHomeUrl + 'bankId=' + row.id;
        _this.FormVisible = true;
      },
      download() {
        var oQrcode = document.querySelector('#qrcode img');
        var url = oQrcode.src;
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        // 下载图名字
        a.download = this.qrform.name;
        a.href = url;
        //合成函数，执行下载
        a.dispatchEvent(event)
      },
      close() {
        this.FormVisible = false;
      },
      handleSort() {
        this.dialogVisible = true;
        $('.el-dialog__title').html('排序');
        this.getSortList();
      },
      getSortList() {
        let _this = this;
        _this.$https({
          method: 'get',
          url: 'bankBranchInfo/getListOnApp',
        }).then((res) => {
            _this.sortList = res.data;
          }, (error) => {
          }
        )
      },
      submitSort() {
        let _this = this;
        let oldList = [];
        _this.sortList.forEach((e) => {
          let obj = {
            id: e.id
          };
          oldList.push(obj)
        });
        _this.$https({
          method: 'put',
          url: 'bankBranchInfo/sort',
          authType: this.backToken
        }, oldList).then((res) => {
            _this.$message({
              type: 'success',
              message: res.data.message
            });
            _this.dialogVisible = false;
          }, (error) => {
          }
        )
      }
    }
  }
</script>

<style lang="less">
  @import '../../style/common';

  .branchesManagePage {
    .content_box {
      .input_box {
        width: 100%;
        min-width: 815px;
        margin-bottom: 30px;
        .el-input, .el-select {
          max-width: 272px;
          height: 32px;
          background: rgba(255, 255, 255, 1);
          border-radius: 4px;
          .el-input__inner {
            height: 32px;
          }
        }
      }
      .btn_form_search, .btn_form_add {
        height: 29.6px;
        text-align: center;
        /*padding: 7 15px;*/
      }
      .scrool {
        width: 100%;
        height: calc(100% - 100px);
        overflow-x: hidden;
        overflow-y: scroll;
        .el-table {
          .el-table__header-wrapper {
            .el-table__header {
              .has-gutter tr th {
                background: rgba(250, 250, 250, 1);
              }

            }
          }
          .el-table__body-wrapper {
            width: 100%;
            table tbody tr td {
              padding: 6px 0px;
              .cell {
                max-height: 94px !important;
                overflow: hidden !important;
              }
            }
          }
        }
      }

      /*!*弹窗*!*/
      .el-dialog {
        width: 600px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        .el-dialog__header {
          padding: 15px;
          border-bottom: 1px solid rgba(0, 0, 0, 0.09);
        }
        .el-dialog__body {
          padding: 0px !important;
          border: 1px solid transparent;
          .form_box {
            padding-bottom: 40px;
            .el-form {
              margin-bottom: 20px;
              .el-form-item {
                margin: 10px 50px 20px;
                .el-form-item__content {
                  width: 280px;
                }
              }
              .el-input {
                width: 100%;
              }
              .c{
                margin: 10px 92px 20px;
                height: 48px;
                line-height: 0px;
                .el-form-item__content{
                  margin-left: 10px!important;
                  .el-input__inner {
                     padding-right: 0px!important;
                  }
                }
              }
            }
            .dialog-footer {
              border-top: 1px solid rgba(0, 0, 0, 0.09);
              padding-top: 8px;
              .el-button {
                margin-right: 10px;
                padding: 8px 16px;
              }
            }
          }
        }
      }

      .upload-demo{
        padding: 10px 20px;
      }
      .el-upload-dragger{
        max-width: 330px!important;
      }
    }
  }


</style>
