<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">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div class="form_cnt">
      <FormMessage :formList="formData" v-model="listQuery" ref="elform" :rules="rules">
        <template #bgnr>
          <el-input v-model="listQuery.bgnr" style="width: 100%" placeholder="请输入关键字" class="input-with-select">
            <template #append>
              <el-button :icon="Search" type="primary">搜索</el-button>
            </template>
          </el-input>
        </template>
        <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="outRow.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 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 } from "@/api/huiShangyp/tacticalApi.js"

const emit = defineEmits(["updateDate", 'ok']);
const props = defineProps({
  dic: Object,
});


const ConsultationShow = ref(false)
const showText = ref(false);
const textContent = ref()
const { proxy } = getCurrentInstance();
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: "bgnr", type: "slot", width: "100%", blur: setEditorTextContent },
  // { label: "附件内容", prop: "fj", type: "slot", width: "100%" },
]);
const listQuery = ref({
  bgmc: "",
  bgnr: "",
  fj: ""
}); //表单
const loading = ref(false);
const elform = ref();
const title = ref("");
/** 外面行数据 */
const outRow = ref({})


// 初始化数据
const init = (type, reportData, row) => {

  listQuery.value = {
    bgmc: reportData.bgmc,
    bgnr: reportData.bgnr,
    id: reportData.id,
    // fj: reportData.fj
  }
  outRow.value = { ...row }
  dialogForm.value = true;
  title.value = type == "add" ? "新增" : "编辑";
  setEditorTextContent()
};
const getText = (val, row = {}) => {
  listQuery.value.fj = val.text;
  setEditorTextContent()
}

function setEditorTextContent() {
  let html = dataBt.value;


  html += `<p style="text-align: center;"><span style="font-size: 22px;">${listQuery.value.bgmc || ''}</span></p>`
  html += `<p>${listQuery.value.fj || ''}</p>`
  textContent.value = html
}

// watch(() => listQuery.value, (val) => {

// },
//   {
//     deep: true, immediate: true
//   })
// 提交
const submit = () => {
  elform.value.submit((data) => {
    // let url = title.value == "新增" ? "/mosty-gsxt/gsxt/jyfx/add" : "/mosty-gsxt/gsxt/jyfx/edit";

    let params = {
      ...data,
      ypid: outRow.value.id,
      ypmc: outRow.value.ypyt
    };
    const apiFun = !listQuery.value.id ? gsxtYpbgAddEntity : gsxtYpbgEditEntity
    if (!listQuery.value.id) delete params.id
    apiFun(params).then(() => {
      loading.value = false;
      proxy.$message({ type: "success", message: title.value + "成功" });
      emit("ok");
      close();
    }).catch(() => {
      loading.value = false;
    })
  });
};
//编辑器创建成功
const handleCreated = (editor) => {
  editorRef.value = editor;
};
//内容发生变化
const handChange = (editor) => {
  // 判断是否是一个空段落，是空就传空文本


};
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) editor.destroy();
});


// 关闭
const close = () => {
  listQuery.value = {};
  loading.value = false;
  dialogForm.value = false;
  listQuery.value = {}
};


// 带样式的下载方法
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>
