<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入用户手机号" maxlength="11" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="添加时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="省级合伙人" prop="parentId">
        <el-select v-model="queryParams.parentId" placeholder="请输入" filterable clearable size="small" style="width: 240px">
          <el-option v-for="(v,i) in partnerList" :key="i" :label="v.username" :value="v.partnerId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-back" size="mini" @click="goBack()">返回</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="级别" align="center" prop="partnerType">
        <template slot-scope="{row}">
          <div v-for="(v,i) in partnerTypeList" :key="i" v-if="v.value == row.partnerType">{{v.label}}</div>
        </template>
      </el-table-column>
      <el-table-column label="所在省" align="center" prop="provinceName" />
      <el-table-column label="昵称" prop="userNickName" align="center" />
      <el-table-column label="真是姓名" prop="username" align="center" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="添加时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下级商户" align="center" prop="businessNum">
        <template slot-scope="{row}">
          <span class="activeCls" @click="goShopList(row)"> {{row.businessNum||0}}</span>
        </template>
      </el-table-column>
      <el-table-column label="下级用户" align="center" prop="userNum">
        <template slot-scope="{row}">
          <span class="activeCls" @click="goUserList(row)"> {{row.userNum||0}}</span>
        </template>
      </el-table-column>
      <el-table-column label="获得下级兑换豆" align="center" prop="point">
        <template slot-scope="{row}">
          {{row.point||0}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.status">正常</el-tag>
          <el-tag type="danger" v-if="!row.status">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" @click="setStatus(row)">{{row.status?'禁用':'解除'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改对话框 -->
    <el-drawer :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择用户" prop="nickname">
          <span v-if="form.nickname">{{form.nickname}}</span>
          <el-button class="ml10" v-if="title != '查看'" type="primary" @click="openSelUser()">选择</el-button>
        </el-form-item>
        <el-form-item label="真实姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入真实姓名" maxlength="10" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省级合伙人" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请输入" disabled filterable clearable size="small" style="width: 240px">
            <el-option v-for="(v,i) in partnerList" :key="i" :label="v.username" :value="v.partnerId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属地区" prop="provinces">
          <el-cascader ref="refSubCat" v-model="form.provinces" placeholder="请选择省" :options="areaTrea" :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%"></el-cascader>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <SelUser ref="selUserRef" @result="result" />
  </div>
</template>

<script>
import { cnAreaTree } from "@/api/shop"
import { partnerRelationPage, partnerRelationSetStatus, partnerRelationAdd, partnerRelationList } from "@/api/partner"
import SelUser from "@/components/SelUser/index.vue";
export default {
  components: {
    SelUser
  },
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      daterangeCreateTime1: [],
      // 查询参数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mobile: undefined,
        parentId: undefined
      },
      rules: {
        nickname: [
          { required: true, message: "请选择用户", trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入真是姓名", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        provinces: [
          { required: true, message: "请选择地区", trigger: "blur" },
        ],
      },
      form: {
        nickname: undefined,
        cityName: undefined,
        username: undefined,
        provinces: undefined,
        parentId: undefined
      },
      areaTrea: [],
      partnerList: [],
      partnerTypeList: [
        { value: 1, label: '省级合伙人' },
        { value: 2, label: '城市合伙人' }
      ]
    }
  },
  created () {
    if (this.$route.query.parentId) {
      this.queryParams.parentId = this.$route.query.parentId * 1
    }
    this.getList()
    this.getPartnerList();
    this.getCnAreaTree()
  },
  methods: {
    reset () {
      this.form = {};
      this.resetForm("form");
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    goBack () {
      if (this.$route.query.queryParams) {
        localStorage.setItem('queryParams', this.$route.query.queryParams)
      }
      this.$router.go(-1);
    },
    openSelUser () {
      this.$refs.selUserRef.open()
    },
    result (e) {
      this.form.nickname = e.nickname;
      this.form.userId = e.id;
      this.$forceUpdate()
    },
    goShopList (row) {
      this.$router.push({ path: '/shop/shopList', query: { parentId: row.parentId } })
    },
    goUserList (row) {
      this.$router.push({ path: '/user/user/index', query: { parentId: row.parentId } })
    },
    getCnAreaTree () {
      cnAreaTree().then(res => {
        if (res.data?.children) {
          res.data.children.map(v => {
            v.children.map(v1 => {
              v1.children = null
            })
          })
          this.areaTrea = res.data.children
        }
      })
    },
    // 省市区选择
    handleChange (value) {
      this.form.provinces = value;
      this.form.provinceCode = value[0];
      this.form.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
      this.form.cityCode = value[1];
      this.form.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
      this.form.areaCode = value[2];
      this.form.areaName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.form.parentId = this.$route.query.parentId * 1;
      this.title = "新增城市合伙人";
    },
    goJuniorTeam () {
      this.$router.push({ path: '/partner/juniorTeam' })
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      const ids = row.businessProductId || this.ids;
      let statusText = row.shelvedStatus ? '禁用' : '解除';
      this.$modal.confirm('是否确认' + statusText + '商品名称为"' + row.title + '"的数据项？').then(() => {
        this.loading = true;
        return businessProductStatus(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          partnerRelationAdd(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      const ids = row.partnerId || this.ids;
      let statusText = row.status ? '禁用' : '解除';
      this.$modal.confirm('是否确认' + statusText + '合伙人昵称为"' + row.userNickName + '"的数据项？').then(() => {
        this.loading = true;
        return partnerRelationSetStatus(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    getList () {
      this.loading = true;
      this.queryParams["startTime"] = undefined;
      this.queryParams["endTime"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["startTime"] = this.daterangeCreateTime[0];
        this.queryParams["endTime"] = this.daterangeCreateTime[1];
      }
      partnerRelationPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getPartnerList () {
      partnerRelationList().then(res => {
        this.partnerList = res.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
}
</script>

<style lang="scss">
.el-drawer__body {
  padding: 0 20px !important;
}
</style>
<style lang="scss" scoped>
.flex {
  display: flex;
}
.demo-drawer__footer {
  margin-left: 120px;
}
.activeCls {
  color: #1890ff;
  cursor: pointer;
}
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: rgb(96, 98, 102);
}
</style>