<template>
  <div>
    <img class="icon" v-show="list.indexOf(symbol) === -1" @click="isFavorite" src="/img/icon/like.png?2" alt="极度证券">
    <img class="icon" v-show="list.indexOf(symbol) !== -1" @click="isFavorite" src="/img/icon/like_a.png?2" alt="极度证券">
  </div>
</template>
<script>
import { insertProductUser, deleteProductUser } from "@/api/user";
import { mapGetters } from "vuex";
export default {
  props: ['symbol'],
  computed: {
    ...mapGetters(["myFavoriteList"]),
    list() {
      return this.myFavoriteList.map(item => item.symbol)
    }
  },
  created () {
    this.getProductUserList()
  },
  methods: {
    getProductUserList() {
      this.$store.dispatch('getProductUserList')
    },
    isFavorite() {
      var index = this.list.indexOf(this.symbol)
      if (this.isLogin) {
        if (index === -1) {
          this.insertProductUser()
        } else {
          this.deleteProductUser()
        }
      } else {
        var myFavoriteList = this.myFavoriteList
        if (index !== -1) {
          myFavoriteList.splice(index, 1)
          localStorage.removeItem('myFavoriteList')
          localStorage.setItem('myFavoriteList', JSON.stringify(myFavoriteList))
        } else {
          myFavoriteList.unshift({
            symbol: this.symbol,
            fixed: 0,
            num: 0
          })
          localStorage.setItem('myFavoriteList', JSON.stringify(myFavoriteList))
        }
        this.getProductUserList()
      }
    },
    insertProductUser() {
      insertProductUser({
        symbol: this.symbol
      }).then(res => {
        this.getProductUserList()
      }).catch(() => {})
    },
    deleteProductUser() {
      deleteProductUser({
        symbol: this.symbol
      }).then(res => {
        this.getProductUserList()
      }).catch(() => {})
    },
  }
}
</script>
<style lang="less" scoped>
.icon {
  width: 17px;
  display: block;
  cursor: pointer;
}
</style>