<template>
  <view class="render-box shadow-lg">
    <view
      class="render-content"
      :id="`render-${pluginTaskId}`"
      :data-did="task.detailId"
      :data-param="param"
      :data-pdu="task.planDuration"
      :data-pid="projectId"
      :data-pstart="task.planStart"
      :data-rdu="task.realDuration"
      :data-rid="roleId"
      :data-tid="task.id"
      :data-tname="task.name"
      :data-token="token"
      :data-rstart="task.realStart"
      :data-uid="userId"
      :prop="pluginInfo"
      :change:prop="projectRender.renderDom"
    ></view>
  </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex';

export default {
  name: 'RenderHtmlFragment',
  props: {
    task: { default: () => {}, type: Object },
    pluginId: { default: '1', type: String },
    styleType: { default: 0, type: Number },
    pluginTaskId: { default: '', type: String },
    businessPluginId: { default: '', type: String },
    param: { type: String, default: '' },
  },
  data() {
    return {
      pluginInfo: null,
    };
  },
  computed: {
    ...mapState(['allPlugin', 'businessPlugin']),
    ...mapState('role', ['roleId']),
    ...mapState('user', ['token']),
    ...mapGetters('project', ['projectId']),
    ...mapGetters('user', ['userId']),
  },

  async mounted() {
    await this.getPlugin();
    if (this.param && this.pluginInfo) {
      let configParam = JSON.parse(this.param);
      this.pluginInfo.config = `var p${this.pluginId}_config = ${this.param}`;
    } else {
      await this.getConfig();
    }
  },
  methods: {
    getPlugin() {
      const allPlugin = this.allPlugin || uni.$storage.getStorageSync('allPlugin');
      if (allPlugin && JSON.parse(allPlugin)) {
        // 有本地数据
        try {
          const pluginLists = JSON.parse(allPlugin);
          // pluginLists 可能没有find方法,交给catch处理
          const pluginTarget = pluginLists.find(item => item.id === this.pluginId);
          pluginTarget.pluginTaskId = this.pluginTaskId;
          this.pluginInfo = pluginTarget || null;
        } catch (error) {
          console.error('error: ', error);
          this.pluginInfo = null;
        }
      } else {
        // 没有本地数据 API 查询
        const params = { businessPluginId: this.businessPluginId };
        uni.$catchReq.getOtherPlugin(params, (err, res) => {
          if (err) {
            console.error('err: ', err);
            this.pluginInfo = null;
          } else {
            res.pluginTaskId = this.pluginTaskId;
            this.pluginInfo = res || null;
          }
        });
      }
    },

    getConfig() {
      const businessPlugin = this.businessPlugin || uni.$storage.getStorageSync('businessPlugin');
      if (businessPlugin && JSON.parse(businessPlugin)) {
        // 有本地数据
        const businessPluginLists = JSON.parse(businessPlugin);
        businessPluginLists.forEach(item => {
          if (item.pluginConfigs) {
            const pluginConfig = item.pluginConfigs.find(plugin => plugin.businessPluginId === this.businessPluginId);
            if (pluginConfig && pluginConfig.config && this.pluginInfo) {
              this.pluginInfo.config = pluginConfig.config;
            }
          }
        });
      } else {
        // 没有本地数据 API 查询
        // const params = { businessPluginId: this.businessPluginId };
        // uni.$catchReq.getOtherPlugin(params, (err, res) => {
        //   if (err) {
        //     console.error('err: ', err);
        //     this.pluginInfo = null;
        //   } else {
        //     this.pluginInfo = res || null;
        //   }
        // });
      }
    },
  },
};
</script>

<script module="projectRender" lang="renderjs">
// TODO: 未处理配置 多次使用插件的复用
let pluginTaskId = '';

export default {
  methods: {

    /**
     * 渲染dom
     * @param {object|null} res 插件详情 监听的pluginInfo
     */
    renderDom(res) {
      if (!res) return;
      this.$nextTick(() => {
        if (res.html) {
          // 注意: 截止目前版本2022年1月30日 直接this.pluginTaskId在APP端是不能行的
          // 已向官方提交bug 后期等待修复后 再做调整
          const content = window.document.getElementById(`render-${res.pluginTaskId}`);
          content.innerHTML = res.html;
        }

        if (res.config) {
          const script_config = window.document.createElement('script');
          script_config.innerHTML = res.config;
          window.document.body.appendChild(script_config);
        }

        if (res.js) {
          const script_js = window.document.createElement('script');
          script_js.innerHTML = res.js;
          window.document.body.appendChild(script_js);
        }
      })
    },

    /**
     * 从prop data中拿到pluginTaskId, 存入变量中
     * 因为目前这里没办法通过this拿到prop data下的数据
     * @param {string} propsPluginTaskId
     */
    // initPluginTaskId(propsPluginTaskId) {
    //   pluginTaskId = propsPluginTaskId;
    // }
  },
};
</script>

<style scoped lang="scss">
.render-box {
  border-radius: 8px;
  background: #fff;
  padding: 16px;
  overflow: hidden;
}

button {
  border: none !important;
}
</style>
