<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信昵称" prop="mpNickName">
        <el-input
          v-model="queryParams.mpNickName"
          placeholder="请输入微信昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:contacts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:contacts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contactsList">
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="姓名" align="left" prop="name" />
      <el-table-column label="手机号码" align="left" prop="phone" />
      <el-table-column label="微信昵称" align="left" prop="mpNickName" />
      <el-table-column label="头像" align="center" width="50px" prop="mpAvatar">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image
              v-if="scope.row.mpAvatar"
              style="width: 35px; height: 35px"
              :src="getIotFileUrl(scope.row.mpAvatar)"
              :preview-src-list="[getIotFileUrl(scope.row.mpAvatar)]"
            ></el-image>
            <span v-else>暂无</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        width="120px"
        prop="status"
        :formatter="statusFormatter"
      />
      <el-table-column
        label="操作"
        align="center"
        width="300px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:contacts:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handelBinding(scope.row)"
            v-hasPermi="['iot:contacts:edit']"
          >绑定微信</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-c-scale-to-original"
            @click="handleUbind(scope.row)"
            v-hasPermi="['iot:contacts:edit']"
          >解绑微信</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:contacts:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改联系人对话框 -->
    <el-dialog class="eldialog-wrap" :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名:" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号码:" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="状态:" >
          <el-switch
            v-model="form.status"
            active-value='0'
            inactive-value='1'
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="描述:" >
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入描述" />
        </el-form-item>
        <!-- <el-form-item label="邮箱地址:" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改联系人对话框 -->
    <el-dialog class="eldialog-wrap" :close-on-click-modal="false" title="授权扫二维码" :visible.sync="qrCodeDialogOpen" width="650px">
      <div class="qrcode-wrap" v-if="qrCodeDialogOpen">
        <div class="qr-wrap">
          <img src="@/assets/images/gzhqr.jpg"/>
          <span>第一步：扫码关注公众号。</span>
        </div>
        <el-button type="text" style="font-size: 20px;" icon="el-icon-d-arrow-right"></el-button>
        <div class="qr-wrap">
          <div id="qrcode"></div>
          <span style="margin-top: 10px;">第二步：扫码绑定微信。</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" style="margin-right: 10px;" @click="qrCodeSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContacts,
  getContacts,
  delContacts,
  addContacts,
  updateContacts,
  exportContacts,
  getqrcodeUrl,
  contactsUbind
} from "@/api/iot/contacts";
import { getIotFileUrl } from "@/utils/hciot";
import QRCode from "qrcodejs2";
import gzhqr from "@/assets/images/gzhqr.jpg"

export default {
  name: "Contacts",
  components: {},
  data() {
    return {
      gzhqr,
      qrCodeDialogOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 联系人表格数据
      contactsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        mpNickName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getIotFileUrl,
    statusFormatter(row) {
      return row.status === '0' ? '正常' : '停用';
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询联系人列表 */
    getList() {
      this.loading = true;
      listContacts(this.queryParams).then(response => {
        this.contactsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        phone: null,
        email: null,
        remark: null,
        status: '0'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加联系人";
    },
    // 绑定微信号操作
    handelBinding(row) {
      getqrcodeUrl({
        id: row.id
      }).then(res => {
        this.qrCodeDialogOpen = true;
        setTimeout(() => {
          this.qrcode(res.data);
        }, 50);
      });
    },
    qrcode(url) {
      if (!document.querySelector("#qrcode")) {
        return;
      }
      // document.querySelector('#qrcode').innerHtml = ""
      let qrcode = new QRCode("qrcode", {
        width: 250,
        height: 250,
        text: url
      });
    },
    qrCodeSubmit() {
      this.qrCodeDialogOpen = false;
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getContacts(id).then(response => {
        this.form = response.data;
        this.form.status = this.form.status.toString();
        this.open = true;
        this.title = "修改联系人";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContacts(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContacts(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 解绑微信
    handleUbind(row) {
      const ids = row.id
      this.$confirm("是否解除此微信号绑定?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return contactsUbind(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("解绑成功");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delContacts(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有联系人数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportContacts(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
<style lang="scss">
.qrcode-wrap {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  .qr-wrap {
    height: 100%;
    display: flex;
    width: 45%;
    -webkit-box-align: self-start;
    -ms-flex-align: self-start;
    align-items: self-start;
    flex-wrap: wrap;
    justify-content: center;
    padding-top: 10px;
  }
}
#qrcode {
}
</style>
