import '@/types/Store/Shopee/Keyword';
import { mapActions } from 'vuex';
import { apiKeywordRemove, apiKeywordUpdate } from '@/api/autoshopee/shopee/keyword';
import { extractKeywordLine } from '@/lib/utils/utils';
import { tableKeywordColumn } from './Data';
import SelectKeywordType from '@/vue/components/Use/Shopee/SelectKeywordType.vue';

import { defineComponent } from '@vue/composition-api';

export default defineComponent({
  props: {
    collectionId: {
      type: String,
      require: true,
    },
  },
  components: {
    'select-keyword-type': SelectKeywordType,
  },
  data() {
    return {
      loadingData: false,
      formAdd: {
        input: '',
        list: [],
        keyword: '',
        price: 0,
      },
      tableKeyword: {
        column: tableKeywordColumn,
        data: [],
        loading: false,
      },
    };
  },
  methods: {
    ...mapActions(['ShopeeKeywordGet']),
    async getDetail() {
      this.tableKeyword.loading = true;

      this.tableKeyword.data = (await this.ShopeeKeywordGet(this.collectionId)).map((item, index) => {
        return {
          ...item,
          index: index + 1,
        };
      });

      this.tableKeyword.loading = false;
    },
    async addKeyword({ keyword, price }) {
      keyword = keyword.trim();
      const isExist = this.tableKeyword.data.some((item) => item.keyword === keyword);

      if (isExist) {
        return this.$Message.error(this.$t('KEYWORD_ADD_WAS_EXIST', { keyword }));
      }

      this.formAdd.loading = true;

      const keywordData = await this.ShopeeKeywordAdd({
        collectionId: this.collectionId,
        keyword,
        price,
      });

      keywordData.loading = false;
      keywordData.index = this.tableKeyword.data.length + 1;
      this.tableKeyword.data.push(keywordData);

      this.formAdd.loading = false;

      this.$Message.success(this.$t('KEYWORD_ADD_SUCCESS', { keyword }));
    },
    handleSubmit() {
      this.addKeyword(this.formAdd);
    },
    handlerInput() {
      const listInput = extractKeywordLine(this.formAdd.input);

      listInput.forEach((item) => this.addKeyword(item));
    },
    async onChange(row, key) {
      const keywordId = row._id;
      const value = row[key];
      apiKeywordUpdate(keywordId, {
        [key]: value,
      });
    },
    onRemove(row) {
      const keywordId = row._id;
      this.$Modal.confirm({
        content: this.$t('REMOVE_CONFIRM'),
        title: row.keyword,
        onOk: async () => {
          this.$Message.success(this.$t('REMOVE_SUCCESS'));
          this.tableKeyword.data = this.tableKeyword.data.filter((item) => item._id !== keywordId);

          apiKeywordRemove(keywordId);
        },
      });
    },
  },
  created() {
    this.getDetail();
  },
  computed: {
    addBtnActive() {
      return this.formAdd.keyword && Number(this.formAdd.price);
    },
  },
});
