<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="归属系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in permissionsSysOriginPlatforms"
          :key="index"
          :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>

      <el-select
        v-model="listQuery.role"
        placeholder="角色"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in teamMemberRoles"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <div class="filter-item">
        <account-input
          v-model="listQuery.ownUserId"
          :sys-origin="listQuery.sysOrigin"
          placeholder="代理ID"
        />
      </div>
      <div class="filter-item">
        <account-input
          v-model="listQuery.memberId"
          :sys-origin="listQuery.sysOrigin"
          placeholder="成员ID"
        />
      </div>
      <div class="filter-item">
        <el-input v-model="listQuery.notActiveDays" 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-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="teamMebmerAddVisible = true"
      >
        新增
      </el-button>
      <el-button
        v-if="selectTableRow.length > 0"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        :disabled="delLoading"
        :loading="delLoading"
        @click="clickRemoveMemberBatch"
      >
        删除
      </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
        :selectable="tableSelectable"
      />
      <el-table-column
        label="代理"
        align="left"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.ownUserProfile"
            :query-details="true"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="成员"
        align="center"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.userProfile"
            :query-details="true"
            :show-sys-origin="true"
            :tag-name="memberRoleMap[scope.row.role].name"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        prop="remarks"
        align="center"
        show-overflow-tooltip
        min-width="200"
      />

      <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"
          />
          <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="center"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <div>创建: {{ scope.row.createTime | dateFormat }}</div>
          <div>活跃: {{ scope.row.activeTime | 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
                v-if="scope.row.role !== 'OWN'"
                @click.native="clickMemberTeamChange(scope.row)"
                >更换团队</el-dropdown-item
              >
              <el-dropdown-item
                v-if="scope.row.role !== 'OWN'"
                :disabled="delLoading"
                @click.native="clickRemoveMember(scope.row)"
                >删除成员</el-dropdown-item
              >
              <el-dropdown-item
                @click.native="clickEditMemberRemarks(scope.row)"
                >修改备注</el-dropdown-item
              >
              <el-dropdown-item @click.native="clickResetTarget(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-member-add
      v-if="teamMebmerAddVisible"
      :sys-origin="listQuery.sysOrigin"
      @close="teamMebmerAddVisible = false"
      @success="teamMebmerAddSuccess"
    />

    <team-member-remark
      v-if="teamMebmerRemarkVisible"
      :row="thatRow"
      @close="teamMebmerRemarkVisible = false"
      @success="teamMebmerRemarkSuccess"
    />

    <team-member-change
      v-if="teamMemberChangeVisible"
      :row="thatRow"
      @close="teamMemberChangeVisible = false"
      @success="teamMemberChangeSuccess"
    />

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

    <team-member-target-reset
      v-if="teamMemberTargetResetVisible"
      :row="thatRow"
      @close="teamMemberTargetResetVisible = false"
    />
  </div>
</template>

<script>
import { listMemberTable, removeTeamMember } from "@/api/team";
import { pickerOptions } from "@/constant/el-const";
import { sysOriginPlatforms } from "@/constant/origin";
import { teamMemberRoles, teamMemberRoleMap } from "@/constant/team-type";
import { mapGetters } from "vuex";

import TeamMemberAdd from "./team-member-add";
import TeamMemberRemark from "./team-member-remark";
import TeamMemberChange from "./team-member-change";
import TeamMemberTargetReset from "./team-member-target-reset";
import TeamDetailsDrawer from "./../components/TeamDetailsDrawer";

export default {
  components: {
    TeamMemberTargetReset,
    TeamMemberAdd,
    TeamMemberRemark,
    TeamMemberChange,
    TeamDetailsDrawer
  },
  data() {
    return {
      teamMemberTargetResetVisible: false,
      teamDetailsDrawerVisible: false,
      teamMemberRoles,
      memberRoleMap: teamMemberRoleMap(),
      sysOriginPlatforms,
      thatRow: {},
      teamMebmerAddVisible: false,
      teamMebmerRemarkVisible: false,
      teamMemberChangeVisible: false,
      delLoading: false,
      selectMemberIds: [],
      pickerOptions,
      cardTeamId: "",
      cardSysOrigin: "",
      listQuery: {
        limit: 20,
        teamId: "",
        memberId: "",
        sysOrigin: "",
        role: "",
        lastId: "",
        startTime: "",
        endTime: "",
        notActiveDays: "",
        ownUserId: ""
      },
      listLoading: false,
      list: [],
      notData: false,
      loadMoreLoading: false,
      rangeDate: "",
      selectTableRow: []
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  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 = "";
      }
    }
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData();
  },
  methods: {
    renderData(isReset, loadMore) {
      const that = this;
      if (isReset === true) {
        that.list = [];
        that.notData = false;
        that.listQuery.lastId = "";
      }
      that.loadMoreLoading = loadMore;
      that.listLoading = !loadMore;
      listMemberTable(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].id;
          }
        })
        .catch(er => {
          that.listLoading = false;
          that.loadMoreLoading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    clickLoadMore() {
      const that = this;
      that.loadMoreLoading = true;
      that.renderData(false, true);
    },
    clickEditMemberRemarks(row) {
      this.thatRow = row;
      this.teamMebmerRemarkVisible = true;
    },
    clickResetTarget(row) {
      this.thatRow = row;
      this.teamMemberTargetResetVisible = true;
    },
    clickMemberTeamChange(row) {
      this.thatRow = row;
      this.teamMemberChangeVisible = row;
    },
    clickRemoveMember(row, index) {
      const that = this;
      if (that.delLoading) {
        that.$opsMessage.warn("正在提交处理中!");
        return;
      }

      that
        .$confirm("是否确认删除, 本期账单工作数据将会同步移除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          that.delLoading = true;
          removeTeamMember({ ids: [row.userProfile.id] }).then(res => {
            that.$opsMessage.success();
            that.delLoading = false;
            that.list.splice(index, 1);
            that.listQuery.lastId = that.list[that.list.length - 1].id;
            this.$refs.teamTable.clearSelection();
          });
        })
        .catch(() => {
          that.delLoading = false;
        });
    },

    // 删除主播
    clickRemoveMemberBatch() {
      const that = this;
      if (that.delLoading) {
        that.$opsMessage.warn("正在提交处理中!");
        return;
      }
      that.selectMemberIds = that.selectTableRow.map(
        item => item.userProfile.id
      );
      that
        .$confirm("是否确认删除, 本期账单工作数据将会同步移除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          that.delLoading = true;
          removeTeamMember({ ids: that.selectMemberIds }).then(res => {
            that.$opsMessage.success();
            that.delLoading = false;
            const processMemberIdStr = that.selectMemberIds.join(",");
            const newList = [];
            that.list.forEach(row => {
              if (processMemberIdStr.indexOf(row.id) < 0) {
                newList.push(row);
              }
            });
            that.list = newList;
            that.listQuery.lastId = that.list[that.list.length - 1].id;
            this.$refs.teamTable.clearSelection();
          });
        })
        .catch(() => {
          that.delLoading = false;
        });
    },
    teamMebmerAddSuccess() {
      this.$opsMessage.success();
      this.teamMebmerAddVisible = false;
      this.renderData(true);
    },
    teamMebmerRemarkSuccess(form) {
      this.$opsMessage.success();
      this.teamMebmerRemarkVisible = false;
      this.thatRow.remarks = form.remarks;
    },
    teamMemberChangeSuccess(res) {
      const that = this;
      that.$opsMessage.success();
      if (res) {
        const newList = [];
        that.list.forEach(item => {
          newList.push(item.id !== that.thatRow.id ? item : res);
        });
        that.list = newList;
        that.teamMemberChangeVisible = false;
      }
    },
    editTeamProfile(row) {
      this.thatRow = row;
      this.teamEditVisible = true;
    },
    selectTableChange(list) {
      this.selectTableRow = list;
    },
    tableSelectable(row) {
      return row.role !== "OWN";
    },
    clickQueryTeamDetails(row) {
      this.thatRow = row;
      this.teamDetailsDrawerVisible = true;
    }
  }
};
</script>
<style scoped lang="scss">
.load-more {
  text-align: center;
  padding: 10px;
}
</style>
