<template>
  <div class="app-container">

    <div>
      <div class="filter-container">
        <el-select
          v-model="listQuery.sysOrigin"
          placeholder="系统"
          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>
        <div class="filter-item">
          <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" placeholder="BD Leader用户ID" />
        </div>
        <el-select
          v-if="backUserConditionVisible"
          v-model="listQuery.createUser"
          v-loading="listMembersLoading"
          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
          :loading="searchLoading"
          :disabled="searchDisabled"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>

        <el-button
          v-if="buttonPermissions.includes('bd:lead:list:add')"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          新增BD Lead
        </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 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="用户" align="center" min-width="200">
          <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="区域" align="center" min-width="60" />
        <el-table-column prop="bdQuantity" label="BD数量" align="center" min-width="100" />
        <el-table-column v-if="buttonPermissions.includes('bd:lead:list:edit')" prop="contact" label="联系方式" align="center" min-width="100" />
        <el-table-column prop="createUserName" label="创建人" align="center" min-width="100" />
        <el-table-column prop="createTime" label="创建时间" 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="操作" 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:lead:list:add:member')" @click.native="bindBd(scope.row, scope.$index)">增加子级BD</el-dropdown-item>
                <el-dropdown-item v-if="buttonPermissions.includes('bd:lead:list:edit')" @click.native="clickEdit(scope.row, scope.$index)">编辑</el-dropdown-item>
                <el-dropdown-item v-if="buttonPermissions.includes('bd:lead:list:del')" @click.native="handlDel(scope.row.id, scope.$index)">删除</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"
      />

      <lead-add-bd
        v-if="addBdVisible"
        :row="thisRow"
        @success="addBdSuccess"
        @close="addBdVisible=false;"
      />

      <bind-bd
        v-if="teamBindDrawerVisible"
        :row="thatRow"
        @success="teamBindSuccess"
        @close="teamBindDrawerVisible=false"
      />

    </div>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { copyText } from '@/utils'
import { pageBdLead, deleteBdLead } from '@/api/room-anchor'
import { mapGetters } from 'vuex'
import { listMembers } from '@/api/team'
import LeadAddBd from './add-bd-lead'
import bindBd from './bind-bd'

export default {
  name: 'BdLead',
  components: {
    Pagination,
    LeadAddBd,
    bindBd
  },
  data() {
    return {
      teamBindDrawerVisible: false,
      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: '',
        sysOrigin: 'HALAR',
        createUser: ''
      },
      listLoading: false,
      listMembersLoading: false,
      searchLoading: false,
      backUserConditionVisible: false
    }
  },
  computed: {
    ...mapGetters(['uid', 'buttonPermissions', 'permissionsSysOriginPlatforms', 'permissionsFirstSysOrigin']),
    showOperationCol() {
      return this.buttonPermissions.includes('bd:lead:list:edit') ||
        this.buttonPermissions.includes('bd:lead:list:add:bind') ||
        this.buttonPermissions.includes('bd:lead:list:del') ||
        this.buttonPermissions.includes('bd:lead:list:add:member')
    }
  },
  watch: {
    buttonPermissions: {
      handler(newVal) {
        this.renderData(true)
      },
      immediate: true
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.loadMembers()
    that.listQuery.sysOrigin = querySystem.value
    that.renderData(true)
    this.listQuery.createUser = that.buttonPermissions.includes('select:all:bd:lead') ? null : this.uid
  },
  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
      pageBdLead(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)
    },
    handleCreate() {
      this.textOptTitle = '创建BD Leader'
      this.thisRow = {}
      this.thisRow.sysOrigin = this.listQuery.sysOrigin
      this.addBdVisible = true
    },
    bindBd(row, _index) {
      this.thatRow = row
      this.thisRowIndex = _index
      this.teamBindDrawerVisible = true
    },
    teamBindSuccess() {
      this.list[this.thisRowIndex].bdQuantity = Number(this.list[this.thisRowIndex].bdQuantity) + 1
      this.teamBindDrawerVisible = false
    },
    addBdSuccess(form) {
      this.$opsMessage.success()
      // success('Successful')
      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: '复制成功',
          type: 'success'
        })
      }).catch(() => {
        that.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    originText(row) {
      const texts = []
      if (row.originPlatform) {
        texts.push(row.originPlatform)
      }
      if (row.originPhoneModel) {
        texts.push(row.originPhoneModel)
      }
      return texts.join('，')
    },
    handleClose() {
      this.addBdVisible = false
    },
    teamCreateSuccess() {
      this.$opsMessage.success()
      this.teamCreateVisible = false
      this.list[this.thisRowIndex].agentCount += 1
    },
    clickEdit(row, _index) {
      const that = this
      that.thisRow = row
      that.thisRowIndex = _index
      this.thisRow.sysOrigin = this.listQuery.sysOrigin
      that.textOptTitle = '编辑BD Leader'
      that.addBdVisible = true
    },
    handlDel(id, _index) {
      const that = this
      this.$confirm('您确定要删除吗(将与名下BD解除绑定, 不影响其他BD身份)?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleteBdLead(id).then(res => {
          that.$opsMessage.success()
          that.list.splice(_index, 1)
        }).catch(er => {
          that.$opsMessage.success()
        })
      }).catch(() => {})
    },
    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>
