<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.mobile" clearable class="filter-item" size="mini" style="width: 200px;" placeholder="请输入引荐人手机号" />
      <el-select v-model="listQuery.type" clearable style="width: 200px" size="mini" class="filter-item" placeholder="请选择引荐人类型">
        <el-option label="公司员工" value="0" />
        <el-option label="公司BD" value="1" />
        <el-option label="一级引荐人" value="2" />
        <el-option label="其他引荐人" value="3" />
      </el-select>
      <el-button v-permission="['GET /admin/referee/list']" class="filter-item" type="primary" size="mini" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/referee/header']" class="filter-item" type="warning" size="mini" icon="el-icon-plus" @click="handleCreateHeader">大团长加入</el-button>
      <el-button v-permission="['POST /admin/referee/create']" class="filter-item" type="success" size="mini" icon="el-icon-plus" @click="handleCreate">小团长加入</el-button>

    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <!-- <el-table-column align="center" label="引荐人id" prop="refereeId" sortable /> -->

      <el-table-column align="center" label="名称" prop="refereeName" />
      <el-table-column align="center" label="联系方式" prop="refereeMobile" />

      <el-table-column align="center" label="类型" prop="refereeType">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.refereeType|filerType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="等级" prop="refereeLevel">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.refereeLevel==1?"V1":"V2" }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否实名" prop="refereeNid">
        <template slot-scope="scope">
          <el-tag type="primary">{{ scope.row.refereeNid?'是':'否' }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="引荐码" prop="refereeCode" /> -->

      <el-table-column align="center" label="下级直客数" prop="customers" />
      <el-table-column align="center" label="下级引荐人数" prop="referee" />
      <el-table-column align="center" label="订单数" prop="orders" />
      <el-table-column align="center" label="销售金额" prop="amount" />
      <el-table-column align="center" label="累计佣金" prop="commissionTotal" />
      <el-table-column align="center" label="冻结佣金" prop="commissionFrozen" />
      <el-table-column align="center" label="已提现" prop="commissionCashout" />
      <el-table-column align="center" label="提现审核中" prop="commissionChecking" />
      <el-table-column align="center" label="状态" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted?'danger':''">{{scope.row.deleted?'冻结':'正常'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="加入时间" prop="joinTime" />

      <el-table-column align="center" label="操作" width="130" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/referee/detail']" type="text" size="mini" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button v-if="!scope.row.deleted" v-permission="['POST /admin/referee/delete']" style="color:red" type="text" icon="el-icon-close" size="mini" @click="handleDelete(scope.row)">冻结</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 小团长添加 -->
    <el-dialog title="小团长添加" :visible.sync="refereeFormDialogVisible" width="600px">
      <el-form ref="refereeForm" :rules="rules" :model="refereeForm" status-icon label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="小团长" prop="name">
          <el-input v-model="refereeForm.name" oninput="if(value.length > 20) value = value.slice(0, 20)" placeholder="请输入小团长名称" />
        </el-form-item>

        <el-form-item label="小团长联系方式" prop="mobile">
          <el-input v-model="refereeForm.mobile" oninput="if(value.length > 11) value = value.slice(0, 11)" placeholder="请输入小团长联系方式" type="number" />
        </el-form-item>

        <el-form-item label="大团长" prop="rid">
          <el-select v-model="refereeForm.rid" style="width: 100%" class="filter-item" placeholder="请选择大团长" filterable="">
            <el-option v-for="item in roots" :key="item.refereeId" :label="item.refereeName" :value="item.refereeId" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属城市" prop="cityId">
          <el-select v-model="refereeForm.cityId" style="width: 100%" class="filter-item" placeholder="请选择所属城市">
            <el-option v-for="item in city" :key="item.id" :label="item.cityName" :value="item.id" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refereeFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="joinReferee">确定</el-button>
      </div>
    </el-dialog>

    <!-- 大团长添加 -->
    <el-dialog title="大团长添加" :visible.sync="refereeHeaderFormDialogVisible" width="600px">
      <el-form ref="headerForm" :rules="rules" :model="headerForm" status-icon label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="大团长" prop="name">
          <el-input v-model="headerForm.name" oninput="if(value.length > 20) value = value.slice(0, 20)" placeholder="请输入大团长名称" />
        </el-form-item>

        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="headerForm.mobile" oninput="if(value.length > 11) value = value.slice(0, 11)" placeholder="请输入大团长联系方式" type="number" />
        </el-form-item>

        <el-form-item label="所属城市" prop="cityId">
          <el-select v-model="headerForm.cityId" style="width: 100%" class="filter-item" placeholder="请选择所属城市">
            <el-option v-for="item in city" :key="item.id" :label="item.cityName" :value="item.id" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refereeHeaderFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="joinHeader">确定</el-button>
      </div>
    </el-dialog>

    <!-- 引荐人详情对话框 -->
    <el-dialog :visible.sync="refereeDialogVisible" title="引荐人详情" width="920px">
      <div class="operate-container">
        <i class="el-icon-info color-danger" style="margin-left: 20px" />
        等级：<span class="color-danger">V{{referee.refereeLevel }} </span>
        上一级姓名：<span class="color-danger">{{referee.parent?referee.parent.refereeName:'无' }} </span>
        联系方式：<span class="color-danger">{{ referee.parent?referee.parent.refereeMobile:'无'}}</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="4" class="table-cell-title">名称</el-col>
          <el-col :span="4" class="table-cell-title">身份证</el-col>
          <el-col :span="4" class="table-cell-title">联系电话</el-col>
          <el-col :span="4" class="table-cell-title">发展团长</el-col>
          <el-col :span="4" class="table-cell-title">发展客户</el-col>
          <el-col :span="4" class="table-cell-title">加入时间</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell">{{referee.refereeName}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.refereeNid}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.refereeMobile}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.referee}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.customers}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.joinTime}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell-title">累计销售金额</el-col>
          <el-col :span="4" class="table-cell-title">累计佣金</el-col>
          <el-col :span="4" class="table-cell-title">已提现</el-col>
          <el-col :span="4" class="table-cell-title">可提现</el-col>
          <el-col :span="4" class="table-cell-title">审核中</el-col>
          <el-col :span="4" class="table-cell-title">待生效</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell">{{referee.amount}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.commissionTotal}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.commissionCashout}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.commissionBlance}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.commissionChecking}}</el-col>
          <el-col :span="4" class="table-cell">{{referee.commissionFrozen}}</el-col>
        </el-row>
      </div>

      <el-tabs v-model="listDetailQuery.tab" @tab-click="handleTabClick">
        <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-tabs>
      <!-- 团长 -->
      <el-table v-loading="listLoading" v-show="listDetailQuery.tab=='0'" :data="refereeDetail" element-loading-text="正在查询中。。。" fit highlight-current-row>
        <el-table-column align="center" label="团长姓名" prop="refereeName" />
        <el-table-column align="center" label="联系方式" prop="refereeMobile" />
        <el-table-column align="center" label="下级直客数" prop="customers" />
        <el-table-column align="center" label="引荐人数" prop="referee" />
        <el-table-column align="center" label="订单数" prop="orders" />
        <el-table-column align="center" label="销售金额" prop="amount" />
        <el-table-column align="center" label="累计佣金" prop="commissionTotal" />
        <el-table-column align="center" label="冻结佣金" prop="commissionFrozen" />
        <el-table-column align="center" label="已提现" prop="commissionCashout" />
        <el-table-column align="center" label="审核中" prop="commissionChecking" />
        <el-table-column align="center" label="加入时间" prop="joinTime" />
      </el-table>

      <!-- 团员=客户 -->
      <el-table v-loading="listLoading" v-show="listDetailQuery.tab=='1'" :data="refereeDetail" element-loading-text="正在查询中。。。" fit highlight-current-row>
        <el-table-column align="center" label="姓名" prop="refereeName" />
        <el-table-column align="center" label="联系方式" prop="refereeMobile" />
        <el-table-column align="center" label="订单数" prop="orders" />
        <el-table-column align="center" label="销售金额" prop="amount" />
        <el-table-column align="center" label="加入时间" width="180" prop="joinTime" />
      </el-table>
      <!-- 分佣明细 -->
      <el-table v-loading="listLoading" style="width:100%" v-show="listDetailQuery.tab=='2'" :data="refereeDetail" element-loading-text="正在查询中。。。" fit highlight-current-row>
        <el-table-column align="center" label="订单编号" prop="orderSn" />
        <el-table-column align="center" label="分佣类型" prop="commissionType">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.commissionType==0?"佣金":scope.row.commissionType==1?"服务费":"佣金+服务费" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="佣金比例" prop="commissionPer" />
        <el-table-column align="center" label="预计佣金" prop="commissionEstimate" />
        <el-table-column align="center" label="实际已分佣" prop="commissionReal" />
        <el-table-column align="center" label="状态" prop="commissionStatus">
          <template slot-scope="scope">
            <el-tag :type="scope.row.commissionStatus==2?'warning':'info'">
              {{ scope.row.commissionStatus==0?"分佣中":scope.row.commissionStatus==1?"已完成":"退单中止" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="分佣时间" width="180" prop="updateTime" />
      </el-table>

      <!-- 提现记录 -->
      <el-table v-loading="listLoading" v-show="listDetailQuery.tab=='3'" :data="refereeDetail" element-loading-text="正在查询中。。。" highlight-current-row>
        <el-table-column align="center" label="申请时间" width="180" prop="applyTime" />
        <el-table-column align="center" label="提现金额" prop="applyAmount" />
        <el-table-column align="center" label="预计上税" prop="applyTax" />
        <el-table-column align="center" label="提现状态" prop="applyStatus" />
        <el-table-column align="center" label="审核时间" width="180" prop="confirmTime" />
        <el-table-column align="center" label="审核备注" prop="confirm_memo" />
        <el-table-column align="center" label="打款时间" prop="payTime" />
        <el-table-column align="center" label="付款编号" prop="payNo" />
      </el-table>

      <pagination v-show="refereeeDetailTotal>0&&listDetailQuery.tab=='3'" :total="refereeeDetailTotal" :page.sync="listDetailQuery.page" :limit.sync="listDetailQuery.limit" @pagination="getDetail" />

      <!-- 二维码 -->
      <el-row v-show="listDetailQuery.tab=='4'">
        <el-col :span="12" class="table-cell" style="text-align:center;padding-top: 5px;height:80px;display: flex; flex-direction: column;align-items: center;">
          <el-image :preview-src-list="[refereePoster]" :lazy="false" :src="refereePoster" style="width:50px;height:60px"></el-image>
          <span>发展小团长二维码</span>
        </el-col>
        <!-- <el-col :span="12" class="table-cell" style="text-align:center;padding-top: 5px;height:80px;display: flex; flex-direction: column;align-items: center;">
          <el-image :preview-src-list="[refereeMPoster]" :lazy="false" :src="refereeMPoster" style="width:50px;height:60px"></el-image>
          <span>送会员二维码</span>
        </el-col> -->
        <el-col v-show="refereeMPoster==null||refereePoster==null">
          <el-button type="text" @click="handlePoster(referee)">生成二维码</el-button>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="refereeDialogVisible = false">确 认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listReferee,
  refereeDetail,
  createReferee,
  listRoots,
  createPoster,
  deleteReferee,createHeader
} from "@/api/referee";
import { getUserCity } from "@/api/city";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "Shop",
  components: { Pagination },
  filters: {
    filerType(value) {
      if (value == 0) return "公司员工";
      if (value == 1) return "大团长";
      if (value == 2) return "一级团长";
      if (value == 3) return "其他团长";
      if (value == 4) return "普通客户";
      return "无法判定";
    },
  },
  data() {
    const callMobileValidate = (rule, value, callback) => {
      if (
        value == null ||        value.length < 10
      ) {
        callback(new Error("请输入正确联系方式"));
      } else {
        callback();
      }
    };
    return {
      city: [],
      roots: [],
      total: 0,
      list: null,
      listLoading: true,
      listQuery: {
        mobile: undefined,
        type: undefined,
        page: 1,
        limit: 20,
        sort: "join_time",
        order: "desc",
      },
      refereePoster: null,
      refereeMPoster: null,
      refereeDialogVisible: false,
      referee: {},
      refereeDetail: [],
      refereeeDetailTotal: 0,
      listDetailQuery: {
        refereeId: undefined,
        tab: "0",
        page: 1,
        limit: 20,
        sort: "join_time",
        order: "desc",
      },
      refereeFormDialogVisible: false,
      refereeForm: {
        rid: 0,
      },
      refereeHeaderFormDialogVisible: false,
      headerForm: {
        mobile: "",
        name: "",
        type: "",
        cityId: "",
      },
      rules: {
        rid: [{ required: true, message: "推荐人不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "大团长类型不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "小团长名称不能为空", trigger: "blur" },
        ],
        mobile: [
          {
            validator: callMobileValidate,
            required: true,
            message: "团长联系方式不能为空",
            trigger: "blur",
          },
        ],
        cityId: [
          { required: true, message: "所属城市不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getUserCity();
  },
  methods: {
    getUserCity() {
      getUserCity().then((res) => {
        this.city = res.data.data;
      });
    },
    getList() {
      this.listLoading = true;
      listReferee(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleCreateHeader() {
      //大团长加入
      this.refereeHeaderFormDialogVisible = true;
      this.headerForm = {};
    },
    joinHeader() {
      this.$refs["headerForm"].validate((valid) => {
        if (valid) {
          if (this.headerForm.mobile.length != 11) {
            this.$notify.error({
              title: "失败",
              message: "手机号不正确",
            });
            return;
          }
          this.$confirm("确定新增大团长?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => { 
            createHeader(this.headerForm)
              .then((res) => {
                this.refereeHeaderFormDialogVisible = false;
                this.getList();
              })
              .catch((res) => { 
                 this.$notify.error({
                  title: '失败',
                  message: res.data.errmsg
                })
              });
          });
        }
      });
    },
    handleCreate() {
      this.refereeForm = {
        rid: "",
        name: "",
        mobile: "",
      };
      this.refereeFormDialogVisible = true;
      if (this.roots.length == 0) {
        listRoots().then((res) => {
          this.roots = res.data.data;
        });
      }
    },
    handlePoster(row) {
      createPoster({ cusId: row.refereeId }).then((res) => {
        this.refereePoster = res.data.data.poster;
        this.refereeMPoster = res.data.data.mPoster;
        this.$forceUpdate();
      });
    },
    joinReferee() {
      this.$refs["refereeForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确定设置为机构引荐人?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            createReferee(this.refereeForm)
              .then((res) => {
                this.refereeFormDialogVisible = false;
                this.getList();
              })
              .catch((res) => { 
                 this.$notify.error({
                  title: '失败',
                  message: res.data.errmsg
                })
              });
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        "确定冻结此引荐人【" +
          row.refereeName +
          "】?冻结后不影响提现，但是无法新增分佣",
        "提示",
        {
          confirmButtonText: "冻结",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        deleteReferee({ refereeId: row.refereeId })
          .then((res) => {
            this.getList();
          })
          .catch((res) => {});
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleTabClick() {
      console.info(this.listDetailQuery.tab);
      if (this.listDetailQuery.tab == "4") return;
      this.getDetail();
    },
    getDetail() {
      refereeDetail(this.listDetailQuery)
        .then((response) => {
          console.info(response.data);
          this.refereeDetail = response.data.data.list;
          this.refereeeDetailTotal = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.refereeDetail = [];
          this.refereeeDetailTotal = 0;
          this.listLoading = false;
        });
    },
    handleDetail(row) {
      this.listDetailQuery = {
        refereeId: row.refereeId,
        tab: "0",
        page: 1,
        limit: 20,
        sort: "join_time",
        order: "desc",
      };
      this.refereePoster = null;
      this.refereeMPoster = null;
      this.handleTabClick();
      this.referee = row;
      this.refereeDialogVisible = true;
    },
  },
};
</script>

<style>
.detail-container {
  width: 80%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
  font-size: 18px;
}

.operate-button-container {
  float: right;
  margin-right: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 20px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  white-space: pre-wrap;
  /* overflow: hidden; */
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
.el-table th.gutter {
  display: table-cell !important;
}
.color-danger {
  color: #f56c6c;
  font-size: 18px;
}
.el-dialog .el-cascader {
  width: 400px;
}
.fixed-width .el-button--mini {
  width: auto;
  min-width: 40px;
  padding: 0px;
}
</style>
