<template>
  <div class="app-container">
    <div v-if="isQueryPermissions">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <div class="filter-item" style="width: 120px;">
          <sys-origin-permission-select
            v-model="listQuery.sysOrigin"
            @change="changeSysOrigin"
            @onLoad="onLoadPermissionSysOrigin"
          />
        </div>

        <div class="filter-item" style="width: 120px;">
          <select-system-region
            ref="regionSelectPolicy"
            v-model="listQuery.region"
            :sys-origin="listQuery.sysOrigin"
            clearable
            placeholder="区域"
            @change="changeRegionSelectPolicy"
          />
        </div>

        <div class="filter-item" style="width: 120px;">
          <el-select
            v-model="listQuery.status"
            placeholder="状态"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="(item, index) in teamStatus"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="filter-item">
          <account-input
            v-model="listQuery.ownUserId"
            :sys-origin="listQuery.sysOrigin"
            placeholder="代理ID"
          />
        </div>

        <div class="filter-item">
          <el-input
            v-model="listQuery.memberQuantityRange"
            placeholder="开始~结束成员数量"
          />
        </div>
        <div class="filter-item">
          <el-date-picker
            v-model="rangeDate"
            style="width: 100%;"
            value-format="timestamp"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期开始"
            end-placeholder="结束日期结束"
          />
        </div>
        <el-select
          v-if="backUserConditionVisible"
          v-model="listQuery.createUser"
          v-loading="listMemberLoading"
          placeholder="后台成员"
          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
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          v-if="buttonPermissions.includes('team:list:add')"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="teamCreateVisible = true"
        >
          新增
        </el-button>
        <el-button
          v-if="
            selectTableRow.length > 0 &&
              buttonPermissions.includes('team:list:del')
          "
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          :loading="statusChangeLoading"
          :disabled="statusChangeLoading"
          @click="clickCloseTeamBatch"
        >
          删除
        </el-button>
      </div>

      <!-- 表单 -->
      <el-table
        ref="teamTable"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @selection-change="selectTableChange"
      >
        <el-table-column type="index" width="50" label="No" />
        <el-table-column type="selection" width="50" show-overflow-tooltip />
        <el-table-column
          label="代理"
          align="left"
          min-width="220"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <user-table-exhibit
              :size="scope.row.bdUserProfile ? 'mini' : 'small'"
              :user-profile="scope.row.ownUserProfile"
              :query-details="true"
            />
            <div v-if="scope.row.bdUserProfile" class="attached">
              <user-table-exhibit
                size="mini"
                :user-profile="scope.row.bdUserProfile"
                :query-details="true"
                tag-name="BD"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="信息"
          align="left"
          show-overflow-tooltip
          min-width="150"
        >
          <template slot-scope="scope">
            <div>
              成员:
              {{ (scope.row.teamProfile.counter || {}).memberQuantity }}/{{
                (scope.row.teamProfile.setting || {}).maxMember
              }}
            </div>
            <div>
              状态:
              <el-tag
                v-if="scope.row.teamProfile.status === 'AVAILABLE'"
                size="mini"
                type="success"
                >正常</el-tag
              >
              <el-tag
                v-if="scope.row.teamProfile.status === 'CLOSE'"
                size="mini"
                type="danger"
                >关闭</el-tag
              >
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          show-overflow-tooltip
          min-width="100"
          prop="regionName"
          label="区域"
        />

        <el-table-column
          align="left"
          show-overflow-tooltip
          min-width="80"
          label="备注"
        >
          <template slot-scope="scope">
            <div>
              <el-link @click.native="editTeamRemark(scope.row)">{{
                scope.row.teamProfile.remarks.length
              }}</el-link>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="创建人"
          align="left"
          show-overflow-tooltip
          min-width="220"
        >
          <template slot-scope="scope">
            <user-table-exhibit
              v-if="scope.row.createUserProfile"
              :user-profile="scope.row.createUserProfile"
              :query-details="true"
              :tag-name="scope.row.createUserBdRoles ? 'BD' : ''"
            />
            <div v-else-if="scope.row.createUserNickname" class="flex-l">
              <avatar :name-avatar="scope.row.createUserNickname" />
              <span style="margin-left: 10px;">{{
                scope.row.createUserNickname
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="修改人"
          align="left"
          show-overflow-tooltip
          min-width="220"
        >
          <template slot-scope="scope">
            <user-table-exhibit
              v-if="scope.row.updateUserProfile"
              :user-profile="scope.row.updateUserProfile"
              :query-details="true"
              :tag-name="scope.row.updateUserBdRoles ? 'BD' : ''"
            />
            <div v-else-if="scope.row.updateUserNickname" class="flex-l">
              <avatar :name-avatar="scope.row.updateUserNickname" />
              <span style="margin-left: 10px;">{{
                scope.row.updateUserNickname
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="时间"
          align="center"
          show-overflow-tooltip
          min-width="220"
        >
          <template slot-scope="scope">
            <div>创建: {{ scope.row.teamProfile.createTime | dateFormat }}</div>
            <div>修改: {{ scope.row.teamProfile.updateTime | dateFormat }}</div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center" width="100">
          <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
                  @click.native="clickQueryTeamDetails(scope.row)"
                  >资料详情</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:edit')"
                  @click.native="editTeamProfile(scope.row)"
                  >修改资料</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:bind:bd')"
                  @click.native="clickBindBd(scope.row)"
                  >绑定BD</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:edit')"
                  @click.native="editTeamRemark(scope.row)"
                  >备注信息</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:edit')"
                  @click.native="editTeamContact(scope.row)"
                  >联系方式</el-dropdown-item
                >
                <!-- <el-dropdown-item :disabled="statusChangeLoading" @click.native="clickChangeTeamStatus(scope.row)">状态变更</el-dropdown-item> -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:send:notice')"
                  @click.native="handleNoticeSend(scope.row)"
                  >发送通知</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('team:list:query:send:notice')
                  "
                  @click.native="handleNoticeList(scope.row)"
                  >通知记录</el-dropdown-item
                >
                <!-- <el-dropdown-item>账单信息-未实现</el-dropdown-item> -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('team:list:query:apply')"
                  @click.native="handleApplicationProcess(scope.row)"
                  >团队申请</el-dropdown-item
                >
                <!-- <el-dropdown-item v-if="buttonPermissions.includes('team:list:query:approval')" @click.native="handleApplicationProcessApprova(scope.row)">审核日志</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 加载更多 -->
      <div v-if="listQuery.lastId" class="load-more">
        <span v-if="notData">已加载全部</span>
        <el-button
          v-else
          size="mini"
          :disabled="loadMoreLoading"
          :loading="loadMoreLoading"
          @click="clickLoadMore"
          >加载更多</el-button
        >
      </div>

      <team-create
        v-if="teamCreateVisible"
        :sys-origin="listQuery.sysOrigin"
        @success="teamCreateSuccess"
        @close="teamCreateVisible = false"
      />

      <!-- 修改资料组件 -->
      <team-edit
        v-if="teamEditVisible"
        :profile="thatRow.teamProfile"
        @success="teamEditSuccess"
        @close="teamEditVisible = false"
      />

      <team-remark
        v-if="teamRemarkVisible"
        :profile="thatRow.teamProfile"
        @close="teamRemarkVisible = false"
        @addRemarks="addRemarks"
        @revemoRemarks="revemoRemarks"
      />

      <team-contact
        v-if="teamContactVisible"
        :profile="thatRow.teamProfile"
        @close="teamContactVisible = false"
        @addContact="addContact"
        @revemoContact="revemoContact"
      />

      <team-status
        v-if="teamStatusVisible"
        :team-ids="changeTeamIds"
        :status="changeTeamStatus"
        @close="teamStatusVisible = false"
        @success="teamStatusSuccess"
      />

      <team-notice-send-drawer
        v-if="noticeSendVisible"
        :team-id="currentClickTeamId"
        @close="noticeSendVisible = false"
      />

      <team-notice-list-drawer
        v-if="noticeListVisible"
        :team-id="currentClickTeamId"
        @close="noticeListVisible = false"
      />

      <team-application-process-drawer
        v-if="applicationProcessVisible"
        :team-id="currentClickTeamId"
        @close="applicationProcessVisible = false"
      />

      <process-approval-drawer
        v-if="applicationProcessApprovaVisible"
        :team-id="currentClickTeamId"
        :sys-origin="currentClickSysOrigin"
        @close="applicationProcessApprovaVisible = false"
      />

      <team-details-drawer
        v-if="teamDetailsDrawerVisible"
        :team-id="thatRow.teamProfile.id"
        @close="teamDetailsDrawerVisible = false"
      />

      <team-switch-own
        v-if="teamSwitchOwnVisible"
        :profile="thatRow.teamProfile"
        @close="teamSwitchOwnVisible = false"
        @success="teamSwitchSuccess"
      />

      <bind-bd
        v-if="teamBindBdDrawerVisible"
        :row="thatRow"
        @close="teamBindBdDrawerVisible = false"
      />
    </div>
    <div
      v-else
      v-loading.lock="listLoading"
      element-loading-background="#FFFFFF"
      element-loading-text="权限验证中..."
      style="text-align: center;"
    >
      抱歉您无权查看，请联系管理员开通查看权限
      【主播中心/代理列表:(team:list:query:all/team:list:query:self)】
    </div>
  </div>
</template>

<script>
import { listTeamTable, delTeamBatch } from "@/api/team";
import { pickerOptions } from "@/constant/el-const";
import { sysOriginPlatforms } from "@/constant/origin";
import { teamStatus } from "@/constant/team-type";
import TeamCreate from "./../components/TeamCreate";
import TeamEdit from "./team-edit";
import TeamRemark from "./team-remark";
import TeamContact from "./team-contact";
import TeamStatus from "./team-status";
import TeamNoticeSendDrawer from "./team-notice-send-drawer";
import TeamNoticeListDrawer from "./team-notice-list-drawer";
import TeamApplicationProcessDrawer from "./team-application-process-drawer";
import ProcessApprovalDrawer from "./../components/ProcessApprovalDrawer";
import TeamDetailsDrawer from "./../components/TeamDetailsDrawer";
import TeamSwitchOwn from "./team-switch-own";
import BindBd from "./bind-bd";
import { listMembers } from "@/api/team";
import { mapGetters } from "vuex";

export default {
  name: "TeamTable",
  components: {
    TeamSwitchOwn,
    TeamDetailsDrawer,
    TeamEdit,
    TeamCreate,
    TeamRemark,
    TeamContact,
    TeamStatus,
    TeamNoticeSendDrawer,
    TeamNoticeListDrawer,
    TeamApplicationProcessDrawer,
    ProcessApprovalDrawer,
    BindBd
  },
  data() {
    return {
      teamBindBdDrawerVisible: false,
      listMemberLoading: false,
      backUserConditionVisible: false,
      teamSwitchOwnVisible: false,
      teamDetailsDrawerVisible: false,
      sysOriginPlatforms,
      thatRow: {},
      statusChangeLoading: false,
      teamStatusVisible: false,
      teamContactVisible: false,
      teamRemarkVisible: false,
      teamEditVisible: false,
      teamCreateVisible: false,
      noticeSendVisible: false,
      noticeListVisible: false,
      applicationProcessVisible: false,
      applicationProcessApprovaVisible: false,
      changeTeamIds: [],
      changeTeamStatus: "",
      teamStatus,
      pickerOptions,
      currentClickTeamId: "",
      currentClickSysOrigin: "",
      listQuery: {
        limit: 20,
        id: "",
        region: "",
        sysOrigin: "",
        account: "",
        ownUserId: "",
        status: "",
        lastId: "",
        startTime: "",
        endTime: "",
        createUser: "",
        memberQuantityRange: ""
      },
      listLoading: false,
      list: [],
      notData: false,
      loadMoreLoading: false,
      rangeDate: "",
      selectTableRow: [],
      members: [],
      searchLoading: false
    };
  },
  computed: {
    ...mapGetters([
      "uid",
      "buttonPermissions",
      "permissionsSysOriginPlatforms",
      "permissionsFirstSysOrigin"
    ]),
    isQueryPermissions() {
      return (
        this.buttonPermissions.includes("team:list:query:all") ||
        this.buttonPermissions.includes("team:list:query:self")
      );
    }
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0];
          this.listQuery.endTime = newVal[1];
          return;
        }
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },
    buttonPermissions: {
      handler(newVal) {
        this.backUserConditionVisible = newVal.includes("team:list:query:all");
        if (newVal.includes("team:list:query:self")) {
          if (newVal.includes("team:list:query:all")) {
            return;
          }
          this.listQuery.createUser = this.uid;
          this.renderData(true);
          return;
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadMembers();
  },
  methods: {
    renderData(isReset, loadMore) {
      const that = this;
      if (!that.listQuery.sysOrigin) {
        return;
      }
      if (isReset === true) {
        that.list = [];
        that.notData = false;
        that.listQuery.lastId = "";
      }
      that.loadMoreLoading = loadMore;
      that.listLoading = !that.loadMoreLoading;
      listTeamTable(that.listQuery)
        .then(res => {
          that.listLoading = false;
          that.loadMoreLoading = false;
          const { body } = res;
          const list = body || [];
          that.notData = list.length <= 0;
          if (!that.notData) {
            that.list = that.list.concat(list);
            that.listQuery.lastId =
              that.list[that.list.length - 1].teamProfile.id;
          }
        })
        .catch(er => {
          that.listLoading = false;
          that.loadMoreLoading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    changeRegionSelectPolicy() {
      this.handleSearch();
    },
    clickLoadMore() {
      const that = this;
      that.loadMoreLoading = true;
      that.renderData(false, true);
    },
    clickCloseTeamBatch() {
      const that = this;
      if (this.statusChangeLoading) {
        this.$opsMessage.warn("正在提交中!");
        return;
      }
      that.changeTeamIds = that.selectTableRow.map(item => item.teamProfile.id);
      that.changeTeamStatus = "CLOSE";
      // that.teamStatusVisible = true
      that
        .$confirm(
          "系统将移除团队所有数据, 操作不可逆!!!! (主播工作/账单/团队信息/团队成员/BD关系等所有)",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
        .then(() => {
          that.statusChangeLoading = true;
          delTeamBatch(that.changeTeamIds)
            .then(res => {
              that.statusChangeLoading = false;
              that.$opsMessage.success();
              that.renderData(true);
            })
            .catch(er => {
              that.statusChangeLoading = false;
            });
        })
        .catch(() => {});
    },
    teamCreateSuccess() {
      this.$opsMessage.success();
      this.teamCreateVisible = false;
      this.renderData(true);
    },
    clickSwitchTeamOwn(row) {
      this.thatRow = row;
      this.teamSwitchOwnVisible = true;
    },
    teamSwitchSuccess({ teamId, ownUserProfile }) {
      this.thatRow.ownUserProfile = ownUserProfile;
    },
    clickQueryTeamDetails(row) {
      this.thatRow = row;
      this.teamDetailsDrawerVisible = true;
    },

    // 修改资料
    editTeamProfile(row) {
      this.thatRow = row;
      this.teamEditVisible = true;
    },
    editTeamRemark(row) {
      this.thatRow = row;
      this.teamRemarkVisible = true;
    },
    teamEditSuccess(form, selectRegion) {
      this.thatRow.teamProfile = form;
      if (selectRegion) {
        this.thatRow.regionName = selectRegion.regionName;
      }
      this.$opsMessage.success();
    },
    addRemarks(remarks) {
      this.thatRow.teamProfile.remarks.push(remarks);
    },
    revemoRemarks(index) {
      this.thatRow.teamProfile.remarks.splice(index, 1);
    },
    editTeamContact(row) {
      this.thatRow = row;
      this.teamContactVisible = true;
    },
    addContact(contact) {
      this.thatRow.teamProfile.contacts.push(contact);
    },
    revemoContact(index) {
      this.thatRow.teamProfile.contacts.splice(index, 1);
    },
    handleNoticeSend(row) {
      this.currentClickTeamId = row.teamProfile.id;
      this.noticeSendVisible = true;
    },
    handleApplicationProcess(row) {
      this.currentClickTeamId = row.teamProfile.id;
      this.applicationProcessVisible = true;
    },
    handleApplicationProcessApprova(row) {
      this.currentClickTeamId = row.teamProfile.id;
      this.currentClickSysOrigin = row.teamProfile.sysOrigin;
      this.applicationProcessApprovaVisible = true;
    },
    handleNoticeList(row) {
      this.currentClickTeamId = row.teamProfile.id;
      this.noticeListVisible = true;
    },
    teamStatusSuccess(form) {
      this.$opsMessage.success();
      this.$refs.teamTable.clearSelection();
      form.teamIds.forEach(teamId => {
        const listSize = this.list.length;
        for (let index = 0; index < listSize; index++) {
          const row = this.list[index];
          if (row.teamProfile && row.teamProfile.id === teamId) {
            row.teamProfile.status = form.status;
            break;
          }
        }
      });
      this.teamStatusVisible = false;
    },
    clickChangeTeamStatus(row) {
      if (this.statusChangeLoading) {
        this.$opsMessage.warn("正在提交中!");
        return;
      }
      this.thatRow = row;
      this.changeTeamIds = [row.teamProfile.id];
      this.changeTeamStatus = row.teamProfile.status;
      this.teamStatusVisible = true;
    },
    selectTableChange(list) {
      this.selectTableRow = list;
    },
    changeSysOrigin() {
      this.$refs.regionSelectPolicy.clearValue();
      this.listQuery.region = "";
    },
    onLoadPermissionSysOrigin(val) {
      const that = this;
      that.renderData(true);
    },
    clickBindBd(row) {
      this.thatRow = row.teamProfile;
      this.teamBindBdDrawerVisible = true;
    },
    loadMembers() {
      const that = this;
      that.listMemberLoading = true;
      listMembers()
        .then(res => {
          const { body } = res;
          that.members = body;
          that.listMemberLoading = false;
        })
        .catch(er => {
          that.listMemberLoading = false;
        });
    }
  }
};
</script>
<style scoped lang="scss">
.load-more {
  text-align: center;
  padding: 10px;
}
</style>
