<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline"
            v-if="checkPermission(['MemberManage:add'])" @click="handleAddMember">添加</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入会员编号" @advancedSearch="advancedSearchEvent" advanced>
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="姓名">
                  <el-input v-model="advancedForm.name"   placeholder="请输入会员名称"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                  <el-input v-model="advancedForm.mobile"  placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="advancedForm.email"  placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="禁用状态">
                  <el-select v-model="advancedForm.disable_flag">
                    <el-option :key="0" label="正常" :value="false" />
                    <el-option :key="-1" label="已禁用" :value="true" />
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column prop="sn" label="会员编号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" >
          <template slot-scope="scope">
            {{ scope.row.sex === 'Men'  ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="birthday" label="出生日期" />
        <el-table-column prop="disable_flag" label="状态">
          <template slot-scope="scope">
            {{ scope.row.disable_flag  ? '已禁用' : '正常' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" v-if="checkPermission(['MemberManage:edit'])"
              @click="handleEditMember(scope.$index, scope.row)">编辑</el-button>
            <template v-if="checkPermission(['MemberManage:disable'])">
              <el-button v-if="!scope.row.disable_flag" command="danger" @click="handleDisableMember(scope.$index, scope.row, true)">禁用</el-button>
              <el-button v-else command="open" @click="handleDisableMember(scope.$index, scope.row, false)">启用</el-button>
            </template>
            <el-button size="mini" type="danger"
              v-if="checkPermission(['MemberManage:del'])"
              @click="handleDeleteMember(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="memberForm.id ? '编辑会员' : '添加会员'" :visible.sync="dialogVisible" width="650px"
      @open="handleDialogOpen" :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="memberForm" :rules="memberRules" ref="memberForm" label-width="80px" inline>
        <el-form-item label="会员编号" prop="sn" >
          <el-input v-model="memberForm.sn" :maxlength="30" clearable placeholder="请输入会员编号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="memberForm.name" :maxlength="20" clearable placeholder="请输入会员名称"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="memberForm.sex" placeholder="请选择" clearable>
            <el-option label="男" value="Men"></el-option>
            <el-option label="女" value="Woman"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="birthday" label="出生日期" >
          <el-date-picker v-model="memberForm.birthday" value-format="timestamp" type="datetime" placeholder="选择日期时间" class="birthday">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="memberForm.mobile"  clearable
            placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="memberForm.email" :maxlength="30" clearable placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="form-item-remark">
          <el-input v-model="memberForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
                    placeholder="请输入备注" class="form-item-remark-input remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitmemberForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Member from '@/api/member'
import * as API_Setting from '@/api/setting'
import md5 from 'js-md5'
import { RegExp, Foundation } from '~/ui-utils'
export default {
  name: 'member',
  data() {
    return {
      deptList: [],
      postList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        user_state: 0
      },
      // 列表数据
      tableData: '',
      // 人员表单
      memberForm: {
        sex: 'Men',
        disable_flag: false
      },
      advancedForm: {
        disable_flag: false
      },
      // 人员表单 规则
      memberRules: {
        sn: [
          this.MixinRequired('会员编号必填！'),
          { min: 2, max: 30, message: '长度在 2 到 30 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }],
        mobile: [
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.mobile.test(value)) {
                callback(new Error('手机号格式错误！'))
              } else {
                callback()
              }
            }
          }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.email.test(value)) {
                callback(new Error('邮箱格式错误！'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      // 人员表单 dialog
      dialogVisible: false
    }
  },
  watch: {
  },
  mounted() {
    this.GET_MemberList()
  },
  methods: {
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.Contract_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.Contract_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.Contract_time_range[1]) / 1000)
      }
      delete this.params.Contract_time_range
      this.params.page_no = 1
      this.GET_MemberList()
    },
    uploadSuccess(res) {
      this.$set(this.memberForm, 'face', res.url)
      this.$refs.faceImage.clearValidate()
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_MemberList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_MemberList()
    },

    /** 添加人员 */
    handleAddMember() {
      this.memberForm = {
        sex: 'Men',
        disable_flag: false
      }
      this.dialogVisible = true
    },

    /** 编辑人员 */
    handleEditMember(index, row) {
      this.memberForm = this.MixinClone(row)
      this.dialogVisible = true
    },
    /** 删除人员 */
    handleDeleteMember(index, row) {
      this.$confirm('确定要删除这个人员吗？', '提示', { type: 'warning' }).then(() => {
        API_Member.deleteMember(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_MemberList()
        })
      }).catch(() => { })
    },
    /** 禁用/启用人员 */
    handleDisableMember(index, row, disable) {
      this.$confirm('确定要' + (disable ? '禁用' : '启用') + '这个人员吗？', '提示', { type: 'warning' }).then(() => {
        if (disable) {
          API_Member.disableMember(row.id).then(() => {
            this.$message.success('禁用成功！')
          })
        } else {
          API_Member.enableMember(row.id).then(() => {
            this.$message.success('启用成功！')
          })
        }
        this.GET_MemberList()
      }).catch(() => { })
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => { this.$refs['memberForm'].clearValidate() })
    },

    /** 提交人员表单 */
    submitmemberForm() {
      this.$refs['memberForm'].validate((valid) => {
        if (valid) {
          const { id } = this.memberForm
          const params = this.MixinClone(this.memberForm)
          if (id) {
            API_Member.editMember(id, params).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_MemberList()
            })
          } else {
            API_Member.addMember(params).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功！')
              this.GET_MemberList()
            })
          }
        } else {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      this.params.page_no = 1
      this.GET_MemberList()
    },

    /** 获取人员列表 */
    GET_MemberList() {
      this.loading = true
      API_Member.getMemberList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.remark{
  width: 256%;
}

.birthday{
  width: 94%;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
