<template>
  <div class="app-container">
    <!-- 有操作权限 -->
    <div v-if="isQueryPermissions">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <!-- 系统 -->
        <el-select
          v-model="listQuery.sysOrigin"
          :placeholder="$t('pages.businessDevelopment.filter.system')"
          style="width: 120px"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option
            v-for="item in permissionsSysOriginPlatforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;">
              <sys-origin-icon :icon="item.value" :desc="item.value"
            /></span>
            <span style="float: left;margin-left:10px">{{ item.label }}</span>
          </el-option>
        </el-select>

        <!-- BD用户ID -->
        <div class="filter-item">
          <account-input
            v-model="listQuery.userId"
            :sys-origin="listQuery.sysOrigin"
            :placeholder="$t('pages.businessDevelopment.filter.bdUserId')"
          />
        </div>

        <!-- BD Lead用户ID -->
        <div class="filter-item">
          <account-input
            v-model="listQuery.bdLeadUserId"
            :sys-origin="listQuery.sysOrigin"
            :placeholder="$t('pages.businessDevelopment.filter.bdLeadUserId')"
          />
        </div>

        <!-- 区域 -->
        <div class="filter-item" style="width: 120px;">
          <select-system-region
            ref="regionSelectPolicy"
            v-model="listQuery.region"
            :sys-origin="listQuery.sysOrigin"
            clearable
            :placeholder="$t('pages.businessDevelopment.filter.region')"
            @change="handleSearch"
          />
        </div>

        <!-- 成员数量 -->
        <div class="filter-item">
          <el-input
            v-model="listQuery.memberQuantityRange"
            :placeholder="$t('pages.businessDevelopment.filter.memberQuantityRange')"
          />
        </div>

        <!-- 后台成员 -->
        <el-select
          v-if="backUserConditionVisible"
          v-model="listQuery.createUser"
          v-loading="listMembersLoading"
          :placeholder="$t('pages.businessDevelopment.filter.backendMember')"
          style="width: 120px"
          class="filter-item"
          clearable
          filterable
          @change="handleSearch"
        >
          <el-option
            v-for="(item, index) in members"
            :key="index"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>

        <!-- 搜索按钮 -->
        <el-button
          :loading="searchLoading"
          :disabled="searchDisabled"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          {{ $t('pages.businessDevelopment.action.search') }}
        </el-button>

        <!-- 新增BD 按钮 -->
        <el-button
          v-if="buttonPermissions.includes('bd:list:add')"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          {{ $t('pages.businessDevelopment.action.createBd') }}
        </el-button>
      </div>

      <!-- 表单 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @cell-mouse-enter="handleMouseEnter"
      >
        <!-- 排序 -->
        <el-table-column type="index" width="50" label="No" />

        <!-- 系统 -->
        <!-- <el-table-column prop="sysOrigin" label="系统" align="center" min-width="60">
          <template slot-scope="scope">
            <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
          </template>
        </el-table-column>
         -->

        <!-- 用户信息 -->
        <el-table-column :label="$t('pages.businessDevelopment.table.user')" align="center" min-width="190">
          <template slot-scope="scope">
            <user-table-exhibit
              :user-profile="scope.row.userProfile"
              :query-details="true"
            />
          </template>
        </el-table-column>

        <!-- 区域 -->
        <el-table-column
          prop="regionName"
          :label="$t('pages.businessDevelopment.table.region')"
          align="center"
          min-width="60"
        />

        <!-- 成员数量 -->
        <el-table-column
          prop="agentCount"
          :label="$t('pages.businessDevelopment.table.teamCount')"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <div>
              <!-- 展示团队成员 -->
              <el-button
                v-if="scope.row.agentCount > 0"
                type="text"
                @click.native="clickTeamMember(scope.row)"
                >{{ scope.row.agentCount }}</el-button
              >
              <span v-else>0</span>
            </div>
          </template>
        </el-table-column>

        <!-- BD Leader -->
        <el-table-column label="BD Leader" align="center" min-width="190">
          <template slot-scope="scope">
            <user-table-exhibit
              :user-profile="scope.row.bdLeadUserProfile"
              :query-details="true"
            />
          </template>
        </el-table-column>

        <!-- 联系方式 -->
        <el-table-column
          v-if="buttonPermissions.includes('bd:list:edit')"
          prop="contact"
          :label="$t('pages.businessDevelopment.table.contact')"
          align="center"
          min-width="100"
        />

        <!-- 创建人 -->
        <el-table-column
          prop="createUserName"
          :label="$t('pages.businessDevelopment.table.createdBy')"
          align="center"
          min-width="100"
        />

        <!-- 修改人 -->
        <el-table-column
          prop="updateUserName"
          :label="$t('pages.businessDevelopment.table.updatedBy')"
          align="center"
          min-width="100"
        />

        <!-- 创建时间 -->
        <el-table-column
          prop="createTime"
          :label="$t('pages.businessDevelopment.table.createdAt')"
          align="center"
          width="160"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat }}
          </template>
        </el-table-column>

        <!-- 操作列表 -->
        <el-table-column
          v-if="showOperationCol"
          fixed="right"
          :label="$t('pages.businessDevelopment.table.actions')"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- 新增代理 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:add:member')"
                  @click.native="clickTeam(scope.row, scope.$index)"
                  >{{ $t('pages.businessDevelopment.action.createAgent') }}</el-dropdown-item
                >

                <!-- 绑定代理 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:add:bind')"
                  @click.native="clickBindTeam(scope.row, scope.$index)"
                  >{{ $t('pages.businessDevelopment.action.bindAgent') }}</el-dropdown-item
                >

                <!-- 编辑 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:edit')"
                  @click.native="clickEdit(scope.row, scope.$index)"
                  >{{ $t('pages.businessDevelopment.action.edit') }}</el-dropdown-item
                >

                <!-- 删除 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:del')"
                  @click.native="handlBDDel(scope.row.id, scope.$index)"
                  >{{ $t('pages.businessDevelopment.action.delete') }}</el-dropdown-item
                >

                <!-- 换绑BD Leader -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:edit')"
                  @click.native="changeBinding(scope.row, scope.$index)"
                  >{{ $t('pages.businessDevelopment.action.changeBdLeader') }}</el-dropdown-item
                >

                <!-- 权限分配 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('bd:list:role:change')"
                  @click.native="AttributionSystem(scope.row)"
                  >{{ $t('pages.businessDevelopment.action.assignPermission') }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.cursor"
        :limit.sync="listQuery.limit"
        @pagination="renderData"
      />

      <!-- 团队成员组件 -->
      <team-member
        v-if="teamMemberVisible"
        :query="teamMemberQuery"
        @close="
          teamMemberVisible = false;
          teamMemberQuery = {};
        "
      />

      <!-- 新增/编辑BD 组件 -->
      <add-bd
        v-if="addBdVisible"
        :row="thisRow"
        @success="addBdSuccess"
        @close="addBdVisible = false"
      />

      <!-- 新增代理组件 -->
      <team-create
        v-if="teamCreateVisible"
        :sys-origin="listQuery.sysOrigin"
        :bd-ops="bdOps"
        @success="teamCreateSuccess"
        @close="teamCreateVisible = false"
      />

      <!-- 绑定代理组件 -->
      <bind-team
        v-if="teamBindDrawerVisible"
        :row="thatRow"
        @success="teamBindSuccess"
        @close="teamBindDrawerVisible = false"
      />

      <!-- 权限分配组件 -->
      <auth-system
        v-if="authSystemVisable"
        :user-id="thatSelectedUserId"
        @close="authSystemVisable = false"
      />

      <!-- 绑定BDLeader 组件 -->
      <bind-bd-leader
        v-if="BDLeaderBindDrawerVisible"
        :row="thatRow"
        @success="BDLeaderBindSuccess"
        @close="BDLeaderBindDrawerVisible = false"
      />
    </div>

    <!-- 无权限 提示 -->
    <div
      v-else
      v-loading.lock="listLoading"
      element-loading-background="#FFFFFF"
      :element-loading-text="$t('pages.businessDevelopment.permission.validating')"
      style="text-align: center;"
    >
      {{ $t('pages.businessDevelopment.permission.deniedPrefix') }}
      {{ $t('pages.businessDevelopment.permission.deniedCode') }}
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { copyText } from "@/utils";

import { pageRoomBDInfo, deleteBD } from "@/api/room-anchor";
import { listMembers } from "@/api/team";

import Pagination from "@/components/Pagination";
import TeamMember from "./team-member";
import AddBd from "./add-bd";
import TeamCreate from "./../components/TeamCreate";
import BindTeam from "./bind-team";
import bindBdLeader from "./bind-bd-leader";
import authSystem from "./auth";

export default {
  name: "BusinessDevelopment",
  components: {
    Pagination,
    TeamMember,
    AddBd,
    TeamCreate,
    BindTeam,
    bindBdLeader,
    authSystem
  },
  data() {
    return {
      teamBindDrawerVisible: false,
      BDLeaderBindDrawerVisible: false,
      authSystemVisable: false,
      thatRow: {},
      bdOps: {},
      teamCreateVisible: false,
      thisRow: {},
      thisRowIndex: 0,
      level: 0,
      dbDisabled: false,
      agentDisabled: false,
      teamMemberQuery: {},
      teamMemberVisible: false,
      addBdVisible: false,
      textOptTitle: "",
      thatSelectedUserId: "",
      submitLoading: false,
      list: [],
      members: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: "",
        bdLeadUserId: "",
        sysOrigin: "HALAR",
        createUser: "",
        region: "",
        memberQuantityRange: ""
      },
      listLoading: false,
      listMembersLoading: false,
      searchLoading: false,
      backUserConditionVisible: false
    };
  },
  computed: {
    ...mapGetters([
      "uid",
      "buttonPermissions",
      "permissionsSysOriginPlatforms",
      "permissionsFirstSysOrigin"
    ]),

    // 是否有操作权限
    showOperationCol() {
      return (
        this.buttonPermissions.includes("bd:list:edit") ||
        this.buttonPermissions.includes("bd:list:add:bind") ||
        this.buttonPermissions.includes("bd:list:del") ||
        this.buttonPermissions.includes("bd:list:add:member")
      );
    },

    // 是否有查看权限
    isQueryPermissions() {
      return (
        this.buttonPermissions.includes("bd:list:query:all") ||
        this.buttonPermissions.includes("bd:list:query:self")
      );
    }
  },
  watch: {
    buttonPermissions: {
      handler(newVal) {
        this.backUserConditionVisible = newVal.includes("bd:list:query:all");
        if (newVal.includes("bd:list:query:self")) {
          if (newVal.includes("bd:list:query:all")) {
            return;
          }
          this.listQuery.createUser = this.uid;
          this.renderData(true);
          return;
        }
      },
      immediate: true
    }
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.loadMembers();
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData(true);
  },
  methods: {
    // 调接口重置数据
    renderData(isReset) {
      const that = this;
      if (isReset === true) {
        that.listQuery.cursor = 1;
        that.list = [];
      }

      if (that.listLoading === true && isReset === true) {
        return;
      }

      that.listLoading = true;
      that.searchDisabled = true;
      pageRoomBDInfo(that.listQuery)
        .then(res => {
          const { body } = res;
          that.total = body.total || 0;
          that.list = body.records;
          that.listLoading = false;
          that.searchLoading = false;
          that.searchDisabled = false;
        })
        .catch(er => {
          that.listLoading = false;
          that.searchLoading = false;
          that.searchDisabled = false;
        });
    },

    // 初始化数据
    loadMembers() {
      const that = this;
      that.listMembersLoading = true;
      listMembers()
        .then(res => {
          const { body } = res;
          that.members = body;
          that.listMembersLoading = false;
          that.searchLoading = false;
        })
        .catch(er => {
          that.listMembersLoading = false;
          that.searchLoading = false;
        });
    },

    // 搜索
    handleSearch() {
      const that = this;
      that.searchLoading = true;
      that.renderData(true);
    },

    // 新增BD
    handleCreate() {
      this.textOptTitle = "新增BD";
      this.thisRow = {}; // 置空为新增BD
      this.thisRow.sysOrigin = this.listQuery.sysOrigin;
      this.addBdVisible = true;
    },

    // 新增代理
    clickTeam(row, _index) {
      this.teamCreateVisible = true;
      this.thisRowIndex = _index;
      this.bdOps = {
        userId: row.userProfile.id,
        region: row.region,
        contact: row.contact
      };
    },

    // 绑定代理
    clickBindTeam(row, _index) {
      this.thatRow = row;
      this.thisRowIndex = _index;
      this.teamBindDrawerVisible = true;
    },

    // 换绑BDLeader
    changeBinding(row, _index) {
      this.thatRow = row;
      this.thisRowIndex = _index;
      this.BDLeaderBindDrawerVisible = true;
    },

    AttributionSystem(row) {
      const that = this;
      this.thatSelectedUserId = row.userId;
      that.authSystemVisable = true;
    },

    // 展示团队成员
    clickTeamMember(row) {
      this.teamMemberVisible = true;
      this.teamMemberQuery = {
        userId: row.userId
      };
    },

    // 绑定代理成功
    teamBindSuccess() {
      this.list[this.thisRowIndex].agentCount =
        Number(this.list[this.thisRowIndex].agentCount) + 1;
      this.teamBindDrawerVisible = false;
    },

    // 换绑BDLeader成功
    BDLeaderBindSuccess() {
      this.$opsMessage.success();
      this.BDLeaderBindDrawerVisible = false;
      this.handleSearch();
    },

    // 新增/修改BD成功
    addBdSuccess(form) {
      this.$opsMessage.success();
      this.addBdVisible = false;
      this.renderData(!!form.id);
    },

    accountHandleSuccess(data) {
      this.$message({
        message: "Successful",
        type: "success"
      });
      // this.renderData()
    },

    handleLiveClick(row) {
      window.open(row.liveUrl);
    },

    copyTextContent(text) {
      const that = this;
      copyText(text)
        .then(() => {
          that.$message({
            message: that.$t("pages.businessDevelopment.message.copySuccess"),
            type: "success"
          });
        })
        .catch(() => {
          that.$message({
            message: that.$t("pages.businessDevelopment.message.copyFail"),
            type: "error"
          });
        });
    },

    originText(row) {
      const texts = [];
      if (row.originPlatform) {
        texts.push(row.originPlatform);
      }
      if (row.originPhoneModel) {
        texts.push(row.originPhoneModel);
      }
      return texts.join("，");
    },

    // 关闭新增BD弹窗
    handleClose() {
      this.addBdVisible = false;
    },

    // 成功新增代理
    teamCreateSuccess() {
      this.$opsMessage.success();
      this.teamCreateVisible = false;
      this.list[this.thisRowIndex].agentCount =
        Number(this.list[this.thisRowIndex].agentCount) + 1;
    },

    // 编辑BD
    clickEdit(row, _index) {
      const that = this;
      that.thisRow = row;
      that.thisRowIndex = _index;
      that.textOptTitle = "编辑BD";
      that.addBdVisible = true;
    },

    // 删除BD
    handlBDDel(id, _index) {
      const that = this;
      this.$confirm(
        this.$t("pages.businessDevelopment.confirm.deleteMessage"),
        this.$t("pages.businessDevelopment.confirm.title"),
        {
          confirmButtonText: this.$t("pages.businessDevelopment.action.confirm"),
          cancelButtonText: this.$t("pages.businessDevelopment.action.cancel")
        }
      )
        .then(() => {
          deleteBD(id)
            .then(res => {
              that.$opsMessage.success();
              that.list.splice(_index, 1);
            })
            .catch(er => {
              that.$opsMessage.success();
            });
        })
        .catch(() => {});
    },

    toPlatformSvgIconKey(row) {
      if (row.cellphoneNumber) {
        return "phone";
      }
      if (row.facebookId) {
        return "facebook";
      }
      if (row.googleId) {
        return "google";
      }
      if (row.appleId) {
        return "apple";
      }
      if (row.snapchatId) {
        return "snapchat";
      }
      return "";
    },

    renderDataSuccess() {
      this.$message({
        message: "Successful",
        type: "success"
      });
      this.renderData();
    },

    // 保存搜索条件
    handleMouseEnter(row) {
      this.thisRow = row;
      this.thatSelectedUserId = row.userId;
    }
  }
};
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}
</style>
