<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <template>
      <el-tabs v-model="listQuery.cert" @tab-click="handleTagToggle">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="未认证" name="0" />
        <el-tab-pane label="邀请人待审核" name="1" />
        <el-tab-pane label="上级待审核" name="2" />
        <el-tab-pane label="等待用户确认" name="3" />
        <el-tab-pane label="邀请人驳回" name="4" />
        <el-tab-pane label="上级驳回" name="5" />
        <el-tab-pane label="已授权" name="6" />
      </el-tabs>
    </template>

    <div class="filter-container">
      <el-input
        v-model="listQuery.search_name"
        placeholder="昵称/身份证号/手机号/姓名"
        class="filter-item filter-input"
      />
      <el-button
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        @click="listQuery.page_index = 1;getList()"
      >
        搜索
      </el-button>
    </div>

    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="nickname"
        align="center"
        label="昵称"
      >
        <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="130"
      />
      <el-table-column
        prop="mobile"
        align="center"
        label="手机号"
      />
      <el-table-column
        prop="level"
        align="center"
        label="代理级别"
        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="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="created_at"
        align="center"
        label="申请时间"
        width="160"
      />
      <el-table-column
        prop="status"
        align="center"
        label="认证状态"
        width="160"
      >
        <template
          slot-scope="{ row }"
        >
          {{ certStatus(row) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="listQuery.cert === '4'"
        prop="usercert"
        align="center"
        label="驳回原因"
      >
        <template
          slot-scope="{ row }"
        >
          {{ (row.usercert && row.usercert.recom_audit_desc) ? row.usercert.recom_audit_desc : '未填写驳回原因' }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="listQuery.cert === '5'"
        prop="usercert"
        align="center"
        label="驳回原因"
      >
        <template
          slot-scope="{ row }"
        >
          {{ (row.usercert && row.usercert.agent_audit_desc) ? row.usercert.agent_audit_desc : '未填写驳回原因' }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="listQuery.cert === 'all' || listQuery.cert === '1' || listQuery.cert === '2' || listQuery.cert === '4' || listQuery.cert === '5'"
        label="操作"
        align="center"
        width="200"
      >
        <template
          slot-scope="{ row }"
        >
          <el-button
            v-if="(listQuery.cert === 'all' && row.cert_status !== 4) || listQuery.cert === '1' || listQuery.cert === '2'"
            v-permit="0"
            :roles-permit="roles"
            type="text"
            :disabled="row.cert_status !== 1"
            @click="handleToExamine(row, 1)"
          >
            邀请人审核
          </el-button>
          <!-- 邀请人再次审核 -->
          <el-button
            v-if="listQuery.cert === '4' || (row.cert_status === 4 && listQuery.cert === 'all')"
            v-permit="2"
            :roles-permit="roles"
            type="text"
            style="margin-left:0"
            @click="handleToExamine(row, 3)"
          >
            再次审核
          </el-button>
          <el-button
            v-if="(listQuery.cert === 'all' && row.cert_status !== 5) || listQuery.cert === '1' || listQuery.cert === '2'"
            v-permit="1"
            :roles-permit="roles"
            type="text"
            style="margin-left:0"
            :disabled="row.cert_status !== 2"
            @click="handleToExamine(row, 2)"
          >
            上级审核
          </el-button>
          <!-- 上级再次审核 -->
          <el-button
            v-if="listQuery.cert === '5' || (row.cert_status === 5 && listQuery.cert === 'all')"
            v-permit="3"
            :roles-permit="roles"
            type="text"
            style="margin-left:0"
            @click="handleToExamine(row, 4)"
          >
            再次审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      :total="tableTotal"
      :limit="listQuery.page_size"
      :page="listQuery.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <!-- 审核 -->
    <el-dialog
      :title="setVisibleExamineType()"
      :visible.sync="visible.examine"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="authForm"
        :model="authForm"
        :rules="authRules"
        label-width="100px"
      >
        <el-form-item label="等级认证:" prop="status">
          <el-radio-group v-model="authForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="authForm.status === 1 && (visible.type === 1 || visible.type === 3)"
          label="确认等级:"
          prop="level"
        >
          <el-radio-group v-model="authForm.level">
            <el-radio :label="3">代理公司</el-radio>
            <el-radio :label="2">销售经理</el-radio>
            <el-radio :label="1">销售主管</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="authForm.status === 2"
          label="备注:"
          prop="remark"
        >
          <el-input
            v-model="authForm.remark"
            type="textarea"
            :rows="2"
            placeholder="认证备注"
          />
          <i class="el-icon-warning">驳回时备注必填</i>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="handleDiaAuthClose"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleSubmitAuth"
          >
            确认
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看销售详情 -->
    <el-drawer
      :title="`${memberInfo.realname} - ${levelStatus(memberInfo.level).name}`"
      :visible.sync="visible.memberInfo"
      direction="rtl"
      size="35%"
    >
      <MemberInfo :info="memberInfo" :team-type="false" @getOtherInfo="getOtherInfo" />
    </el-drawer>
  </div>
</template>

<script>
// api
import {
  getList,
  setExamine,
  recomAgainExamine,
  agentAgainExamine
} from '@/api/team/examine'
// 获取上级销售或邀请人信息
import {
  getOtherInfo
} from '@/api/team/common'
// 显示函数
import {
  certStatus,
  levelStatus
} from '@/filters/common'
// 组件
import MemberInfo from './components/MemberInfo'
export default {
  components: {
    MemberInfo
  },
  data() {
    // 驳回时原因必填
    const checkIsNo = (rule, value, callback) => {
      if (this.authForm.status === 2) {
        if (value === '') {
          callback(new Error('驳回时请填写驳回原因'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 通过后显示等级
    const checkOnByLevel = (rule, value, callback) => {
      if (this.authForm.status === 1) {
        if (value === '') {
          callback(new Error('请确认代理级别'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const roles = this.$route.meta.buttonAuthList ? this.$route.meta.buttonAuthList : []
    return {
      roles,
      listQuery: {
        cert: 'all',
        search_name: '',
        page_index: 1,
        page_size: 20
      },
      table: [],
      tableTotal: 0,
      authForm: {
        level: '',
        status: '',
        remark: '',
        type: '',
        id: ''
      },
      authRules: {
        level: [
          { validator: checkOnByLevel, trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请确认认证状态', trigger: 'change' }
        ],
        remark: [
          { validator: checkIsNo, trigger: 'blur' }
        ]
      },
      visible: {
        examine: false,
        type: 1,
        memberInfo: false
      },
      memberInfo: {},
      loadingFull: false
    }
  },
  watch: {
    'listQuery.cert'() {
      this.listQuery.page_index = 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 选项卡切换
    handleTagToggle(tab) {
      this.listQuery.cert = tab.name
      this.getList()
    },
    // 获取列表
    async getList() {
      this.loadingFull = true
      try {
        const res = await getList(this.listQuery)
        const { message, code } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.tableTotal = total
          this.table = list
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取代理授权失败:${e}`)
      }
      this.loadingFull = false
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.listQuery.page_size = limit
      this.listQuery.page_index = page
      this.getList()
    },
    certStatus(row) {
      const { cert_status } = row
      return certStatus(cert_status)
    },
    // 关闭认证
    handleDiaAuthClose() {
      this.$refs.authForm.resetFields()
      this.visible.examine = false
    },
    // 审核
    handleToExamine(row, type) {
      const { id, level } = row
      this.authForm.level = level
      this.authForm.type = type
      this.authForm.id = id
      this.visible.type = type
      this.visible.examine = true
    },
    // 提交认证
    handleSubmitAuth() {
      this.$refs.authForm.validate((valid) => {
        if (valid) {
          const { level, status, type, id, remark } = this.authForm
          if (this.visible.type === 3) {
            this.recomAgainExamine({
              id,
              type: status,
              level,
              desc: String(status) === '1' ? '' : remark
            })
          } else if (this.visible.type === 4) {
            this.agentAgainExamine({
              id,
              type: status,
              desc: String(status) === '1' ? '' : remark
            })
          } else {
            if (status === 1) {
              this.setExamine({
                level,
                status,
                remark: '',
                type,
                id
              })
            } else {
              this.setExamine(this.authForm)
            }
          }
        } else {
          return false
        }
      })
    },
    // 设置审核
    async setExamine(data) {
      const res = await setExamine(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleDiaAuthClose()
          this.authForm = {
            level: '',
            status: '',
            remark: '',
            type: '',
            id: ''
          }
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`代理审核失败:${e}`)
      }
    },
    // 销售级别
    levelStatus(level) {
      return levelStatus(level)
    },
    // 查看销售详情
    handleSeeMemberInfo(row) {
      this.memberInfo = row
      this.visible.memberInfo = true
    },
    // 获取上级销售或邀请人信息
    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
    },
    // 邀请人再次审核
    async recomAgainExamine(data) {
      try {
        const res = await recomAgainExamine(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleDiaAuthClose()
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`邀请人再次审核失败: ${e}`)
      }
    },
    // 上级再次审核
    async agentAgainExamine(data) {
      try {
        const res = await agentAgainExamine(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleDiaAuthClose()
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`上级再次审核失败: ${e}`)
      }
    },
    // 审核类型
    setVisibleExamineType() {
      let title
      const { type } = this.visible
      switch (type) {
        case 1:
        case '1':
          title = '邀请人审核'
          break
        case 2:
        case '2':
          title = '上级审核'
          break
        case 3:
        case '3':
          title = '邀请人再次审核'
          break
        case 4:
        case '4':
          title = '上级再次审核'
          break
      }
      return title
    }
  }
}
</script>
