<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <template>
      <el-tabs v-model="listQuery.level" @tab-click="handleTabToggle">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="代理公司" name="3" />
        <el-tab-pane label="销售经理" name="2" />
        <el-tab-pane label="销售主管" name="1" />
        <el-tab-pane label="已删除" name="4" />
      </el-tabs>
    </template>

    <div class="filter-container">
      <el-input v-model="listQuery.search_name" placeholder="姓名/昵称/手机号/身份证号" class="filter-item filter-input" @keydown.native.enter="handleSearch" />
      <el-input v-model="listQuery.recom_name" placeholder="邀请人姓名/手机号/昵称/身份证号" class="filter-item filter-input" @keydown.native.enter="handleSearch" />
      <el-input v-model="listQuery.agent_name" placeholder="上级姓名/手机号/昵称/身份证号" class="filter-item filter-input" @keydown.native.enter="handleSearch" />
      <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">搜索</el-button>
      <el-button type="primary" icon="el-icon-edit" class="filter-item" @click="handleAddMember">添加销售</el-button>
      <el-button type="primary" :loading="downloadLoading" icon="el-icon-document" class="filter-item" @click="exportMember">导出</el-button>
    </div>

    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="headimgurl"
        label="头像"
        align="center"
        width="60"
      >
        <template slot-scope="{ row }">
          <el-image :src="row.headimgurl" fit="contain" class="hoverImg" />
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" @click="getOtherInfo(row.id)">{{ 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="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="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="cert_status"
        align="center"
        label="认证状态"
        width="100"
      >
        <template
          slot-scope="{ row }"
        >
          {{ certStatus(row) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        align="center"
        label="账户状态"
        width="80"
      >
        <template
          slot-scope="{ row }"
        >
          <el-tag
            :type="row.delete === 1 ? 'danger' : (row.status === 0 ? 'success' : 'warning')"
            size="mini"
          >
            {{ row.delete === 1 ? '已删除' : (row.status === 0 ? '正常' : '已禁用') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        v-if="listQuery.level !== '4'"
        label="操作"
        width="320"
      >
        <template
          slot-scope="scope"
        >
          <el-popover
            :ref="`popover_tel_${scope.$index}`"
            placement="right"
            width="300"
            @after-leave="edit.tel = ''"
          >
            <el-input v-model="edit.tel" placeholder="修改的手机号" size="mini" minlength="11" maxlength="11" style="width: 200px" />
            <el-button
              type="primary"
              size="mini"
              @click="handleEditTel(scope)"
            >
              修改
            </el-button>
          </el-popover>
          <!-- <el-popover
            :ref="`popover_share_${scope.$index}`"
            placement="right"
            width="300"
            @after-leave="edit.share = ''"
          >
            <el-input
              v-model="edit.share"
              placeholder="邀请人手机号"
              size="mini"
              minlength="11"
              maxlength="11"
              style="width: 200px"
            />
            <el-button
              type="primary"
              size="mini"
              @click="handleEditShare(scope)"
            >
              修改
            </el-button>
            <el-button
              slot="reference"
              type="text"
              :disabled="scope.row.level === 0 || scope.row.delete === 1"
              @click="handleChangeShare"
            >
              变更邀请人
            </el-button>
          </el-popover> -->
          <el-button
            type="text"
            :disabled="scope.row.level === 0 || scope.row.delete === 1"
            @click="handleChangeShare(scope.row)"
          >
            变更邀请人
          </el-button>
          <div
            v-permit="4"
            :roles-permit="roles"
            style="display:inline-block;"
          >
            <el-button
              v-if="scope.row.level !== 3"
              type="text"
              style="margin-left:0px"
              :disabled="scope.row.level === 0 || scope.row.delete === 1"
              @click="handleEditLevel(scope.row, scope.row.level+1)"
            >
              升级
            </el-button>
            <span
              v-if="scope.row.level === 2"
            >/</span>
            <el-button
              v-if="scope.row.level !== 1"
              type="text"
              style="margin-left:0px"
              :disabled="scope.row.level === 0 || scope.row.delete === 1"
              @click="handleEditLevel(scope.row, scope.row.level-1)"
            >
              降级
            </el-button>
          </div>
          <el-button
            v-permit="3"
            :roles-permit="roles"
            type="text"
            style="margin-left:0px"
            :disabled="scope.row.level === 0 || scope.row.delete === 1"
            @click="changeStatus(scope.row.id)"
          >
            {{ scope.row.status === 0 ? '禁用' : '启用' }}账号
          </el-button>
          <el-button
            v-permit="2"
            :roles-permit="roles"
            type="text"
            style="margin-left:0px"
            :disabled="scope.row.level === 0 || scope.row.delete === 1"
            @click="handleDelete(scope.row)"
          >
            删除代理
          </el-button>
          <el-button
            v-if="scope.row.level === 3 && listQuery.level === '3'"
            type="text"
            style="margin-left:0px"
            :disabled="scope.row.level === 0"
            @click="getStock(scope.row)"
          >
            查看库存
          </el-button>
          <el-button v-if="scope.row.level === 3 && listQuery.level === '3'" type="text" style="margin-left:0px" @click="handleCrownCloseWar(scope.row)">
            选择战区
          </el-button>
          <el-popover :ref="`popover_pwd_${scope.$index}`" placement="right" width="300" @after-leave="edit.pwd = ''">
            <el-input v-model="edit.pwd" placeholder="新的密码" size="mini" minlength="11" maxlength="11" style="width: 200px" />
            <el-button type="primary" size="mini" @click="handleEditPwd(scope)">修改</el-button>
            <el-button slot="reference" v-permit="0" :roles-permit="roles" type="text" :disabled="scope.row.delete === 1">修改密码</el-button>
          </el-popover>
          <el-button v-permit="1" :roles-permit="roles" type="text" style="margin-left:0px" :disabled="scope.row.delete === 1" @click="handleResetPwd(scope.row)">重置密码</el-button>
          <el-button type="text" style="margin-left:0px" @click="handleUpdateInfo(scope.row)">修改信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="batch-container">
      <!-- 分页 -->
      <pagination
        :total="tableTotal"
        :limit="listQuery.page_size"
        :page="listQuery.page_index"
        style="margin-top:0"
        @pagination="changePagination"
        @update:limit="changePagination"
      />
    </div>

    <el-dialog :title="visible.type === 'add' ? '添加销售' : '修改销售'" top="50px" :visible.sync="visible.member" :before-close="handleMemberClose">
      <el-form ref="memberForm" :model="memberForm" :rules="memberRules" label-width="120px">
        <el-form-item label="微信昵称:" prop="nickname">
          <el-input v-model="memberForm.nickname" placeholder="微信昵称" />
        </el-form-item>
        <el-form-item label="真实姓名:" prop="realname">
          <el-input v-model="memberForm.realname" placeholder="真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号:">
          <el-input v-model="memberForm.cre_num" minlength="15" maxlength="18" placeholder="身份证号" />
        </el-form-item>
        <el-form-item label="电话号:" prop="mobile">
          <el-input v-model="memberForm.mobile" minlength="11" maxlength="11" placeholder="电话号" show-word-limit />
        </el-form-item>
        <el-form-item label="代理等级:" prop="level">
          <el-radio-group v-model="memberForm.level">
            <el-radio :label="1">销售主管</el-radio>
            <el-radio :label="2">销售经理</el-radio>
            <el-radio :label="3">代理公司</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邀请人手机号:" prop="share">
          <el-input v-model="memberForm.share" minlength="11" maxlength="11" placeholder="邀请人手机号" show-word-limit />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="handleMemberClose">取消</el-button>
          <el-button type="primary" size="mini" @click="handleSubmitAddEdit">{{ visible.type === 'add' ? '添加' : '修改' }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看库存 -->
    <el-drawer :title="`${stockInfo.user.nickname}的商品库存`" :visible.sync="visible.stock" direction="rtl" size="40%">
      <el-form label-width="0">
        <el-form-item style="padding: 0 20px">
          <el-table :data="stockInfo.goods" border>
            <el-table-column prop="img_url" label="图片" align="center">
              <template slot-scope="{ row }">
                <el-image style="width: 60px; height: 60px" :src="row.img_url" fit="cover" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品" align="center" />
            <el-table-column prop="account" label="库存" align="center" />
          </el-table>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 查看代理详情 -->
    <el-drawer :title="`${memberInfo.realname} - ${levelStatus(memberInfo.level).name}`" :visible.sync="visible.memberInfo" direction="rtl" size="35%">
      <MemberInfo :info="memberInfo" :team-type="true" @getOtherInfo="getOtherInfo" />
    </el-drawer>
    <!-- 代理公司选择战区 -->
    <el-dialog title="选择战区" :visible.sync="visible.war" :before-close="handleCloseWar">
      <el-form label-width="100px">
        <el-form-item label="代理公司:">{{ selectedCrown.nickname }}</el-form-item>
        <el-form-item label="战区:">
          <el-select ref="crownWarSelect" v-model="crownWarId" placeholder="请选择战区">
            <el-option v-for="item in warList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSureCrownWar">确认</el-button>
          <el-button size="small" @click="handleCloseWar">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除代理 -->
    <el-dialog title="删除代理" :visible.sync="visible.delete" :close-on-click-modal="false" :show-close="false" width="520px" class="dialog_delete">
      <span class="desc">请填写删除代理的原因:</span>
      <el-input v-model="deleteMemberInfo.remark" type="textarea" class="textarea_h" maxlength="250" show-word-limit />
      <el-button @click="resetDialogDelete">取消</el-button>
      <el-button type="primary" @click="submitDelete">确定</el-button>
    </el-dialog>
    <!-- 变更邀请人 -->
    <el-dialog title="变更邀请人" :visible.sync="visible.share" :close-on-click-modal="false" :show-close="false" width="520px" class="dialog_delete">
      <span class="desc">请输入要变更的邀请人手机号:</span>
      <el-input v-model="changeShare.mobile" class="desc" type="text" maxlength="11" show-word-limit />
      <span class="desc">请填写变更邀请人的原因:</span>
      <el-input v-model="changeShare.remark" type="textarea" class="textarea_h" maxlength="250" show-word-limit />
      <el-button @click="resetDialogShare">取消</el-button>
      <el-button type="primary" @click="handleEditShare">确定</el-button>
    </el-dialog>
    <!-- 删除代理 -->
    <el-dialog title="修改代理信息" :visible.sync="visible.updateInfo" :close-on-click-modal="false" :show-close="false" width="520px" class="dialog_delete">
      <el-form>
        <el-form-item label="用户昵称">
          <el-input v-model="updateInfoData.nickname" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="updateInfoData.realname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="updateInfoData.mobile" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="updateInfoData.cre_num" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible.updateInfo = false; updateInfoData = {}">取消</el-button>
        <el-button type="primary" @click="updateInfo">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// api
import {
  getList,
  editTel,
  addMember,
  deleteMember,
  changeStatus,
  editShare,
  editLevel,
  getStock,
  getWarList,
  crownWar,
  setPwd,
  exportMember,
  updateInfo
} from '@/api/team/member'
// 获取上级销售或邀请人信息
import {
  getOtherInfo
} from '@/api/team/common'
// 验证
import {
  validateMobile
} from '@/filters/validate'
// 公共方法
import {
  certStatus,
  levelStatus
} from '@/filters/common'
// 组件
import MemberInfo from './components/MemberInfo'
// 导出格式化时间
import { parseTime } from '@/utils'
export default {
  components: {
    MemberInfo
  },
  data() {
    // 获取页面的按钮操作权限
    const roles = this.$route.meta.buttonAuthList ? this.$route.meta.buttonAuthList : []
    return {
      table: [],
      tableTotal: 0,
      listQuery: {
        level: 'all',
        page_index: 1,
        page_size: 20,
        search_name: '',
        recom_name: '',
        agent_name: ''
      },
      edit: {
        tel: '',
        share: '',
        pwd: ''
      },
      memberForm: {
        nickname: '',
        realname: '',
        cre_num: '',
        mobile: '',
        level: '',
        share: ''
      },
      memberRules: {
        nickname: [
          { required: true, message: '请输入销售微信昵称', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入销售真实姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择销售级别', trigger: 'change' }
        ],
        share: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ]
      },
      visible: {
        stock: false,
        member: false,
        type: false,
        memberInfo: false,
        war: false,
        delete: false,
        share: false,
        updateInfo: false
      },
      stockInfo: {
        user: {},
        goods: []
      },
      memberInfo: {
        realname: '',
        level: ''
      },
      roles,
      loadingFull: false,
      warList: [],
      crownWarId: '',
      selectedCrown: {},
      downloadLoading: false,
      changeShare: {
        id: '',
        mobile: '',
        remark: ''
      },
      updateInfoData: {},
      deleteMemberInfo: {
        id: '',
        remark: ''
      }
    }
  },
  created() {
    this.getList()
    this.getWarList()
  },
  methods: {
    // 修改用户信息
    updateInfo() {
      if (this.updateInfoData.nickname.trim() && this.updateInfoData.realname.trim() && this.updateInfoData.mobile.trim().length === 11) {
        this.$request(updateInfo({
          id: this.updateInfoData.id,
          mobile: this.updateInfoData.mobile.trim(),
          nickname: this.updateInfoData.nickname.trim(),
          realname: this.updateInfoData.realname.trim(),
          cre_num: this.updateInfoData.cre_num.trim()
        }), data => {
          this.table.find(e => e.id === this.updateInfoData.id).nickname = this.updateInfoData.nickname.trim()
          this.table.find(e => e.id === this.updateInfoData.id).realname = this.updateInfoData.realname.trim()
          this.table.find(e => e.id === this.updateInfoData.id).mobile = this.updateInfoData.mobile.trim()
          this.table.find(e => e.id === this.updateInfoData.id).cre_num = this.updateInfoData.cre_num.trim()
          this.updateInfoData = {}
          this.visible.updateInfo = false
          this.$message.success('修改成功')
        })
      } else {
        this.$message.error('用户填写不完整')
      }
    },
    // 点击修改信息
    handleUpdateInfo({ nickname, realname, mobile, cre_num, id }) {
      cre_num ? '' : cre_num = ''
      this.updateInfoData = { nickname, realname, mobile, cre_num, id }
      this.visible.updateInfo = true
    },
    // 获取销售列表
    async getList() {
      this.loadingFull = true
      const res = await getList(this.listQuery)
      try {
        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)
        }
        this.loadingFull = false
      } catch (e) {
        console.log(`获取销售列表失败:${e}`)
        this.loadingFull = false
      }
    },
    // 导航条切换
    handleTabToggle(tab) {
      this.listQuery.level = tab.name
      this.getList()
    },
    // 认证状态显示
    certStatus(row) {
      const { cert_status } = row
      return certStatus(cert_status)
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.listQuery.page_size = limit
      this.listQuery.page_index = page
      this.getList()
    },
    // 修改手机号
    handleEditTel(scope) {
      const { id } = scope.row
      if (!this.edit.tel) {
        this.$message.warning('手机号不能为空')
        return false
      }
      this.editTel({
        id,
        mobile: this.edit.tel
      }, () => {
        this.edit.tel = ''
        scope._self.$refs[`popover_tel_${scope.$index}`].doClose()
      })
    },
    // 修改手机号
    async editTel(data, callback) {
      const res = await editTel(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getList()
          callback()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`修改销售手机号失败:${e}`)
      }
    },
    // 关闭代理弹窗
    handleMemberClose() {
      this.visible.member = false
      this.$refs.memberForm.resetFields()
    },
    // 添加代理
    handleAddMember() {
      this.visible.type = 'add'
      this.visible.member = true
    },
    // 提交添加修改
    handleSubmitAddEdit() {
      this.$refs.memberForm.validate((valid) => {
        if (valid) {
          if (this.visible.type === 'add') {
            this.addMember(this.memberForm)
          } else {
            console.log('edit')
          }
        } else {
          return false
        }
      })
    },
    // 提交添加
    async addMember(data) {
      try {
        const res = await addMember(data)
        const { message, code } = res
        if (code === 200) {
          this.handleMemberClose()
          this.$message.success(message)
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`添加销售失败:${e}`)
      }
    },
    // 删除代理
    handleDelete(row) {
      this.deleteMemberInfo.id = row.id
      this.visible.delete = true
    },
    submitDelete() {
      const { id, remark } = this.deleteMemberInfo
      if (!remark) {
        this.$message.error('请填写删除代理原因')
      } else {
        this.loadingFull = true
        deleteMember({
          id,
          remark
        }).then(res => {
          this.loadingFull = false
          if (res.code === 200) {
            this.resetDialogDelete()
            this.getList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        }).catch(e => {
          this.loadingFull = false
        })
      }
    },
    resetDialogDelete() {
      this.deleteMemberInfo = {
        id: '',
        remark: ''
      }
      this.visible.delete = false
    },
    // 变更邀请人
    handleChangeShare(row) {
      this.changeShare.id = row.id
      this.visible.share = true
    },
    // 禁用启用
    async changeStatus(id) {
      const res = await changeStatus({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`禁用启用销售失败:${e}`)
      }
    },
    // 变更邀请人
    handleEditShare() {
      const { id, mobile, remark } = this.changeShare
      if (!mobile) {
        this.$message.warning('邀请人手机号不能为空')
      } else if (!remark) {
        this.$message.warning('请填写变更邀请人原因')
      } else {
        this.loadingFull = true
        editShare({
          id, mobile, remark
        }).then(res => {
          this.loadingFull = false
          if (res.code === 200) {
            this.resetDialogShare()
            this.getList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        }).catch(e => {
          this.loadingFull = false
        })
      }
    },
    resetDialogShare() {
      this.changeShare = {
        id: '',
        mobile: '',
        remark: ''
      }
      this.visible.share = false
    },
    // 变更销售级别
    handleEditLevel(row, next) {
      const { id, realname } = row
      let msg
      switch (next) {
        case 1:
          msg = '销售主管'
          break
        case 2:
          msg = '销售经理'
          break
        case 3:
          msg = '代理公司'
      }
      this.$confirm(`确认将代理${realname}的等级变更为-${msg}?`, '变更等级确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editLevel({
          id,
          level: next
        })
      })
    },
    // 变更销售级别
    async editLevel(data) {
      const res = await editLevel(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`变更销售级别失败:${e}`)
      }
    },
    // 查看代理公司库存
    async getStock(row) {
      const { id } = row
      this.stockInfo.user = row
      const res = await getStock({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          const { data } = res
          if (data.length < 1) {
            this.$message.warning(`${row.nickname}还没有商品库存`)
          } else {
            this.stockInfo.goods = data
            this.visible.stock = true
          }
        } 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 getWarList() {
      try {
        const res = await getWarList()
        const { code } = res
        if (code === 200) {
          const { data } = res
          this.warList = data
        }
      } catch (e) {
        console.log(`获取战区失败:${e}`)
      }
    },
    // 代理公司选择战区
    async crownWar(data) {
      try {
        const res = await crownWar(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleCloseWar()
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`代理公司选择战区失败: ${e}`)
      }
    },
    // 皇冠选择战区
    handleCrownCloseWar(row) {
      if (this.warList.length < 1) {
        this.$message.error('还没有战区,请前往: 系统设置->战区设置,添加战区')
        return false
      }
      this.crownWarId = row.warea_id ? row.warea_id : ''
      this.visible.war = true
      this.selectedCrown = row
    },
    // 确认
    handleSureCrownWar() {
      if (!this.crownWarId) {
        this.$message.warning('请选择战区')
        this.$refs.crownWarSelect.focus()
        return false
      }
      this.crownWar({
        id: this.selectedCrown.id,
        wid: this.crownWarId
      })
    },
    // 关闭
    handleCloseWar() {
      this.crownWarId = ''
      this.selectedCrown = {}
      this.visible.war = false
    },
    // 修改重置密码
    async setPwd(data, callback) {
      try {
        const res = await setPwd(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          callback ? callback() : null
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`重置/修改密码失败:${e}`)
      }
    },
    // 重置密码
    handleResetPwd(row) {
      const { id, mobile } = row
      this.$confirm(`重置密码将会使用户当前密码失效,将重置为: ${mobile} ,是否确认这样做?`, '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.setPwd({
          type: 1,
          password: mobile,
          id
        })
      })
    },
    // 修改密码
    handleEditPwd(scope) {
      const { id } = scope.row
      if (!this.edit.pwd) {
        this.$message.warning('修改的密码不能为空')
        return false
      }
      this.setPwd({
        type: 2,
        password: this.edit.pwd,
        id
      }, () => {
        this.edit.share = ''
        scope._self.$refs[`popover_pwd_${scope.$index}`].doClose()
      })
    },
    // 导出
    async exportMember() {
      this.loadingFull = true
      try {
        const { search_name, recom_name, agent_name, level } = this.listQuery
        const res = await exportMember({
          search_name,
          level,
          recom_name,
          agent_name
        })
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          if (data.length < 1) {
            this.$message.error('没有数据哦!!!')
            return false
          }
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['昵称', '真实姓名', '电话号码', '身份证号', '代理级别', '授权码', '授权开始时间', '授权结束时间', '邀请码', '认证状态', '账户状态', '上级代理昵称', '上级代理手机号', '邀请人昵称', '邀请人手机号']
            const filterVal = ['nickname', 'realname', 'mobile', 'cre_num', 'level', 'auth_code', 'auth_startime', 'auth_endtime', 'recom_code', 'cert_status', 'status', 'agent_name', 'agent_mobile', 'recom_name', 'recom_mobile']
            data.map((item) => {
              item.agent_name = item.agent && item.agent.nickname ? item.agent.nickname : ''
              item.agent_mobile = item.agent && item.agent.mobile ? item.agent.mobile : ''
              item.recom_name = item.recom && item.recom.nickname ? item.recom.nickname : ''
              item.recom_mobile = item.recom && item.recom.mobile ? item.recom.mobile : ''
              item.level = this.levelStatus(item.level).name
              item.status = item.delete === 1 ? '已删除' : (item.status === 0 ? '正常' : '已禁用')
              item.cert_status = this.certStatus(item)
            })
            const list = data
            const dataVal = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data: dataVal,
              filename: `销售详情`,
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.loadingFull = false
            this.$message.success('导出数据完成')
          })
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`导出销售失败: ${e}`)
        this.loadingFull = false
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 搜藏
    handleSearch() {
      this.listQuery.page_index = 1
      this.getList()
    }
  }
}
</script>
<style lang="scss">
  :focus{
    outline:0;
  }
  .dialog_delete {
    .textarea_h {
      height: 190px;
      margin-bottom: 30px;

      .el-textarea__inner {
        height: 100% !important;
        resize: none;
      }
    }

    .desc {
      display: block;
      margin-bottom: 15px;
    }
  }
</style>
