<template>
  <div class="app-container">
    <div class="app-header-top" style="width: 100%;float: right;margin-bottom: 10px;">
      <div class="app-title">当前机构：{{ clubTitle }} </div>
      <el-button type="primary" icon="el-icon-back" style="float: right;" @click="backToList">返回</el-button>
    </div>
    <div class="filter-container">
      <div class="filter-control">
        <span style="width: auto;">姓名:</span>
        <el-input v-model="listQuery.linkName" style="width:130px;" placeholder="请输入姓名" clearable @keyup.enter.native="getList" @clear="getList" />
      </div>
      <div class="filter-control">
        <span style="width: auto;">手机号:</span>
        <el-input v-model="listQuery.mobile" style="width:130px;" placeholder="请输入手机号" clearable @keyup.enter.native="getList" @clear="getList" />
      </div>
      <div class="filter-control">
        <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column label="姓名" align="center" prop="linkName" />
      <el-table-column label="手机号码" align="center" prop="mobile" />
      <el-table-column class-name="status-col" label="微信绑定状态" align="center" prop="status">
        <template slot-scope="{row}">
          <i v-if="row.status === '2'" class="el-icon-success" style="color:#67C23A;font-size: 18px;" />
          <!-- <i v-else class="el-icon-error" style="color: #E6A23C;font-size: 20px;" /> -->
        </template>
      </el-table-column>
      <el-table-column align="center" label="绑定时间" prop="bindTime">
        <template slot-scope="{row}">
          <span v-if="row.bindTime">{{ row.bindTime }}</span>
          <span v-else>----</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>20" :total="total" :page.sync="listQuery.index" :limit.sync="listQuery.pageSize" @pagination="initOperatorListData" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="440px">
      <el-form ref="dataForm" :rules="rules" :model="editTemp" label-position="left" label-width="70px" style="width: 400px;">
        <el-form-item label="姓名" prop="linkName">
          <el-input v-model="editTemp.linkName" placeholder="请输入姓名" maxlength="11" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editTemp.mobile" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="loadingbut" @click="handleCreateOperator()">{{ loadingbuttext }}</el-button>
        <el-button v-if="dialogStatus === 'add'" type="primary" @click="handlePreservOperator()">保存生成邀请码</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="20%">
      <span>{{ dialogVisibleText }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadingbut" @click="handleConfirm()">{{ loadingbuttext }}</el-button>
      </span>
    </el-dialog>
    <template>
      <el-backtop style="right: 40px; bottom: 40px;">
        <i class="el-icon-upload2" />
      </el-backtop>
    </template>
  </div>
</template>

<script>
import { getOperatorList, updateOperatorCode, unbindOperator, preservOperator } from '@/api/club'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'gray'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      pageNum: 0,
      list: null,
      clubTitle: this.$route.query.name,
      listLoading: true,
      total: 0,
      dialogVisible: false,
      dialogVisibleText: '',
      handleConfirmType: '',
      listQuery: {
        index: 1,
        pageSize: 20,
        clubID: this.$route.query.clubId,
        userID: this.$route.query.userId,
        userorganizeId: this.$store.getters.organizeId,
        linkName: '',
        mobile: '',
        status: '',
        beginAddTime: '',
        endAddTime: ''
      },
      editTemp: {
        userorganizeId: this.$store.getters.organizeId,
        linkName: '',
        mobile: ''
      },
      codeRemp: {},
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogStatus: '',
      loadingbut: false,
      loadingbuttext: '确定',
      textMap: {
        add: '添加运营人员',
        edit: '编辑运营人员',
        update: '提示',
        untying: '解绑',
        generate: '生成邀请码',
        updateCode: '更新邀请码'
      },
      rules: {
        linkName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            required: true,
            pattern: /^\d{11}|\d{13}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }]
      }
    }
  },
  computed: {
    organizeId() {
      return this.$store.getters.organizeId
    }
  },
  created() {
    this.initOperatorListData()
  },
  methods: {
    initOperatorListData() {
      this.listLoading = true
      getOperatorList(this.listQuery).then(response => {
        const operatorListPage = response.data
        this.pageNum = operatorListPage.index
        this.list = operatorListPage.results
        this.total = operatorListPage.totalRecord
        this.listLoading = false
      })
    },
    handleGenerateCode(row) {
      this.dialogVisible = true
      if (row.invitationCode) {
        this.dialogStatus = 'updateCode'
        this.dialogVisibleText = '确定生成邀请码吗?生成后将会短信通知该运营人员。'
      } else {
        this.dialogStatus = 'generate'
        this.dialogVisibleText = '确定生成邀请码吗?生成后将会短信通知该运营人员。'
      }
      this.handleConfirmType = 'generate'
      this.codeRemp = {
        id: row.id,
        clubID: row.clubID,
        userID: row.userID,
        userorganizeId: this.$store.getters.organizeId
      }
    },
    handleConfirm() {
      switch (this.handleConfirmType) {
        case 'untying':
          this.unbindOperators()
          break
        case 'generate':
          this.generateRequst()
          break
      }
    },
    generateRequst() {
      const params = this.codeRemp
      this.loadingbut = true
      this.loadingbuttext = '请稍候...'
      updateOperatorCode(params).then(response => {
        this.$message({ message: response.msg, type: 'success', center: true })
        this.loadingbut = false
        this.loadingbuttext = '确定'
        this.dialogVisible = false
        setTimeout(() => {
          this.initOperatorListData()
        }, 1000)
      })
    },
    handleUntying(row) {
      this.dialogVisible = true
      this.dialogStatus = 'untying'
      this.dialogVisibleText = '确定解绑该运营人员吗?'
      this.handleConfirmType = 'untying'
      this.editTemp = { userorganizeId: this.$store.getters.organizeId, id: row.id, userId: row.clubId, userID: row.userID }
    },
    unbindOperators() {
      const params = this.editTemp
      this.loadingbut = true
      this.loadingbuttext = '解绑中...'
      unbindOperator(params).then(response => {
        this.$message({ message: response.msg, type: 'success', center: true })
        this.dialogVisible = false
        this.loadingbut = false
        this.loadingbuttext = '确定'
        setTimeout(() => {
          this.initOperatorListData()
        }, 1000)
      })
    },
    bindAddPeople() { // 添加运营人员
      this.loadingbuttext = '保存'
      const addTemp = { clubID: this.listQuery.clubID, userID: this.listQuery.userID }
      this.editTemp = Object.assign({}, addTemp)
      console.log(this.editTemp)
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) { // 编辑
      this.loadingbuttext = '保存'
      const rowTemp = { id: row.id, clubID: row.clubID, userID: row.userID, linkName: row.linkName, mobile: row.mobile }
      this.editTemp = Object.assign({}, rowTemp)
      console.log(this.editTemp)
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreateOperator() { // 保存
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const params = Object.assign({ userorganizeId: this.$store.getters.organizeId, configFlag: 1 }, this.editTemp)
          this.loadingbut = true
          this.loadingbuttext = '保存中...'
          preservOperator(params).then(response => {
            this.$message({ message: response.msg, type: 'success', center: true })
            this.dialogFormVisible = false
            this.loadingbut = false
            this.loadingbuttext = '确定'
            setTimeout(() => {
              this.initOperatorListData()
            }, 3000)
          }).catch(() => {
            this.loadingbut = false
            this.loadingbuttext = '保存'
          })
        }
      })
    },
    handlePreservOperator() { // 保存并生成邀请码
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const Formobj = { userorganizeId: this.$store.getters.organizeId, configFlag: 2 }
          const params = Object.assign(Formobj, this.editTemp)
          preservOperator(params).then(response => {
            this.dialogFormVisible = false
            this.$message({ message: response.msg, type: 'success', center: true })
            setTimeout(() => {
              this.initOperatorListData()
            }, 1000)
          })
        }
      })
    },
    handleFilter() {
      this.initOperatorListData()
    },
    rexpStautsText(status) {
      let text = ''
      switch (status) {
        case '1':
          text = '有效'
          break
        case '2':
          text = '已使用'
          break
        case '3':
          text = '已失效'
          break
      }
      return text
    },
    rexpStautsColor(status) {
      let textColor = ''
      switch (status) {
        case '1':
          textColor = '#E6A441'
          break
        case '2':
          textColor = '#417DE6'
          break
        case '3':
          textColor = '#C5C5C5'
          break
      }
      return textColor
    },
    backToList() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({
            path: '/club/list'
          })
        })
      })
    }
  }
}
</script>
<style lang="scss">
  .app-title{
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    color: #999999;
    margin-bottom:10px;
    color: #417DE6;
    float: left;
  }
</style>
