<template>
  <div>
    <div class="search">
      <el-button type="primary" icon="el-icon-plus" @click="addContactItem">
        添加
      </el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        :disabled="!selectedRows.length"
        @click="delContactItem"
      >
        删除
      </el-button>
      <el-input
        v-model="searchKey"
        clearable
        placeholder="请输入关键词 联系人名称/邮箱地址"
        @keyup.enter.native="search"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" @click="search">搜索</el-button>
    </div>

    <div class="contacts-table">
      <el-table
        v-loading="loading"
        border
        :data="contactsList"
        :height="tableHeight"
        :header-cell-style="headerStyle"
        @selection-change="selectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50"
        ></el-table-column>

        <el-table-column
          align="center"
          type="index"
          width="60"
          label="序号"
        ></el-table-column>

        <el-table-column
          prop="linkName"
          label="联系人名称"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column
          prop="mailId"
          label="邮箱地址"
          width="360"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column
          prop="phone"
          label="联系人电话"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column align="center" label="操作" width="120">
          <template #default="{ row }">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="updateContactItem(row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="pageSizes"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-row>
    </div>

    <!-- 添加联系人 dialog -->
    <div class="dialog">
      <el-dialog
        width="600px"
        title="添加邮箱联系人"
        :visible.sync="contactDialogVisible"
        :close-on-click-modal="false"
      >
        <el-form
          ref="form"
          :rules="rules"
          :model="contactForm"
          label-width="120px"
        >
          <el-form-item label="联系人名称：" prop="linkName">
            <el-input
              v-model="contactForm.linkName"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="邮箱地址：" prop="mailId">
            <el-input
              v-model="contactForm.mailId"
              maxlength="30"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="联系人电话：" prop="phone">
            <el-input v-model="contactForm.phone"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="contactDialogVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import tableCommon from '@/mixins/tableCommon'
  import { saveContact, delContactById, getContactList } from '@/api/personal'
  export default {
    name: 'MailContacts',
    mixins: [tableCommon],
    data() {
      var checkName = (rule, value, callback) => {
        var pattern = new RegExp(
          "[`~!@#$%^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]"
        )
        if (value == '') {
          callback(new Error('请输入联系人名称'))
        } else if (pattern.test(value)) {
          callback(new Error('联系人名称包含特殊字符，请重新输入'))
        } else {
          callback()
        }
      }
      var checkphone = (rule, value, callback) => {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (value == '') {
          callback(new Error('请输入手机号'))
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确的手机号!'))
        } else {
          callback()
        }
      }
      return {
        loading: false,
        searchKey: '',
        contactDialogVisible: false,

        contactsList: [],
        contactForm: {
          linkName: '',
          mailId: '',
          phone: '',
        },

        rules: {
          mailId: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '邮箱地址不正确',
              trigger: 'blur',
            },
          ],
          linkName: [{ required: true, validator: checkName, trigger: 'blur' }],
          phone: [{ required: true, validator: checkphone, trigger: 'blur' }],
        },
      }
    },
    created() {
      this.search()
    },
    methods: {
      addContactItem() {
        this.contactForm = {
          linkName: '',
          mailId: '',
          phone: '',
        }
        this.contactDialogVisible = true
      },
      updateContactItem(row) {
        this.contactForm = { ...row }
        this.contactDialogVisible = true
      },
      delContactItem() {
        this.$confirm('确定删除该联系人？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const ids = []
          this.selectedRows.forEach((item) => {
            ids.push(item.id)
          })
          delContactById(ids.join(',')).then((res) => {
            if (res.state) {
              this.$message.success(res.message)
              this.search()
            }
          })
        })
      },
      search(isPageChange) {
        this.loading = true
        if (!isPageChange) {
          this.pagination.page = 1
        }
        const queryFilter = {
          pageBean: this.pagination,
        }
        if (this.searchKey !== '') {
          queryFilter.querys = [
            {
              property: 'linkName',
              value: this.searchKey,
              group: 'main',
              operation: 'LIKE',
              relation: 'OR',
            },
            {
              property: 'mailId',
              value: this.searchKey,
              group: 'main',
              operation: 'LIKE',
              relation: 'OR',
            },
          ]
        }
        getContactList(queryFilter).then((data) => {
          if (data) {
            this.pagination = {
              page: data.page,
              pageSize: data.pageSize,
              total: data.total,
            }
            this.contactsList = data.rows ? data.rows : []
            setTimeout(() => {
              this.loading = false
            }, 300)
          }
        })
      },
      submitForm() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            saveContact(this.contactForm).then((res) => {
              if (res.state) {
                this.$message.success(res.message)
                this.contactDialogVisible = false
                this.search()
              }
            })
          } else {
            this.$message.error('您输入表单信息有误，请重新填写！')
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .search {
    padding-bottom: 20px;
    border-bottom: 1px solid $base-border-color;
    .el-input {
      width: 400px;
      margin: 0 10px;
    }
  }
</style>
