import "./index.css";
import _Promise from "@babel/runtime-corejs2/core-js/promise";
import "core-js/modules/web.dom.iterable";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import get from 'lodash/get';
import { createComponentName, componentMixin } from '../../utils/base';
import { clickOutside } from '../../utils/dom';
import MenuBar from './menu-bar';
import Tips from '../tips';
import Content from './content';
import request from '../../service/request';
const __vue_script__ = {
  name: createComponentName('editor-help'),
  components: {
    MenuBar,
    Content
  },
  mixins: [componentMixin],
  model: {
    name: 'value',
    event: 'change'
  },
  props: {
    // 是否可以见,可以通过 v-model 绑定
    value: {
      type: Boolean,
      default: false
    },
    // udesk 配置
    udeskConfig: {
      type: Object,
      default: () => ({})
    },
    // 展示未读消息
    unread: {
      type: Boolean,
      default: true
    },
    // 哪个位置的帮助内容
    position: {
      type: Number,
      // 2: 抠图编辑器
      default: 2
    }
  },

  data() {
    return {
      list: [],
      articleContentMap: {},
      articleStatusMap: {},
      articleId: null,
      loadContent: false
    };
  },

  computed: {
    content() {
      if (!this.articleId) return null;

      if (this.articleContentMap[this.articleId]) {
        return this.articleContentMap[this.articleId].content;
      }

      return null;
    }

  },
  watch: {
    articleId(value) {
      if (!value) return;
      this.getArticle(value);
    }

  },

  mounted() {
    this.getArticles();
    clickOutside(this.$el, this.onClose);
  },

  methods: {
    onClose() {
      if (this.value) {
        // value 变化触发
        // @arg (value: boolean)
        this.$emit('change', false);
      }
    },

    async getArticles() {
      try {
        const res = await request.get('/api/articles', {
          params: {
            positions: this.position,
            type: 'help'
          }
        });
        this.list = res.data;
      } catch (error) {
        Tips(error);
      }
    },

    async getArticle(id) {
      this.loadContent = true;
      await _Promise.all([this.getArticleContent(id), this.getArticleLikeStatus(id)]);
      this.loadContent = false;
    },

    async getArticleContent(id) {
      if (this.articleContentMap[id]) {
        return this.articleContentMap[id];
      } else {
        this.$set(this.articleContentMap, id, null);
        const res = await request.get('/api/articles/' + id);
        this.articleContentMap[id] = res.data;
      }
    },

    async changeArticle(status) {
      let lastStatus = this.articleStatusMap[this.articleId].status;
      this.articleStatusMap[this.articleId].status = 'on' + status;

      try {
        if (lastStatus && lastStatus.indexOf(status) === 0) {
          await this.deleteArticleStatus();
        } else {
          const res = await request.post(`/api/articles/${this.articleId}/likes`, {
            status: status === 'praise' ? 1 : 0
          });
          this.articleStatusMap[this.articleId] = {
            status,
            id: res.data.id
          };
        }
      } catch (error) {
        Tips(error);
        const id = get(this.articleStatusMap, `${this.articleId}.id`, null);
        this.articleStatusMap[this.articleId] = {
          status: lastStatus + 'error',
          id
        };
      }
    },

    async deleteArticleStatus() {
      await request.delete(`api/articles/${this.articleId}/likes/${this.articleStatusMap[this.articleId].id}`);
      this.articleStatusMap[this.articleId] = {
        status: null,
        id: null
      };
    },

    async getArticleLikeStatus(id) {
      const res = await request.get(`/api/articles/${id}/likes`);
      let status = get(res.data, '0.status', null);

      if (status === 0) {
        status = 'blame';
      } else if (status === 1) {
        status = 'praise';
      }

      this.$set(this.articleStatusMap, this.articleId, {
        status,
        id: get(res.data, '0.id', null)
      });
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("transition", {
    attrs: {
      name: "editor-help-slide-fade"
    }
  }, [_c("div", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.value,
      expression: "value"
    }],
    class: _vm.bem({
      active: this.articleId
    })
  }, [_c("MenuBar", {
    attrs: {
      unread: _vm.unread,
      udeskConfig: _vm.udeskConfig,
      list: _vm.list
    },
    model: {
      value: _vm.articleId,
      callback: function ($$v) {
        _vm.articleId = $$v;
      },
      expression: "articleId"
    }
  }, [_vm._t("footer")], 2), _vm._v(" "), _c("transition", {
    attrs: {
      name: "editor-help-fade"
    }
  }, [!_vm.loadContent && _vm.articleId ? _c("Content", {
    attrs: {
      status: _vm.articleStatusMap[_vm.articleId].status,
      content: _vm.content,
      id: _vm.articleId
    },
    on: {
      clickPraise: function ($event) {
        _vm.changeArticle("praise");
      },
      clickBlame: function ($event) {
        _vm.changeArticle("blame");
      }
    }
  }) : _vm._e()], 1)], 1)]);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../../utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);