<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="超级会员列表" name="first" />
      <el-tab-pane label="赠送超级会员" name="second" />
      <template v-if="activeName === 'first'">
        <div class="filter-container">
          <div class="filter-control">
            <span>机构名称:</span>
            <el-input
              v-model="listQuery.clubName"
              placeholder="机构名称"
              clearable
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>联系人:</span>
            <el-input
              v-model="listQuery.linkMan"
              placeholder="联系人"
              clearable
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>手机号:</span>
            <el-input
              v-model="listQuery.mobile"
              placeholder="手机号"
              clearable
              style="width:160px;"
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>购买套餐:</span>
            <el-select v-model="listQuery.packageId" style="width:120px;" clearable @change="getList">
              <el-option value="" label="请选择" />
              <el-option :value="0" label="系统赠送" />
              <el-option :value="1" label="1个月" />
              <el-option :value="3" label="3个月" />
              <el-option :value="12" label="12个月" />
            </el-select>
          </div>
          <div class="filter-control">
            <span>会员状态:</span>
            <el-select v-model="listQuery.status" style="width:120px;" clearable @change="getList">
              <el-option value="" label="请选择" />
              <el-option :value="1" label="已生效" />
              <el-option :value="2" label="已过期" />
            </el-select>
          </div><br>
          <div class="filter-control">
            <span>购买时间:</span>
            <el-date-picker
              v-model="time"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="getList"
            />
          </div>
          <div class="filter-control">
            <span>到期时间:</span>
            <el-date-picker
              v-model="dueTime"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerEndOptions"
              @change="getList"
            />
          </div>
          <div class="filter-control">
            <el-button type="primary" @click="getList">查询</el-button>
          </div>
        </div>
        <el-table v-loading="isLoading" :data="tableData" border style="width: 100%" :height="580">
          <el-table-column prop="clubName" label="机构名称" align="center" />
          <el-table-column prop="linkMan" label="联系人" align="center" />
          <el-table-column prop="mobile" label="手机号" align="center" />
          <el-table-column prop="status" label="会员状态" align="center" width="180">
            <template slot-scope="{ row }">
              <span :class="{
                'el-span-status': row.status == '1',
                'el-span-notStatus': row.status == '2',
                'el-span-notEffective': row.status == '3',
              }"
              >
                {{ row.status | statusFilters }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="handleTagsList(row)">购买记录</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 页码 -->
        <pagination
          :total="total"
          :page-sizes="[20, 30, 50, 100]"
          :page-size="20"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          @pagination="getList"
        />
      </template>
      <template v-else>
        <div class="club-container" style="width: 100%;height: 600px;padding-top: 40px;">
          <div class="filter-container">
            <div class="filter-control">
              <el-form :model="vipForm" :rules="rules" label-width="120px">
                <el-form-item label="机构" prop="clubId" :hidden="!hiddenItem">
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleDialogVisible">请选择机构</el-button>
                  <el-checkbox-group v-show="false" v-model="vipForm.clubId" />
                </el-form-item>
                <el-form-item label="机构" :hidden="hiddenItem">
                  <el-table :data="clubData" border width="1000">
                    <el-table-column prop="clubId" label="机构ID" align="center" width="120" />
                    <el-table-column prop="name" label="机构名称" align="center" width="250" />
                    <el-table-column prop="linkMan" label="联系人" align="center" width="120" />
                    <el-table-column prop="contractMobile" label="手机号" align="center" width="120" />
                    <el-table-column label="操作" align="center" width="120">
                      <el-button type="danger" size="mini" @click="deleteClub">删除</el-button>
                    </el-table-column>
                  </el-table>
                </el-form-item>
                <el-form-item label="赠送会员" :rules="rules.month">
                  <el-input v-model="vipForm.month" style="width: 150px">
                    <template slot="append">个月</template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :disabled="saveDisabled" @click="handleSaveVip">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </template>
    </el-tabs>
    <!-- 机构弹框 -->
    <el-dialog title="选择机构" :visible.sync="dialogTableVisible" width="1000px">
      <div class="filter-container">
        <div class="filter-control">
          <span>机构ID:</span>
          <el-input
            v-model="clubForm.clubId"
            placeholder="机构Id"
            clearable
            @input="checkedInput"
          />
        </div>
        <div class="filter-control">
          <span>机构名称:</span>
          <el-input
            v-model="clubForm.name"
            placeholder="机构名称"
            clearable
          />
        </div>
        <div class="filter-control">
          <span>机构简称:</span>
          <el-input
            v-model="clubForm.shortName"
            placeholder="机构简称"
            clearable
          />
        </div>
        <div class="filter-control">
          <el-button type="primary" @click="searchGetclubList">搜索</el-button>
        </div>
      </div>
      <el-table ref="table" :data="clubTableData" height="350px" border @select="handleSelect">
        <el-table-column type="selection" width="55" />
        <el-table-column property="clubId" label="机构Id" align="center" width="150" />
        <el-table-column property="name" label="机构名称" align="center" width="150" />
        <el-table-column property="shortName" label="机构简称" align="center" width="200" />
        <el-table-column property="linkMan" label="联系人" align="center" />
        <el-table-column property="contractMobile" label="手机号" align="center" />
      </el-table>
      <div slot="footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="pushClub()">确定</el-button>
      </div>
      <!-- 页码 -->
      <pagination
        :total="clubTotal"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="20"
        :page.sync="clubForm.pageNum"
        :limit.sync="clubForm.pageSize"
        @pagination="getclubList"
      />
    </el-dialog>
  </div>
</template>

<script>

import { fetchMemberList, fetchClubList, saveSvip } from '@/api/member/member'

const defaultListQuery = {
  clubName: '', // 机构名称
  linkMan: '', // 联系人
  mobile: '', // 手机号
  packageId: '', // 购买套餐
  status: '', // 会员状态
  startPayTime: '', // 购买开始时间
  endPayTime: '', // 购买结束时间
  startEndTime: '', //  到期开始时间
  endEndTime: '', // 到期结束时间
  pageNum: 1,
  pageSize: 20
}
export default {
  name: 'MemberList',
  filters: {
    statusFilters(value) {
      console.log('value', value)
      // 处理状态显示
      const map = {
        '0': '未生效',
        '1': '已生效',
        '2': '已过期',
        '3': '暂未生效'
      }
      return map[value]
    }
  },
  data() {
    const pickerOptions = {
      shortcuts: [
        {
          text: '近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 183)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }
      ]
    }
    const pickerEndOptions = {
      shortcuts: [
        {
          text: '近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 183)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }
      ]
    }
    return {
      isLoading: true,
      activeName: 'first',
      pickerOptions,
      pickerEndOptions,
      time: '',
      dueTime: '',
      listQuery: Object.assign({}, defaultListQuery),
      // 会员列表总数
      total: 0,
      tableData: [],
      vipForm: {
        clubId: '',
        userId: '',
        contractMobile: '',
        month: ''
      },
      dialogTableVisible: false,
      // 选择机构总数
      clubTotal: 0,
      clubForm: {
        clubId: '',
        name: '',
        shortName: '',
        pageNum: 1,
        pageSize: 20
      },
      hiddenItem: true,
      clubTableData: [],
      clubRadio: null,
      rows: [], // 选择机构
      clubData: [], // 机构数据
      rules: {
        month: [{ required: true, message: '请输入赠送数量', trigger: 'blur' }],
        clubId: [{ required: true, message: '请选择机构', trigger: 'blur' }]
      }
    }
  },
  computed: {
    disabled() {
      return this.clubRadio === null
    },
    saveDisabled() {
      return !(this.vipForm.clubId > 0 && this.vipForm.month !== '')
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 选择机构
    handleSelect(selection, row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
      this.clubRadio = row.clubId
      this.vipForm.clubId = row.clubId
      this.vipForm.userId = row.userId
      this.vipForm.contractMobile = row.contractMobile
      this.rows = row
      console.log('clubRadio', this.clubRadio)
    },
    initTime() {
      // 初始化获取时间筛选值
      if (this.time && this.time.length > 0) {
        this.listQuery.startPayTime = this.time[0]
        this.listQuery.endPayTime = this.time[1]
      } else {
        this.listQuery.startPayTime = ''
        this.listQuery.endPayTime = ''
      }
      if (this.dueTime && this.dueTime.length > 0) {
        this.listQuery.startEndTime = this.dueTime[0]
        this.listQuery.endEndTime = this.dueTime[1]
      } else {
        this.listQuery.startEndTime = ''
        this.listQuery.endEndTime = ''
      }
    },
    // 会员列表数据
    async getList() {
      this.isLoading = true
      this.initTime()
      const res = await fetchMemberList(this.listQuery)
      this.tableData = res.data.results
      this.total = res.data.totalRecord
      this.isLoading = false
    },
    handleDialogVisible() {
      // 宣誓弹窗
      this.dialogTableVisible = true
      this.getclubList()
    },
    searchGetclubList() {
      // 搜索
      this.clubForm.pageNum = 1
      this.getclubList()
    },
    // 机构数据
    async getclubList() {
      const res = await fetchClubList(this.clubForm)
      this.clubTableData = res.data.results
      this.clubTotal = res.data.totalRecord
    },
    // 机构选择确认
    pushClub() {
      this.clubData.push(this.rows)
      this.dialogTableVisible = false
      this.row = []
      this.hiddenItem = false
      console.log(this.clubData)
    },
    // 清除机构
    deleteClub() {
      this.clubData = []
      this.hiddenItem = true
    },
    async handleSaveVip() {
      try {
        await saveSvip(this.vipForm)
        this.$message.success('操作成功')
        setTimeout(() => {
          this.activeName = 'first'
          this.getList()
          this.deleteClub()
          this.vipForm.month = ''
        }, 2000)
      } catch (error) {
        console.log(error)
      }
    },
    handleTagsList(row) {
      const query = {
        userId: row.userId,
        clubName: row.clubName, // 机构名称
        linkMan: row.linkMan, // 联系人
        mobile: row.mobile// 手机号
      }
      this.$router.push({ path: '/member/member/record-list', query: query })
    },
    checkedInput(event) {
      this.clubForm.clubId = event.replace(/[^\d]/g, '')
      console.log('event', this.clubForm.clubId)
    }
  }
}

</script>

<style lang="scss" scoped>
::v-deep{
  thead .el-checkbox{display: none !important;}
}
.el-span-status {
  color: rgb(16, 230, 8);
}
.el-span-notStatus {
  color: rgb(245, 13, 13);
}
.el-span-notEffective {
  color: rgb(245, 13, 13);
}
</style>
