<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="app-header-search">
      <el-form class="demo-form-inline">
        <el-form-item label="姓名:" style="width:210px;float: left;">
          <el-input v-model="listQuery.linkName" placeholder="请输入姓名" maxlength="50" style="width:150px;" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="手机号:" style="width:200px;float: left;">
          <el-input v-model="listQuery.mobile" placeholder="请输入手机号" maxlength="11" style="width:130px" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="状态:" style="width:160px;float: left;">
          <el-select v-model="listQuery.status" placeholder="请选择" style="width:100px" value="" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="已绑定" value="2" />
            <el-option label="未绑定" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加时间:" style="width:410px;float: left;">
          <el-date-picker
            v-model="listQuery.beginAddTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 150px;"
          />
          至
          <el-date-picker
            v-model="listQuery.endAddTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item style="width:100px;float: left;">
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        </el-form-item>
        <el-form-item style="width:100px;float: left;">
          <el-button type="primary" @click="bindAddPeople()">添加运营人员</el-button>
        </el-form-item>
      </el-form>
    </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 align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ ((pageNum-1)*listQuery.pageSize)+scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center" prop="account" />
      <el-table-column label="姓名" min-width="80" align="center" prop="linkName" />
      <el-table-column label="手机号码" min-width="80" align="center" prop="mobile" />
      <el-table-column label="邀请码" min-width="80" align="center" prop="invitationCode">
        <template slot-scope="{row}">
          <div style="width:130px;margin: 0 auto;">
            <span v-if="row.invitationCode" style="text-align: center;float:left">{{ row.invitationCode }}</span>
            <span v-if="row.invitationCode" :style="{color: rexpStautsColor(row.effectiveFlag)}">{{ rexpStautsText(row.effectiveFlag) }}</span>
            <span v-else type="info">----</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="50" 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 label="微信昵称" align="center" prop="nickName">
        <template slot-scope="{row}">
          <span v-if="row.nickName">{{ row.nickName }}</span>
          <span v-else>----</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="OpenID" prop="openid">
        <template slot-scope="{row}">
          <span v-if="row.openid">{{ row.openid }}</span>
          <span v-else>----</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="添加时间" prop="addTime">
        <template slot-scope="{row}">
          <span v-if="row.addTime">{{ row.addTime }}</span>
          <span v-else>----</span>
        </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-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" style="width: 90px;margin:5px 0 0 0;" @click="handleEdit(row)">编辑</el-button>
          <el-button v-if="row.status === '2'" type="primary" size="mini" style="width: 90px;margin:5px 0 0 0;" @click="handleUntying(row)">解绑</el-button>
          <el-button v-else type="primary" size="mini" style="width: 90px;margin:5px 0 0 0;" @click="handleGenerateCode(row)">{{ row.invitationCode ? '更新邀请码' : '生成邀请码' }}</el-button>
        </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: 100,
      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, clubID: 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>
