<template>
  <el-result
    v-if="success"
    icon="success"
    title="成功"
    sub-title="已成功调用系统打印"></el-result>
  <el-result
    v-if="error"
    icon="error"
    title="错误"
    sub-title="请求参数或者返回数据错误"></el-result>
</template>
<script setup>
  import {ElLoading, ElResult, ElMessageBox} from 'element-plus';
  import {onMounted, ref} from 'vue';
  import {hiprint, fetchAndRender} from 'yh-hiprint';

  function getQuery() {
    let query = {};
    try {
      location.hash
        .split('?')[1]
        .split('&')
        .forEach((str) => {
          let index = str.indexOf('=');
          let key = str.substring(0, index);
          let value = decodeURIComponent(str.substring(index + 1));
          switch (key) {
            case 'returnHtml':
              value = value === '1';
              break;
            case 'isCustom':
              value = value === '1';
              break;
          }
          query[key] = value;
        });
    } catch (error) {
      console.error('hiprint Preview getQuery on error:', error);
    }
    return query;
  }

  onMounted(() => {
    let query = getQuery();
    if (query.code) {
      sessionStorage.printQuery = JSON.stringify(query);
      getData(query);
    } else {
      if (sessionStorage.printQuery) {
        query = JSON.parse(sessionStorage.printQuery);
        getData(query);
      } else {
        loading.close();
        error.value = true;
      }
    }
    window.addEventListener('afterprint', () => {
      self.close();
    });
  });

  const success = ref(false);
  const error = ref(false);

  let loading = ElLoading.service({
    text: '正在加载数据……',
  });

  async function getData(query) {
    let {code, params, data, isCustom, returnHtml} = query;
    loading.setText('获取打印配置和数据');
    try {
      const result = await fetchAndRender({
        code,
        params,
        data,
        isCustom,
        onAlert: (msg) => ElMessageBox.alert(msg, '提示'),
        onPrompt: async (message, defaultValue) => {
          const res = await ElMessageBox.prompt(message, '自定义数据', {
            inputType: 'textarea',
            inputValue: defaultValue,
          });
          return res.value;
        },
      });
      if (!result) {
        error.value = true;
        return;
      }

      // returnHtml 模式：把 HTML 回传给 opener（供调用方拿到渲染结果）
      if (opener && returnHtml && result.html) {
        opener.postMessage({
          type: 'sendPrintHTML',
          data: result.html,
        });
        ElMessageBox.alert('渲染完成！确认后返回系统').then(() => {
          window.close();
        });
      } else {
        // 浏览器原生打印
        document.body.innerHTML = '';
        document.body.insertAdjacentHTML('beforeend', result.html);
        if (result.hasData) {
          setTimeout(() => {
            window.print();
          }, 1000);
        } else {
          ElMessageBox.alert('数据源没有数据，打印将取消').then(() => {
            window.close();
          });
        }
      }
      success.value = false;
    } catch (error) {
      console.error(error);
      error.value = true;
    } finally {
      if (loading) {
        loading.close();
      }
    }
  }
</script>
<style lang="scss"></style>
