<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-tabs v-model="searchParams.status" @tab-click="handleClick">
      <el-tab-pane name="0" label="销售审核流程-未授权" />
      <el-tab-pane name="1" label="已授权" />
      <el-tab-pane name="2" label="已过期" />
    </el-tabs>
    <div style="margin-bottom: 10px">
      <el-input
        v-model="searchParams.search_name"
        placeholder="昵称/手机号/姓名"
        size="small"
        style="width:250px"
      />
      <el-button type="primary" size="small" @click="searchParams.page_index = 1;getList()">
        查询
      </el-button>
    </div>
    <el-table
      ref="multipleTable"
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        v-show="searchParams.status === '2'"
        type="selection"
        width="50"
        align="center"
      />
      <el-table-column prop="nickname" label="昵称" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleSeeMemberInfo(row)">{{
            row.nickname
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="realname"
        align="center"
        label="真实姓名"
        width="120"
      />
      <el-table-column
        prop="mobile"
        label="手机号"
        align="center"
      />
      <el-table-column
        prop="level"
        label="代理级别"
        align="center"
        width="100"
      >
        <template
          slot-scope="{ row }"
        >
          <el-tag
            :color="levelStatus(row.level).color"
            style="color:#ffffff;"
          >
            {{ levelStatus(row.level).name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="加入时间"
        align="center"
        width="155"
      />
      <el-table-column
        prop="recom"
        label="邀请人"
        align="center"
        width="130"
      >
        <template slot-scope="{ row }">
          <span class="buttonText" @click="getOtherInfo(row.recom.id)">{{ row.recom && row.recom.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="agent"
        label="上级代理"
        align="center"
        width="130"
      >
        <template slot-scope="{ row }">
          <span class="buttonText" @click="getOtherInfo(row.agent.id)">{{ row.agent && row.agent.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auth_status"
        label="授权状态"
        align="center"
        width="80"
      >
        <template slot-scope="{ row }">
          <el-tag
            :color="row.auth_status === 0 ? '#909399' : (row.auth_status === 1 ? '#67C23A' : '#F56C6C')"
            style="color:#ffffff;"
          >
            {{
              row.auth_status === 0
                ? "未授权"
                : row.auth_status === 1
                  ? "已授权"
                  : "已过期"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="cert_status"
        label="认证状态"
        align="center"
        width="100"
      >
        <template slot-scope="{ row }">
          {{ certStatus(row) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="auth_code"
        label="授权编号"
        width="235"
        align="center"
      >
        <template slot-scope="{ row }">
          {{
            row.auth_code
              ? row.auth_code
              : row.auth_status === 0
                ? "未授权"
                : row.auth_status === 1
                  ? "已授权"
                  : "已过期"
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="authTerm"
        label="授权期限"
        width="160"
        align="center"
      >
        <template slot-scope="{ row }">
          <span v-if="row.auth_status === 0">
            待定
          </span>
          <span v-else>{{ row.auth_startime }}<br>至<br>{{ row.auth_endtime }}</span>
          <!-- {{ row.status === 0 ? '待定' : `${row.auth_startime} \n至\n ${row.auth_endtime}` }} -->
        </template>
      </el-table-column>
      <el-table-column
        v-if="searchParams.status === '2'"
        label="重新授权"
        align="center"
        width="80"
      >
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleSetOne(row)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-control">
      <el-button
        v-show="searchParams.status === '2'"
        type="primary"
        size="mini"
        @click="handleManySet"
      >批量授权</el-button>
      <div class="batch-container">
        <!-- 分页 -->
        <pagination
          :total="tableTotal"
          :limit="searchParams.page_size"
          :page="searchParams.page_index"
          style="margin-top:0"
          @pagination="changePagination"
          @update:limit="changePagination"
        />
      </div>
    </div>
    <!-- 销售信息 -->
    <el-drawer
      title="销售信息"
      :visible.sync="visible.userinfo"
      direction="rtl"
      :before-close="handleCloseUserinfo"
    >
      <el-form label-width="80px" style="padding: 0 20px">
        <el-form-item label="真实姓名:">{{ memberInfo.realname }}</el-form-item>
        <el-form-item label="身份证号:">{{ memberInfo.cre_num }}</el-form-item>
        <el-form-item label="联系电话:">{{ memberInfo.mobile }}</el-form-item>
        <el-form-item label="销售级别:">{{
          changeLevel(memberInfo.level)
        }}</el-form-item>
        <el-form-item label="微信昵称:">{{ memberInfo.nickname }}</el-form-item>
        <el-form-item label="授权状态:">{{
          memberInfo.auth_status === 0
            ? "未授权"
            : memberInfo.auth_status === 1
              ? "已授权"
              : "已过期"
        }}</el-form-item>
      </el-form>
    </el-drawer>
    <!-- 授权 -->
    <el-dialog
      title="销售授权"
      :visible.sync="visible.auth"
      :before-close="handleCloseAuthTime"
    >
      <el-form label-width="80px">
        <el-form-item label="销售信息">
          <p>昵称: {{ authInfo.nickname }}</p>
          <p>手机号: {{ authInfo.mobile }}</p>
          <p>销售级别: {{ changeLevel(authInfo.level) }}</p>
          <p>{{ `上级销售: ${authInfo.agent && authInfo.agent.nickname}` }}</p>
          <p>{{ `邀请人: ${authInfo.recom && authInfo.recom.nickname}` }}</p>
        </el-form-item>
        <el-form-item label="授权期限:">
          <el-date-picker
            v-model="authTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="left"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSureSet">授权</el-button>
          <el-button @click="handleCloseAuthTime">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 批量销售授权 -->
    <el-dialog
      title="批量销售授权"
      :visible.sync="visible.manyAuth"
      :before-close="handleCloseAuthMany"
    >
      <el-form label-width="80px">
        <el-form-item label="销售信息">
          <div style="max-height: 400px;overflow-y: scroll">
            <p v-for="item in manyAuthInfo" :key="item.id">
              {{ `${item.nickname}-${item.mobile}-${item.level}` }}
            </p>
          </div>
        </el-form-item>
        <el-form-item label="授权期限:">
          <el-date-picker
            v-model="authTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="left"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSureManySet">授权</el-button>
          <el-button @click="handleCloseAuthMany">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看销售详情 -->
    <el-drawer
      :title="`${seeMemberInfo.realname} - ${levelStatus(seeMemberInfo.level).name}`"
      :visible.sync="visible.memberInfo"
      direction="rtl"
      size="35%"
    >
      <MemberInfo :info="seeMemberInfo" :team-type="false" @getOtherInfo="getOtherInfo" />
    </el-drawer>
  </div>
</template>
<script>
import { getList, oneSet, matchSet } from '@/api/team/authorization'
// 获取上级销售或邀请人信息
import {
  getOtherInfo
} from '@/api/team/common'
// 公共方法
import {
  certStatus,
  levelStatus
} from '@/filters/common'
// 组件
import MemberInfo from './components/MemberInfo'
export default {
  components: {
    MemberInfo
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '一年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 365)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '两年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 730)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '三年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 1095)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      authTime: '',
      searchParams: {
        status: '0',
        search_name: '',
        page_index: 1,
        page_size: 10,
        auth_time: ''
      },
      table: [],
      tableTotal: 0,
      memberInfo: {
        nickname: '',
        mobile: '',
        level: '',
        cre_num: '',
        realname: '',
        auth_status: '',
        agent: {},
        recom: {}
      },
      visible: {
        userinfo: false,
        auth: false,
        manyAuth: false,
        memberInfo: false
      },
      authInfo: {
        nickname: '',
        mobile: '',
        level: '',
        id: '',
        agent: {},
        recom: {}
      },
      manyAuthInfo: [],
      manyAuthId: [],
      loadingFull: false,
      seeMemberInfo: {}
    }
  },
  watch: {
    'searchParams.status'() {
      this.searchParams.page_index = 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleClick(tab, event) {
      this.searchParams.status = tab.name
      this.getList()
    },
    handleCloseUserinfo() {
      this.memberInfo.nickname = ''
      this.memberInfo.mobile = ''
      this.memberInfo.level = ''
      this.memberInfo.cre_num = ''
      this.memberInfo.realname = ''
      this.memberInfo.auth_status = ''
      this.memberInfo.agent = {}
      this.memberInfo.recom = {}
      this.visible.userinfo = false
    },
    // 获取列表
    async getList() {
      this.loadingFull = true
      try {
        let res
        if (this.searchParams.status === '0') {
          const params = Object.assign({}, this.searchParams)
          this.$delete(params, 'auth_time')
          res = await getList(params)
        } else {
          res = await getList(this.searchParams)
        }
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取代理授权失败:${e}`)
      }
      this.loadingFull = false
    },
    // 关闭授权弹窗
    handleCloseAuthTime() {
      this.authInfo.id = ''
      this.authInfo.mobile = ''
      this.authInfo.level = ''
      this.authTime = ''
      this.authInfo.recom = {}
      this.authInfo.agent = {}
      this.visible.auth = false
    },
    // 单个授权
    handleSetOne(row) {
      const { id, nickname, mobile, level, agent, recom } = row
      this.authInfo.nickname = nickname
      this.authInfo.mobile = mobile
      this.authInfo.level = level
      this.authInfo.id = id
      this.authInfo.agent = agent
      this.authInfo.recom = recom
      this.visible.auth = true
    },
    // 单个授权
    handleSureSet() {
      const { id } = this.authInfo
      const auth_startime = this.authTime[0]
      const auth_endtime = this.authTime[1]
      this.oneSet({
        id,
        auth_startime,
        auth_endtime
      })
    },
    // 单个授权
    async oneSet(data) {
      try {
        const res = await oneSet(data)
        const { code, message } = res
        if (code === 200) {
          this.handleCloseAuthTime()
          this.getList()
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('单个会员授权失败!!!')
      }
    },
    // 批量授权
    handleManySet() {
      const members = this.$refs.multipleTable.selection
      if (members.length < 1) {
        this.$message.warning('请先选择代理')
        return false
      }
      members.map(item => {
        const data = {};
        // eslint-disable-next-line no-sequences
        (data.nickname = item.nickname), (data.mobile = item.mobile)
        data.level = item.level
        data.id = item.id
        this.manyAuthId.push(item.id)
        this.manyAuthInfo.push(data)
      })
      this.visible.manyAuth = true
    },
    // 关闭批量授权弹窗
    handleCloseAuthMany() {
      this.authTime = ''
      this.manyAuthId = []
      this.manyAuthInfo = []
      this.visible.manyAuth = false
    },
    // 批量授权
    handleSureManySet() {
      const auth_startime = this.authTime[0]
      const auth_endtime = this.authTime[1]
      this.matchSet({
        userId: this.manyAuthId,
        auth_startime,
        auth_endtime
      })
    },
    // 批量授权
    async matchSet(data) {
      try {
        const res = await matchSet(data)
        const { code, message } = res
        if (code === 200) {
          this.handleCloseAuthMany()
          this.getList()
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('批量会员授权失败!!!')
      }
    },
    // 销售级别
    changeLevel(level) {
      let out = ''
      switch (level) {
        case 0:
          out = '公司'
          break
        case 1:
          out = '代理公司'
          break
        case 2:
          out = '销售经理'
          break
        default:
          out = '销售主管'
      }
      return out
    },
    // 查看销售详情
    showMemberInfo(row) {
      const {
        nickname,
        mobile,
        level,
        cre_num,
        realname,
        auth_status,
        agent,
        recom
      } = row
      this.memberInfo.nickname = nickname
      this.memberInfo.mobile = mobile
      this.memberInfo.level = level
      this.memberInfo.cre_num = cre_num
      this.memberInfo.realname = realname
      this.memberInfo.auth_status = auth_status
      this.memberInfo.agent = agent
      this.memberInfo.recom = recom
      this.visible.userinfo = true
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getList()
    },
    // 销售级别
    levelStatus(level) {
      return levelStatus(level)
    },
    // 获取上级销售或邀请人信息
    async getOtherInfo(id) {
      if (!id) {
        this.$message.error('获取用户id失败')
        return false
      }
      this.loadingFull = true
      try {
        const res = await getOtherInfo({ id })
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          this.handleSeeMemberInfo(data)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取邀请人或上级代理信息失败:${e}`)
      }
      this.loadingFull = false
    },
    // 查看销售详情
    handleSeeMemberInfo(row) {
      this.seeMemberInfo = row
      this.visible.memberInfo = true
    },
    // 认证状态
    certStatus(row) {
      const { cert_status } = row
      return certStatus(cert_status)
    }
  }
}
</script>
