<template>
  <div class="layout-no-cols" @keyup.enter="getFansList">
    <el-toolbar align="left">
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button @click="isShowModal=true" :disabled="selectedFans.length==0||tagList.length==0" type="button" class="el-button el-button--default "
        priv="SocialMedia.FansManage.Lable">
        <span>
          <i class="fa fa-tag"></i>打标签</span>
      </el-button>
      <el-button @click="removeFans" :disabled="!tagID||selectedFans.length==0" type="button" class="el-button el-button--default "
        priv="SocialMedia.FansManage.Remove">
        <span>
          <i class="fa fa-remove"></i>从当前标签移除粉丝</span>
      </el-button>
      <el-button @click="addTag" type="button" class="el-button el-button--default " priv="SocialMedia.FansManage.Tag_Add">
        <span>
          <i class="fa fa-plus"></i>新建标签</span>
      </el-button>
      <el-button @click="editTag" :disabled="!tagID" type="button" class="el-button el-button--default " priv="SocialMedia.FansManage.Tag_Edit">
        <span>
          <i class="fa fa-edit"></i>修改当前标签</span>
      </el-button>
      <el-button @click="delCurTag" :disabled="!tagID" type="button" class="el-button el-button--default " priv="SocialMedia.FansManage.Tag_Delete">
        <span>
          <i class="fa fa-remove"></i>删除当前标签</span>
      </el-button>
      <el-button @click="syncTags" type="button" class="el-button el-button--default " priv="SocialMedia.FansManage.Tag_Sync">
        <span>
          <i class="fa fa-refresh"></i>同步标签信息</span>
      </el-button>
    </el-toolbar>
    <el-row class="row-bg">
      <el-col :span="14" style="line-height:50px;">
        标签：
        <el-select class="" v-model="tagID" @change="getFansList">
          <el-option key="key_" value="" :label="tagLable('全部',tagFansTotal)"></el-option>
          <el-option v-for="item in tagList" :key="'key_'+item.ID" :value="item.ID" :label="tagLable(item.tagName,item.FCount)"></el-option>
        </el-select>
      </el-col>
      <el-col :span="10"   class="dropdown-search-box-r search-bar-algin-toolbar">
        <el-input v-model="nickname" placeholder="请输入粉丝名称" @keyup.enter.native="getFansList" size="medium">
          <el-select placeholder="性别" clearable slot="prepend" v-model="sex" @change="getFansList">
            <el-option v-for="item in genderList" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-input>
        <span class="search-icon"><i class="fa fa-search" @click="getFansList" title="查询"></i></span>
      </el-col>
    </el-row>
    <el-list-view ref="multipleTable" :data-read-url="getFansData" :page-size="20" :layout="listLayout" :selectable="true">
      <template slot-scope="row">
        <div class="panel-card" @click="listclick(row)">
          <el-row :gutter="20" align="middle" type="flex">
            <el-col :span="3" class="item-logo-ct">
              <div class="HeadImage" :style="{backgroundImage:'url('+row.headImgUrl+'),url(assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png)'}"></div>
            </el-col>
            <el-col :span="20" class="item-info-ct">
              <el-row>
                <el-col :span="8" class="item-logo-ct">
                  粉丝昵称：{{row.remark?row.remark+'（'+row.nickName+'）':row.nickName}}
                  <el-button @click="setRemark(row)" type="text" class="el-button" priv="SocialMedia.FansManage.NickName" title="设置备注">
                    <i class="fa fa-bookmark"></i>
                  </el-button>
                </el-col>
                <el-col :span="8" class="item-logo-ct">
                  性别:{{row.sex | decodeGender}}
                </el-col>
                <el-col :span="8" class="item-logo-ct">
                  城市：{{row.city}}
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8" class="item-logo-ct">
                  关注时间：{{row.subTime | fixDateTime}}
                </el-col>
                <el-col :span="8" class="item-logo-ct">
                  关注来源：{{subscribeMap[row.subscribeScene]}}
                </el-col>
                <el-col :span="8" class="item-logo-ct">
                  历史消息:
                  <router-link :to="{path:`/socialmedia/fansMsgHistory/${row.openID}`,query:{'accountID':accountID}}">查看消息</router-link>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" class="item-logo-ct">
                  标签：{{row.TagNames}}
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-list-view>
    <el-dialog title="给选中粉丝打标签" :append-to-body="true" :visible.sync="isShowModal">
      选择标签
      <el-checkbox-group v-model="checkedtag" :min="1">
        <el-checkbox v-for="(tag,index) in tagList" :checked="index==0" :label="tag.tagID" :key="tag.tagID">{{tag.tagName}}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer">
        <el-button @click="isShowModal = false">取 消</el-button>
        <el-button type="primary" v-loading="submitLoading" @click="setTagToFans">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  filters: {
    decodeGender: function(val) {
      switch (val) {
        case 1:
          return '男'
        case 2:
          return '女'
        case 0:
          return '未知'
        default:
          return val
      }
    },
    fixDateTime: function(val) {
      return val ? util.formatDate(val, 'yyyy-MM-dd HH:mm') : '　'
    }
  },
  props: {
    aid: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      submitLoading: false,
      isShowModal: false,
      checkedtag: [],
      accountID: this.$route.query.accountID,
      listLayout: 'list',
      nickname: '',
      sex: '',
      tagID: '',
      sort: '',
      genderList: [{ label: '男', value: '1' }, { label: '女', value: '2' }, { label: '未知', value: '0' }],
      subscribeMap: {
        ADD_SCENE_SEARCH: '公众号搜索',
        ADD_SCENE_ACCOUNT_MIGRATION: '公众号迁移',
        ADD_SCENE_QR_CODE: '扫描二维码',
        ADD_SCENE_PROFILE_CARD: '名片分享',
        'ADD_SCENEPROFILE LINK': '图文页内名称点击',
        ADD_SCENE_PROFILE_ITEM: '图文页右上角菜单',
        ADD_SCENE_PAID: '支付后关注',
        ADD_SCENE_OTHERS: '其他'
      },
      selectedFans: [],
      tagList: [],
      tagFansTotal: 0
    }
  },
  async created() {
    this.$parent.activeMenu = '粉丝管理'
    await this.getTagList()
  },
  methods: {
    tagLable(val, count) {
      return val + '(' + count + ')'
    },
    getFansData() {
      let params = {
        nickname: this.nickname,
        sex: this.sex,
        tagid: this.tagID,
        sort: this.sort,
        aid: this.aid
      }
      return [`/ui/fans`, { params }]
    },
    getFansList() {
      this.$refs.multipleTable.getData()
    },
    async getTagList() {
      /* this.tagList=[{
            ID:1,
            tagName:'测试',
            fCount:1
          },{
            ID:2,
            tagName:'测试2',
            fCount:3
            }
        ]
        this.tagFansTotal=4 */
      try {
        let res = await axios.get('/ui/fanstags', {params: {aid: this.aid}})
        if (res.data.data) {
          this.tagList = res.data.data
          this.tagFansTotal = res.data.allfcount
        }
      } catch (e) {}
    },
    listclick(row) {
      if (this.$refs.multipleTable.selectedRows.indexOf(row) >= 0) {
        this.selectedFans.splice(this.selectedFans.indexOf(row), 1)
      } else {
        this.selectedFans.push(row)
      }
    },
    setRemark(row) {
      this.$router.push({
        path: `/socialmedia/fansRemarkForm/${row.openID}`,
        query: {
          accountID: this.accountID,
          remark: row.remark || row.nickName
        }
      })
    },
    async removeFans() {
      try {
        await this.$confirm('警告：您确认要从当前标签内移除选中粉丝吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let openIDs = this.selectedFans.reduce((p, c, i) => p + (i > 0 ? ',' : '') + c.openID, '')
        let params = {
          aid: this.accountID,
          openIDs: openIDs
        }
        let res = await axios.delete(`/ui/fanstags/${this.tagID}/fans`, { data: params })
        if (res.data.status === 1) {
          this.getTagList()
          this.getFansList()
        }
        util.showMessage(res)
      } catch (e) {
        console.warn(e)
      }
    },
    addTag() {
      this.$router.push({path: '/socialmedia/fansTagForm/new', query: { aid: this.accountID }})
    },
    editTag() {
      if (this.tagID) {
        let tag = this.tagList.find(val => val.ID === this.tagID)
        if (tag) {
          this.$router.push({path: `/socialmedia/fansTagForm/${tag.ID}`, query: { aid: this.accountID, tagName: tag.tagName }})
        }
      }
    },
    async delCurTag() {
      if (!this.tagID) {
        return
      }
      try {
        await this.$confirm('警告：您确认要删除当前标签吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/fanstags/${this.tagID}`, { data: { aid: this.accountID } })
        if (res.data.status === 1) {
          this.tagID = ''
          this.getTagList()
        }
        util.showMessage(res)
      } catch (e) {

      }
    },
    async setTagToFans() {
      try {
        this.submitLoading = true
        let openIDs = this.selectedFans.reduce((p, c, i) => p + (i > 0 ? ',' : '') + c.openID, '')
        let tagIDs = this.checkedtag.join()
        let params = {
          aid: this.accountID,
          openIDs: openIDs
        }
        let res = await axios.put(`/ui/fanstags/${tagIDs}/fans`, params)
        if (res.data.status === 1) {
          this.getTagList()
          this.getFansList()
        }
        util.showMessage(res)
      } catch (e) {
        util.showErrorMessageBox(e)
        this.submitLoading = false
        return
      }
      this.submitLoading = false
      this.isShowModal = false
    },
    async syncTags() {
      try {
        await this.$confirm('警告：您确认要同步标签信息吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put('/ui/fanstags/sync', { aid: this.accountID })
        if (res.data.status === 1) {
          this.getTagList()
        }
        util.showMessage(res)
      } catch (e) {

      }
    }
  }
}
</script>
<style>
.self-table .el-table__header .el-input {
  padding-left: 0;
}

.self-table th > .cell .el-select {
  float: right;
  padding: 0;
}
</style>
<style scoped>
.col-wrap {
  background: white;
  flex-basis: 350px;
  max-width: none;
  flex-shrink: 0;
  position: relative;
}

.content-input-wrap {
  color: #999;
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
}

.page {
  float: right;
}

.div-scroll {
  height: 350px;
  overflow: auto;
}

.search-input {
  display: inline-block;
  width: 260px;
}

.summary {
  line-height: 1.5;
  min-height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.datetime {
  text-align: right;
  color: #bbb;
}

.el-list-view.grid .item-logo-ct,
.el-list-view.grid .item-info-ct {
  float: none;
  width: 100%;
}

.el-list-view.grid .item-info-ct {
  padding: 5px 15px !important;
}

.HeadImage {
  width: 80px;
  height: 0;
  padding-bottom: 80px;
  overflow: hidden;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  margin: auto;
}
</style>
