<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      代理商管理
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="姓名/手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="state">
          <el-select placeholder="状态" v-model="searchForm.state" clearable>
            <el-option label="正常" value="0"></el-option>
            <el-option label="冻结" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <el-button native-type="reset" type="danger">重置</el-button>
        </el-form-item>
      </save-form>
      <div class="btnList">
        <el-button type="primary" style="margin-bottom: 20px" @click="addAgent">
          新建代理商
        </el-button>
        <el-button type="primary" style="margin-bottom: 20px" @click="lookH5">
          代理商H5
        </el-button>
      </div>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
          row-key="userId"
          ref="table1"
          type="expand"
          lazy
          :load="getStaffList"
          @expand-change="hasExpandChange"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <!--     -->
          <el-table-column
            align="center"
            prop="userId"
            label="代理商编号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="proxyName"
            label="代理商名称"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="姓名"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="phone"
            label="手机号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="role"
            label="角色"
          ></el-table-column>
          <el-table-column align="center" prop="state" label="状态">
            <template slot-scope="scope">
              {{ scope.row.state == "0" ? "正常" : "冻结" }}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="300"
          >
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="onJoinQrCode(scope.row)"
                  >入驻二维码</el-button
                >
                <el-button
                  type="text"
                  v-if="!scope.row.parentId"
                  @click="addAgentStaff(scope.row)"
                  >添加员工</el-button
                >
                <!-- permission -->
                <el-button
                  type="text"
                  v-if="!scope.row.parentId"
                  @click="addAgent(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  v-if="scope.row.parentId"
                  @click="addAgentStaff(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  v-if="scope.row.state == '0' && !scope.row.parentId"
                  @click="freezeProxy(scope.row)"
                  >冻结</el-button
                >
                <el-button
                  type="text"
                  v-if="scope.row.state != '0' && !scope.row.parentId"
                  @click="freezeProxy(scope.row)"
                  >启用</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <eidtAgentMager ref="eidtAgentMagerRef" @getList="getList" />
    <eidthStaff ref="eidthStaffRef" @getList="resetTreedata" />
    <qr-code
      v-model="codeStatus"
      :isDown="true"
      :title="title"
      :codeUrl="qrCodeUrl"
    />
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import { permission } from "@/utils/directivePage";
import {
  getProxyUserList,
  freezeProxyUser,
  getProxyUserStaffList,
} from "./api";
import eidtAgentMager from "./modals/eidtAgentMager";
import eidthStaff from "./modals/eidthStaff";
import qrCode from "@/components/QrCode/index";
import {
  isvalidPhone,
  vaildStudentUrl,
  vaildTeachingUrl,
} from "@/utils/validate";
export default {
  components: { pagination, eidtAgentMager, qrCode, eidthStaff },
  data() {
    return {
      searchForm: {
        search: null,
        state: "",
      },

      tableList: [],
      organList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      codeStatus: false,
      qrCodeUrl: null,
      title: "入驻二维码",
      hasLoad: false,
      currentLoadTreeData: null,
      resolveObj: null,
      treeIds: [],
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部

    this.init();
  },
  methods: {
    init() {
      this.getList();
    },
    async getList() {
      try {
        const res = await getProxyUserList({
          ...this.searchForm,
          page: this.rules.page,
          rows: this.rules.limit,
        });
        this.tableList = res.data.rows.map((item, index) => {
          // console.log(this.$refs.table1["store"].states.treeData)
          return {
            ...item,
            hasChildren: true,
          };
        });

        this.refreshRow();
        this.rules.total = res.data.total;
      } catch (e) {}
    },
    search() {
      this.rules.page = 1;
      this.getList();
      // this.$set(this.$refs.table1.store.states.lazyTreeNodeMap,parentId,this.childrenData)
    },
    onReSet() {
      this.$nextTick(() => {
        this.search();
      });
    },
    permission(str) {
      return permission(str);
    },
    addAgent(row) {
      this.$refs.eidtAgentMagerRef.openDialog(row);
    },
    addAgentStaff(row) {
      this.$refs.eidthStaffRef.openDialog(row);
    },
    onJoinQrCode(row) {
      this.qrCodeUrl =
        vaildStudentUrl() +
        "/project/questionAsk/index.html?recommender=" +
        row.userId;
      this.title = "入驻二维码";
      this.codeStatus = true;
    },
    lookH5() {
      this.qrCodeUrl = vaildTeachingUrl() + "/#/saas-home";
      this.title = "代理商H5";
      this.codeStatus = true;
    },
    async freezeProxy(row) {
      let str = "";
      let state = "";
      if (row.state == 0) {
        state = 1;
        str = "冻结";
      } else {
        state = 0;
        str = "启用";
      }
      try {
        await this.$confirm(`是否${str}代理商"${row.proxyName}"?`, "提示", {
          type: "warning",
        });
        await freezeProxyUser({ state, id: row.userId });
        this.$message.success(`${str}成功`);
        this.getList();
      } catch (e) {}
    },
    async getStaffList(tree, treeNode, resolve) {
      this.hasLoad = true;
      this.currentLoadTreeData = tree;
      this.resolveObj = resolve;
      if (!this.treeIds.includes(tree.userId)) {
        this.treeIds.push(tree.userId);
      }
      try {
        const res = await getProxyUserStaffList({ id: tree.userId });
        console.log(res.data);
        resolve(res.data || []);
      } catch (e) {
        //  resolve([])
      }
    },
    hasExpandChange(row, expanded) {
      if (expanded) {
        // 当前是展开状态
        if (this.hasLoad) {
          // 已执行过load，则去掉执行过的标记
          this.hasLoad = false;
        } else {
          // 不然，则执行load。因为load只会执行一次，所以需要在expand事件触发再次执行
          this.getStaffList(this.currentLoadTreeData, "", this.resolveObj);
        }
      }
    },
    refreshRow() {
      for (let i in this.treeIds) {
        this.$refs.table1["store"].states.treeData[
          this.treeIds[i]
        ].loaded = false;
        this.$refs.table1["store"].states.treeData[
          this.treeIds[i]
        ].expanded = false;
      }
    },
    async resetTreedata(parentId) {
      try {
        const res = await getProxyUserStaffList({ id: parentId });
        this.$set(
          this.$refs.table1.store.states.lazyTreeNodeMap,
          parentId,
          res.data
        );
      } catch (e) {
        //  resolve([])
      }
    },
  },
};
</script>
<style lang='scss' scoped>
</style>
