<template>
  <section class="main">
    <div class="p_all_20">
      <el-card class="kefu_item" v-for="(item,index) in tableData.list" :key="index">
        <div class="top_info">
            <el-row class="info-box">
              <el-col :span="8">
                <div class="head_box">
                  <img :src="item.icoPath" alt="">
                </div>
              </el-col>
              <!--这是客服头像显示地点 -->
              <el-col :span="16" class="right_text">
                <p>客服工号：{{item.code}}</p>
                <p>客服姓名：{{item.name}}</p>
              </el-col>
            </el-row>
          <!-- <el-divider class="dividerImg"></el-divider> -->
        </div>
            
        <el-row>

          <el-col :span="8">

            <div class="erweima_box">
              <img :src="item.wexinQRcodePath" alt="">
              <!--这是微信二维码显示地点 -->
            </div>

          </el-col>

          <el-col :span="16">
            <div class="middle_info">
              <p>
                <span>手机号码：</span>
                {{item.phone}}
              </p>
              <p>
                <span>固话：</span>
                {{item.tel}}
              </p>
              <p>
                <span>微信号：</span>
                {{item.weixin}}
              </p>
              <p>
                <span>QQ号码：</span>
                {{item.icq}}
              </p>
              <p>
                <span>邮箱：</span>
                {{item.email}}
              </p>
            </div>

          </el-col>

          <el-col :span="24">
            <el-col :span="8">
            <div><br></div>
            </el-col>
            <el-col :span="16">
              <div class="bottom_info">
              <el-button icon="el-icon-delete" @click="handleDelete(index,item.serverId)">删除</el-button>
              <el-button type="primary" icon="el-icon-edit" @click="handleEdit(index,item)">编辑</el-button>
            </div>
           </el-col>
            </el-col>
        </el-row>

      </el-card>
      <!-- 新增 -->
      <el-card class="kefu_item">
        <a href="javascript:;" @click="handleAdd">
          <img class="add_kefu" src="../../../assets/img/add_kefu.png" alt>
        </a>
      </el-card>
    </div>

    <div class="pagination">
      <pagination 
      @eventSizeChange="eventSizeChange" 
      @eventCurrentChange="eventCurrentChange" 
      :total="total" 
      :pageSize="listParam.pageSize"></pagination>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="centerDialogVisible" width="600px" center class="form">
      <div>
        <el-form :model="form" ref="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="客服工号" class="must" prop="code">
            <el-input v-model="form.code" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="客服姓名" class="must" prop="name">
            <el-input v-model="form.name" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" class="must" prop="phone">
            <el-input v-model="form.phone" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="固话" prop="tel">
            <el-input v-model="form.tel" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="微信" prop="weixin">
            <el-input v-model="form.weixin" clearable autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="QQ号码" prop="icq">
            <el-input v-model="form.icq" clearable autocomplete="off"></el-input>
          </el-form-item>
          <div class="uploader-box">
            <el-form-item label="客服头像上传" class="upload">
              <el-upload
                class="avatar-uploader"
                :action="KefuUploadData.host|| '' "
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :data="KefuUploadData"
                :show-file-list="false"
              >
                <img
                  v-if="form.icoPath"
                  :src="form.icoPath"
                  class="avatar"
                >
                <!-- 这是编辑和新增弹窗的客服头像 -->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="微信二维码上传" class="upload" label-width="150px">
              <el-upload
                class="avatar-uploader"
                :action="weixinUploadData.host|| '' "
                :on-success="handleWeChatQRSuccess"
                :before-upload="beforeWeChatQRUpload"
                :data="weixinUploadData"
                :show-file-list="false"
              >
                <img
                  v-if="form.wexinQRcodePath"
                  :src="form.wexinQRcodePath"
                  class="avatar"
                >
                <!-- 这是编辑和新增弹窗的微信二维码 -->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <!-- <el-button type="primary" @click="handleOnSubmit('form')">保 存</el-button> -->
        <el-button type="primary" @click="addSeiver('ruleForm')">保 存</el-button>


      </span>
    </el-dialog>
  </section>
</template>

<script>
import { _getOssToken, _uuid } from "@/utils/utils";
import pagination from "@/components/common/pagination";

export default {
  name: "service",
  data() {
    var phone = /^\d{11}$/;
    var tel = /^[0-9]*$/;
    var icq = /^[0-9]*$/;
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号码不能为空"));
      } else if (!phone.test(value)) {
        return callback(new Error("手机号码必须为11位纯数字"));
      } else {
        return callback();
      }
    };
    var checkTel = (rule, value, callback) => {
      if (!tel.test(value)) {
        return callback(new Error("固话号码最多为30位纯数字"));
      } else {
        return callback();
      }
    };
    var checkICQ = (rule, value, callback) => {
      if (!icq.test(value)) {
        return callback(new Error("QQ号码最多为30位纯数字"));
      } else {
        return callback();
      }
    };

    return {
      dialogTitle:'编辑客服',
      centerDialogVisible: false,
      total:0,
      listParam:{
        page:1,
        pageSize:10
      },
      imageUrl: "",
      tableData: [],
      form: {
        code:'',
        name:'',
        phone:'',
        tel:'',
        email:'',
        weixin:'',
        icq:'',
        icoPath:'',
        wxpath:'',
        wexinQRcodeType:'',
        status:''
      },
      confirm: 0,
      KefuUploadData: {},
      weixinUploadData: {},
      rules: {
        code: [
          { required: true, message: "客服工号不能为空", trigger: "blur" },
          {
            max: 30,
            message: "客服工号不能超过30位",
            trigger: ["blur", "change"]
          }
        ],
        name: [
          { required: true, message: "客服姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: ["blur", "change"] }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur"]
          }
        ],
        tel: [
          {
            validator:checkTel,
            max: 30,
            message: "固话号码不能超过30位而且必须是纯数字",
            trigger: ["blur", "change"]
          }
        ],
        icq:[
          {
            max:30,
            message: "QQ号码不能超过30位而且必须是纯数字",
            validator:checkICQ,
          }
        ]
      }
    };
  },
  components: {
    pagination
  },
  mounted() {
    this.init();
  },

  methods: {
    init() {
      // let token = JSON.parse(localStorage.getItem("info")).token? JSON.parse(localStorage.getItem("info")).token: "";
      this.$axios
        .get("/service/list",{
          params:this.listParam
        })
        .then(res => {
          // 接收图片地址
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.total=Number(res.data.data.total)
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    eventSizeChange(val) {
      this.listParam.pageSize = val;
      this.init();
    },
    eventCurrentChange(val) {
      this.listParam.page = val;
      this.init();
    },
    handleEdit(index,item) {
      this.dialogTitle='编辑客服';
      this.centerDialogVisible = true;
      this.confirm = 0;
      this.form = JSON.parse(JSON.stringify(item));
      // this.form.weixinUploadData = "";
      // this.form.KefuUploadData = "";
      console.log(index,item);
    },
    handleCancel() {
      this.centerDialogVisible = false;
    },
    handleDelete(index, serverId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.$axios
            .delete("/service/" + serverId)
            .then(res => {
              if (res.data.code == 200) {
                this.init();
                // this.tableData.splice(index, 1);
              }
            })
            .catch(err => {
              console.log(err);
            });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //新增客服
    handleAdd() {
      this.dialogTitle='新增客服';
      this.centerDialogVisible = true;
      this.confirm = 1;
      this.form ={
        code:'',
        name:'',
        phone:'',
        tel:'',
        email:'',
        weixin:'',
        icq:'',
        icoPath:'',
        wxpath:'',
        wexinQRcodeType:'',
        status:''
      };
      this.$nextTick(function(){
        this.$refs['ruleForm'].clearValidate();
      })
    },
    reset(formName){
        this.$refs[formName].resetFields();
      },
      addSeiver(formName){
        var params = this.form;
        if(params.code =='' || params.name=="" || params.phone==""){
            this.$message.error('请完善必填信息')
            return false
          }
         if(this.confirm == 0){

           this.$axios
              .post("/service/modify", params)
              .then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!"
                  });
                  this.init();
                  this.centerDialogVisible = false;
                }else{
                  this.$message.error(res.data.message);
                }
              })
              .catch(err => {

              });
         }else if(this.confirm == 1){
              this.$axios.post('/service/add',
                params
              ).then((res) => {
                if(res.data.code==200){
                  this.centerDialogVisible = false;
                  this.init();
                }else{
                  this.$message.error(res.data.message);
                }

            }).catch(()=>{})
         }

      },
    handleOnSubmit(formName) {
      if (this.confirm == 0) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.centerDialogVisible = false;
            //下面做一个判断，是否给后天的地址加上'/'
            if (this.form.icoPath.charAt(0) === "/") {
              this.form.icoPath;
            } else {
              this.form.icoPath = "/" + this.form.icoPath; //在这里给传给后台的客服头像图片加上一个"/"
            }

            if (this.form.wexinQRcodePath.charAt(0) === "/") {
              this.form.wexinQRcodePath;
            } else {
              this.form.wexinQRcodePath = "/" + this.form.wexinQRcodePath; //在这里给传给后台的客服头像图片加上一个"/"
            }
            this.$axios
              .post(this.HOST + "/sys/service/modify", this.form)
              .then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!"
                  });
                  this.init();
                }
              })
              .catch(err => {
                console.log(err);
              });
          } else {
            this.$message({
              type: "info",
              message: "修改失败,请检查输入信息!"
            });
            return false;
          }
        });
      } else if (this.confirm == 1) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.centerDialogVisible = false;
            this.form.icoPath = "/" + this.form.icoPath; //在这里给传给后台的客服头像图片加上一个  /
            this.form.wexinQRcodePath = "/" + this.form.wexinQRcodePath; //在这里给传给后台的微信QR码图片加上一个  /
            this.centerDialogVisible = false;
         //下面做一个判断，是否给后天的地址加上'/'
            if (this.form.icoPath.charAt(0) === "/") {
              this.form.icoPath;
            } else {
              this.form.icoPath = "/" + this.form.icoPath; //在这里给传给后台的客服头像图片加上一个"/"
            }

            if (this.form.wexinQRcodePath.charAt(0) === "/") {
              this.form.wexinQRcodePath;
            } else {
              this.form.wexinQRcodePath = "/" + this.form.wexinQRcodePath; //在这里给传给后台的客服头像图片加上一个"/"
            }

            this.$axios
              .post(this.HOST + "sys/service/add", this.form)
              .then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: "添加客服成功!"
                  });
                  this.init();
                }
              })
              .catch(err => {
                console.log(err);
              });
            alert("submit!");
          } else {
            this.$message({
              type: "info",
              message: "添加客服失败，请检查输入信息!"
            });
            return false;
          }
        });
      }
    },

    handleAvatarSuccess(res, file) {
      // this.$set(this.form, "icoPath", this.KefuUploadData.key);
      // this.$forceUpdate(); // 强制重新渲染页面
      var imgInfo=this.KefuUploadData.host + "/" + this.KefuUploadData.key;
      this.form.icoPath=imgInfo;
      this.KefuUploadData = {};
    },
    beforeAvatarUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$message.error("请上传图片格式文件");
        return false;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片大小不能超过2M");
        return false;
      }
      return new Promise((resolve, reject) => {
        _getOssToken
          .call(this, null)
          .then(res => {
            let fileExt = /\.[^\.]+$/.exec(file.name);
            this.KefuUploadData = res;
            this.KefuUploadData.key =
              "ROOT/SJHT/AppShow/" + _uuid() + fileExt;
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    handleWeChatQRSuccess(res, file) {
      // this.$set(this.form, "wexinQRcodePath", this.weixinUploadData.key);
      // this.$forceUpdate(); // 强制重新渲染页面
      var imgInfo=this.weixinUploadData.host + "/" + this.weixinUploadData.key;
      this.form.wexinQRcodePath=imgInfo;
      this.weixinUploadData = {};
    },
    beforeWeChatQRUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$message.error("请上传图片格式文件");
        return false;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片大小不能超过2M");
        return false;
      }
      return new Promise((resolve, reject) => {
        _getOssToken
          .call(this, null)
          .then(res => {
            let fileExt = /\.[^\.]+$/.exec(file.name);
            this.weixinUploadData = res;
            this.weixinUploadData.key =
              "ROOT/SJHT/AppShow/" + _uuid() + fileExt;
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
</script>

<style scoped>
img{
  max-width: 100%;
  max-height: 100%;
}
.kefu_item {
  display: inline-block;
  width: 429px;
  height: 236px;
  background-color: #fff;
  /* float: left; */
  padding: 15px;
  position: relative;
  margin-bottom: 16px;
  overflow: hidden;
  border: 1px solid #dcdcdc;
  margin: 10px;
  font-size: 14px;
}
@media screen and (max-width: 1366px) {
  .kefu_item {
    width: 340px;
  }
}
@media screen and (max-width: 400px) {
  .kefu_item {
    width: 96%;
    padding: 1%;
    margin: 1%;
  }
}
>>> .el-card__body{
  padding:0;
}
.form >>> div {
  /* max-width: 490px; */
}
.top_info {
  display: block;
  padding-bottom: 20px;
  /* text-align: center; */
}
.info-box{
  display: flex;
  align-items: center;
}
.head_box{
    width: 90px;
    height:60px;
    margin: 0 auto;
    text-align: center;
  }
.dividerImg{
    margin: 20px 0;
}
.top_info img {
  display: inline-block;
  vertical-align: middle;
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.top_info .right_text {
  display: inline-block;
  vertical-align: middle;
  /* padding-left: 10px; */
}
.kefu_item p {
  padding-bottom: 5px;
}
.erweima_box {
  width: 90px;
  height:90px;
  margin: 0 auto;
  text-align: center;
}
.middle_info {
  display: block;
  overflow: hidden;
}
.bottom_info {
  margin-top: 20px;
  /* text-align: right; */
}
.add_kefu {
  display: block;
  height: 100px;
  width: 100px;
  margin: 77px auto;
}
.add_kefu img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
}
/* 头像上传 */
.uploader-box {
  overflow: hidden;
}
.uploader-box .avatar-uploader{
      border: 1px dashed #ddd;
}
.uploader-box .upload {
  float: left;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
>>> .el-upload--text {
  width: 90px;
  height: 90px;
}
>>> .avatar-uploader-icon {
  width: 90px;
  height: 90px;
  line-height: 90px;
}
>>> .el-upload--text img {
  max-width: 100%;
  max-height: 100%;
}
>>> .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 20px;
}
>>> .must label {
  color: red;
}
</style>
