<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">报告{{ title }} </span>
      <div>
        <el-button type="primary" size="small" :loading="loading" @click="submit" v-if="title != '详情'">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div class="form_cnt">
      <FormMessage :formList="formData" :disabled="title == '详情'" v-model="listQuery" ref="elform" :rules="rules">
        <template #fj><el-button type="primary" @click="showText = true">附件上传</el-button></template>
      </FormMessage>
      <div class="cntBox">
        <!-- 工具栏 -->
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
          :mode="mode" />
        <!-- 编辑器 -->
        <Editor :style="`height: 480px; overflow-y: hidden`" v-model="textContent" :defaultConfig="editorConfig"
          :mode="mode" @onCreated="handleCreated" @onChange="handChange" />
      </div>
      <div v-if="listQuery.id" style="display: flex; justify-content: center;">
        <!-- <el-button style="display: block;" type="primary" @click="ConsultationShow = true">网上会商</el-button> -->
        <el-button style="display: block;" type="primary" @click="downloadWithStyles(textContent)">下载</el-button>
      </div>
    </div>
  </div>
  <!-- 文字解析 -->
  <ExtractionText v-model="showText" @change="getText"></ExtractionText>
  <!-- 网上会商 -->
  <!-- <Consultation v-model="ConsultationShow" /> -->
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { timeValidate } from '@/utils/tools.js'
import ExtractionText from "@/components/ExtractionText/index.vue";
import FormMessage from "@/components/aboutTable/FormMessage.vue";
import { qcckGet, qcckPost, qcckPut } from "@/api/qcckApi.js";
import "@wangeditor/editor/dist/css/style.css";
import { useRoute, useRouter } from 'vue-router'
// import Consultation from './consultation.vue'
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ref, defineExpose, reactive, defineEmits, getCurrentInstance, shallowRef, onBeforeUnmount, watch } from "vue";
import { gsxtYpbgAddEntity, gsxtYpbgEditEntity, gsxtYpbgId } from "@/api/huiShangyp/strategicApi.js"
const emit = defineEmits(["updateDate", 'ok']);
const { proxy } = getCurrentInstance();
const { D_BZ_YPLX } = proxy.$dict("D_BZ_YPLX")
const props = defineProps({});
const ConsultationShow = ref(false)
const showText = ref(false);
const textContent = ref()
const editorRef = shallowRef();
const dialogForm = ref(false); //弹窗
const mode = "default";
const dataBt = ref(`<p class="html_bt">
    <h4 style=\"text-align: center;\"><span style=\"color: rgb(225, 60, 57); font-size: 32px; font-family: 标楷体;\">林芝市公安局情指中心</span></h4>
    <h4 style=\"text-align: center;\"><span style=\"color: rgb(225, 60, 57); font-size: 32px; font-family: 标楷体;\">研判专刊（初稿）</span></h4></p>
      <p style="text-align: center;"><span style="color: rgb(225, 60, 57); font-size: 22px; font-family: 标楷体;">市公安局情指中心编</span></p>
      <p style="text-align: center;"><span style="color: rgb(225, 60, 57); font-size: 22px; font-family: 标楷体;"> ${timeValidate(new Date(), 'td')}</span></p>
      <hr/>`)
//编辑器配置
const editorConfig = {
  withCredentials: true, //允许跨域
  placeholder: props.placeholder, //提示语
  MENU_CONF: {
    uploadImage: {
      // 自定义上传图片
      async customUpload(file, insertFn) {
        let fileBlob = await compressImage(file);
        let fileData = new File([fileBlob], fileBlob.name, { type: fileBlob.type });
        if (fileData.size > 2 * 1024 * 1024) {
          ElMessage({ message: "图片超过2MB", type: "success" });
        } else {
          await uploadFn(fileData, insertFn);
        }
      }
    },
    uploadVideo: {
      // 自定义上传视频
      async customUpload(file, insertFn) {
        await uploadFn(file, insertFn);
      }
    }
  }
};

//工具配置
const toolbarConfig = {
  excludeKeys: ["blockquote", "codeBlock"] //清除不必要的工具，引用和代码块
};
const rules = reactive({
  jymc: [
    { required: true, message: "请输入经验名称", trigger: "blur" }
  ],
  fbnr: [
    { required: true, message: "请输入经验内容", trigger: "blur" }
  ]
});
const formData = ref([
  { label: "报告名称", prop: "bgmc", type: "input", width: "100%", blur: setEditorTextContent },
  {
    label: "报告类型", prop: "bglx", type: "select", width: "100%", options: D_BZ_YPLX
  },
]);
const listQuery = ref({}); //表单
const loading = ref(false);
const elform = ref();
const title = ref("");

// 初始化数据
const init = (type, row) => {
  dialogForm.value = true;
  title.value = type == "add" ? "新增" : type == "edit" ? "编辑" : "详情";


  if (row) {
    getDataById(row.id)
  }
  // listQuery.value = JSON.parse(JSON.stringify(row));

  setEditorTextContent()
};
// 根据id查询详情
const getDataById = (id) => {
  qcckGet({}, '/mosty-gsxt/gsxtYpbg/' + id).then((res) => {
    listQuery.value = res || {};
    textContent.value = res.bgnr
    // /** @type {Array<JudgmentDept>} 参与研判部门数据数组 */
    // const cyypList = Array.isArray(res.cyypList) ? res.cyypList : []
    // listQuery.value.jsdxBmDm = cyypList.map(item => {
    //   return item.ypbmdm
    // })
    // listQuery.value.jsdxBmMc = cyypList.map(item => {
    //   return item.ypbmmc
    // })
  });
};

const getText = (val) => {
  listQuery.value.fj = val.text;
  setEditorTextContent()
}

// function stripReportHeader(html) {
//   const source = typeof html === "string" ? html : "";
//   if (!source) return "";
//   const hrMatch = source.match(/<hr\b[^>]*\/?>/i);
//   if (hrMatch && typeof hrMatch.index === "number") {
//     return source.slice(hrMatch.index + hrMatch[0].length).trim();
//   }
//   if (typeof dataBt.value === "string" && source.startsWith(dataBt.value)) {
//     return source.slice(dataBt.value.length).trim();
//   }
//   return source.trim();
// }

function setEditorTextContent() {
  let html = dataBt.value;
  html += `<p style="text-align: center;"><span style="font-size: 22px;">${listQuery.value.bgnr || ''}</span></p>`
  html += `<p>${listQuery.value.fj || ''}</p>`
  textContent.value = html;
}

// 提交
const submit = () => {
  elform.value.submit(async (data) => {
    loading.value = true;
    const params = {
      ...data,
      bgnr: textContent.value
    };
    const apiFun = !listQuery.value.id ? gsxtYpbgAddEntity : gsxtYpbgEditEntity;
    if (!listQuery.value.id) delete params.id;
    try {
      await apiFun(params);
      loading.value = false;
      proxy.$message({ type: "success", message: title.value + "成功" });
      emit("ok");
      close();
    } catch (e) {
      loading.value = false;
    }
  });
};
//编辑器创建成功
const handleCreated = (editor) => {
  editorRef.value = editor;
};
//内容发生变化
const handChange = (editor) => {

  // 判断是否是一个空段落，是空就传空文本
};
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) editor.destroy();
});

const router = useRouter();
// 关闭
const close = () => {
  loading.value = false;
  dialogForm.value = false;
  listQuery.value = {}
  router.replace({ path: '/strategicResearchs' })// 移除id 避免刷新一直带参数
};


// 带样式的下载方法
const downloadWithStyles = (textContent) => {

  const wordDocument = `
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>富文本导出</title>
      <style>
        /* 应用两端对齐样式 */
        body {
          text-align: justify;
          text-justify: inter-character; /* 中文文本两端对齐 */
          font-family: "Microsoft YaHei", Arial, sans-serif;
        }
        p {
          text-align: justify;
          text-justify: inter-character;
        }
      </style>
    </head>
    <body>
      ${textContent}
    </body>
    </html>
  `;

  const blob = new Blob([wordDocument], {
    type: 'application/msword'
  });

  saveAs(blob, '战略研判报告.doc');
};

defineExpose({ init });
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.boxlist {
  width: 99%;
  margin-top: 10px;
}

::v-deep .el-textarea__inner {
  min-height: 550px !important;
}

.html_bt>>>p {
  color: red;
}

.html_bt {
  h4 {
    margin: 10px 0 !important;
  }
}

.cntBox {
  width: 80vw;
  margin: 0 auto;
}
</style>
