<template>
    <div>
        <el-card shadow="never">
            <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
                <el-tab-pane v-if="query.type != 'view'" label="稿纸信息" name="1">
                    <MainBodyTemplate ref="mainBodyTemplate" :type="routerQuery.type" menu="notice" :disabled="disabled" @sendFiles="getFiles"></MainBodyTemplate>
                </el-tab-pane>
                <el-tab-pane label="正文" name="2">
                    <div class="editor-wrapper">
                        <div class="editor-main">
                            <div v-show="tabValue === '2'" style="min-height: 525px;">
                                <tinymce-editor v-if="tinymceConfig && tabValue === '2'" :disabled="disabled" v-model="formData.content" :init="tinymceConfig" />
                            </div>
                        </div>
                        <div class="seal-panel" v-if="isApprove">
                            <div class="seal-section">
                                <div class="panel-title">公用章</div>
                                <div class="seal-grid">
                                    <div
                                        v-for="(img, index) in publicImages"
                                        :key="'pub-' + index"
                                        class="seal-item"
                                        draggable="true"
                                        @dragstart="handleDragStart($event, img, 'public')"
                                    >
                                        <img :src="img.imgUrl" :alt="img.name" />
                                        <span class="seal-name">{{ img.name }}</span>
                                    </div>
                                    <div v-if="!publicImages.length" class="no-seal">暂无公用章</div>
                                </div>
                            </div>
                            <div class="seal-section">
                                <div class="panel-title">个人章</div>
                                <div class="seal-grid">
                                    <div
                                        v-for="(img, index) in privateImages"
                                        :key="'pri-' + index"
                                        class="seal-item"
                                        draggable="true"
                                        @dragstart="handleDragStart($event, img, 'private')"
                                    >
                                        <img :src="img.imgUrl" :alt="img.name" />
                                        <span class="seal-name">{{ img.name }}</span>
                                    </div>
                                    <div v-if="!privateImages.length" class="no-seal">暂无个人章</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="附件查看" name="3">
                  <div class="file-container">
                    <el-row :gutter="20">
                      <el-col :span="6">
                          <div class="file-item" v-for="(item, index) in fileList" :key="item.id" @click="filesOpen(item)">
                              <el-link type="primary">{{index + 1}}. {{item.name}}</el-link>
                              <span v-if="!disabled" class="delete-icon" @click="deleteFile(index)">
                                <i class="el-icon-delete"></i>
                              </span>
                          </div>
                      </el-col>
                      <el-col :span="18">
                          <iframe class="file-iframe" style="width: 100%; height: 62vh;" v-if="fileList && fileList.length > 0" :src="currentFileUrl" frameborder="0" allowfullscreen="true"></iframe>
                      </el-col>
                    </el-row>
                  </div>
                </el-tab-pane>
                <el-tab-pane v-if="formData?.processInstanceId && !isApprove && query.type != 'view'" label="流程详情" name="4">
                     <bpmDetail
                        v-if="formData.processInstanceId"
                        :id="formData.processInstanceId"
                      ></bpmDetail>
                </el-tab-pane>
            </el-tabs>
            <div v-if="!disabled" class="footer">
                <el-button type="primary" @click="save(0)" v-click-once>保存</el-button>
                <el-button type="primary" @click="save(1)" v-click-once>提交</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-card>
        <process-submit-dialog
          :processSubmitDialogFlag.sync="processSubmitDialogFlag"
          v-if="processSubmitDialogFlag"
          ref="processSubmitDialogRef"
          @reload="cancel"
        ></process-submit-dialog>
    </div>
</template>
<script>
import MainBodyTemplate from '@/views/bpm/documents/documentTemplate/components/mainBodyTemplate.vue'
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import { docTplTemplateById  } from '@/api/documents/doc-manage';
import { noticeDocumentCreateAPI, noticeDocumentByIdAPI, noticeDocumentUpdateAPI } from '@/api/documents/noticeIssuance/index.js';
import bpmDetail from '@/views/bpm/processInstance/detailNew.vue';
import { queryIds } from '@/components/addDoc/api/index'
import { getCode } from '@/api/codeManagement';
import { uploadFile } from '@/api/system/file/index.js';
import processSubmitDialog  from '@/BIZComponents/enventSubmitDialog/processSubmitDialog'
import { setFileUrl } from '@/components/addDoc/util.js'
import { getSealPage } from '@/api/bpm/components/sealManagement';
import { getUserDetail } from '@/api/system/organization/index';
export default {
  components: {
    MainBodyTemplate,
    TinymceEditor,
    bpmDetail,
    processSubmitDialog
  },
  props: {
    query: {
      default: () => {
        return {
          id: '',
          type: ''
        }
      }
    },
    isApprove: {
      default: false
    }
  },
  data() {
    return {
      drawer: false,
      businessId: '',
      processSubmitDialogFlag: false,
      currentFileUrl: '',
      tabValue: '1',
      formData: {
        code: '',
        name: '',
        status: true,
        content: '',
        fields: [],
      },
      fileList: [],
      publicImages: [],
      privateImages: [],
      sealsFetched: false,
      tinymceConfig: {
        height: 525,
        resize: false,
        autoresize_bottom_margin: 0,
        auto_focus: false,
        scroll_padding: 0,
        scroll_padding_bottom: 0,
        images_upload_handler: (blobInfo, success, error) => {
          const file = blobInfo.blob();
          console.log('file~~~', file);
          // 判断 file 是否为有效的文件对象
          if (!file || !(file instanceof File) || file.size === 0) {
            return;
          }
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          uploadFile({
                module: 'main',
                multiPartFile: file
            }).then((res) => {

                if (res.data) {
                  console.log('images_upload_handler~~~', res);
                  success(res.data.url);
                } else {
                  error(res.message);
                }
            }).catch(error => {
                this.$message.error('文件上传失败');
            });
        },
        setup: (editor) => {
          editor.on('init', () => {
            // 查看详情/只读模式下不注册任何拖拽事件
            // if (this.disabled) return;

            const body = editor.getBody();
            const win = editor.getWin();
            let dragState = null;
            let pendingImg = null;
            let pendingSx = 0, pendingSy = 0;
            const THRESHOLD = 5;

            /* ===== 1. 从外部签章面板拖入编辑器 ===== */
            body.addEventListener('dragover', (e) => {
              e.preventDefault();
              e.dataTransfer.dropEffect = 'copy';
            }, true);

            body.addEventListener('drop', (e) => {
              e.preventDefault();
              e.stopPropagation();
              const imageData = e.dataTransfer.getData('imageData');
              if (!imageData) return;
              try {
                const data = JSON.parse(imageData);
                const rect = body.getBoundingClientRect();
                const x = e.clientX - rect.left + body.scrollLeft;
                const y = e.clientY - rect.top + body.scrollTop;

                let w = 200, h = 200;
                if (data.sealType === 'private') { w = 210; h = 'auto'; }

                const imgHtml = `<img src="${data.url}" class="seal-drag-img"
                  style="position:absolute;left:${Math.max(0, x)}px;top:${Math.max(0, y)}px;width:${w}px;height:${h}px;cursor:move;z-index:10;"
                  data-seal-type="${data.sealType}" data-seal-name="${data.name}" />`;

                editor.undoManager.transact(() => {
                  editor.execCommand('mceInsertContent', false, imgHtml);
                });
                this.$message({ showClose: true, message: '已插入签章', type: 'success' });
              } catch (err) {
                console.error('签章插入失败:', err);
              }
            }, true);

            /* ===== 2. 编辑器内拖动签章图片 ===== */
            body.addEventListener('mousedown', (e) => {
              const target = e.target;
              if (!target || !target.closest) return;
              const img = target.closest('img.seal-drag-img');
              if (!img) return;
              e.preventDefault();
              e.stopPropagation();
              pendingImg = img;
              pendingSx = e.clientX;
              pendingSy = e.clientY;
            }, true);

            win.addEventListener('mousemove', (e) => {
              if (pendingImg && !dragState) {
                const dx = e.clientX - pendingSx;
                const dy = e.clientY - pendingSy;
                if (Math.abs(dx) > THRESHOLD || Math.abs(dy) > THRESHOLD) {
                  dragState = {
                    img: pendingImg,
                    sx: pendingSx,
                    sy: pendingSy,
                    sLeft: parseFloat(pendingImg.style.left) || 0,
                    sTop: parseFloat(pendingImg.style.top) || 0
                  };
                  pendingImg = null;
                  dragState.img.style.cursor = 'grabbing';
                  body.style.userSelect = 'none';
                }
              }
              if (!dragState) return;
              e.preventDefault();
              dragState.img.style.left = (dragState.sLeft + e.clientX - dragState.sx) + 'px';
              dragState.img.style.top  = (dragState.sTop  + e.clientY - dragState.sy) + 'px';
            });

            win.addEventListener('mouseup', () => {
              if (dragState) {
                dragState.img.style.cursor = 'move';
                body.style.userSelect = '';
                dragState = null;
              }
              pendingImg = null;
            });

            body.addEventListener('mouseleave', () => {
              if (dragState) {
                dragState.img.style.cursor = 'move';
                body.style.userSelect = '';
                dragState = null;
              }
              pendingImg = null;
            });
          });
        }
      },
    }
  },
  created() {
    // this.routerQuery = this.isApprove ? this.query : this.$route.query;
    this.routerQuery = this.query;
    this.tabValue = this.query.type == 'view' ? '3' : '1';
    console.log('this.query~~~', this.query);
    this.$nextTick(() => {
      this.getDetail();
    })
 
  },
  computed: {
    disabled() {
      return this.routerQuery.type == 'detail' || this.routerQuery.type == 'view';
    },
  },
  methods: {
    // openDrawer(query) {
    //   this.routerQuery = this.isApprove ? this.query : query;
    //   this.drawer = true;
    //   this.$nextTick(() => {
    //     this.getDetail();
    //   })
    // },
    filesOpen(item) {
      this.currentFileUrl = setFileUrl(item);
      console.log('currentFileUrl~~~', this.currentFileUrl);
    },
    async getFiles(ids) {
      if(ids) {
        let res = await queryIds({ ids: "'" + ids + "'" });
        this.fileList = res || [];
        this.filesOpen(res?.[0] || '');
      }
    },
    deleteFile(index) {
      this.fileList.splice(index, 1);
      this.$refs.mainBodyTemplate.setFiles(this.fileList);
      this.filesOpen(this.fileList.length > 0 ? this.fileList[0] : '');
    },
    async getDetail() {
      const requestUrl = this.routerQuery.type == 'add' ? docTplTemplateById : noticeDocumentByIdAPI;
      let res = await requestUrl(this.routerQuery.id);

      this.businessId = this.routerQuery.type == 'add' ? '' : res.id;
      console.log('type~~~', this.routerQuery.type);
      // 如果是新增，将发文编号设置到 fields 中
      if (this.routerQuery.type == 'add' && res.fields) {
        const documentNumberField = res.fields.find((item) => item.fieldKey == 'documentNumber');
        if (documentNumberField) {
          documentNumberField.defaultValue = await getCode('fm_document_number_code');
          console.log('documentNumberField~~~', documentNumberField, await getCode('fm_document_number_code'));
        }
      }
      
      this.formData = res;
      
      let ids =this.formData.fields.find((item) => item.fieldKey == 'attachments')?.defaultValue || '';
      this.getFiles(ids);
      console.log(this.formData, this.$refs.mainBodyTemplate);
      this.$nextTick(() => {
        this.$refs.mainBodyTemplate && this.$refs.mainBodyTemplate.setData(this.formData.fields);
      })
    },
    async getTemplateDetail() {
      let res = await docTplTemplateById(this.routerQuery.id);
      // res.status = res.status == 1 ? true : false;
      this.formData = res;
      let ids =this.formData.fields.find((item) => item.fieldKey == 'attachments')?.defaultValue || '';
      this.getFiles(ids);
      console.log(this.formData, this.$refs.mainBodyTemplate);
      this.$refs.mainBodyTemplate.setData(this.formData.fields);
    },
    handleTabClick(tab) {
      this.tabValue = tab.name;
      // 切换到「正文」Tab 时加载签章
      if (tab.name === '2' && !this.sealsFetched) {
        this.sealsFetched = true;
        this.fetchSeals();
      }
    },
    /* 获取签章列表 */
    async fetchSeals() {
      try {
        const userId = this.$store?.state?.user?.info?.userId;
        // 公用章
        getSealPage({
          size: 999,
          pageNum: 1,
          status: 1,
          approvalStatus: 2,
          sealHolderId: userId
        }).then((res) => {
          this.publicImages = res.list || [];
        }).catch(() => {});
        // 个人章（签名）
        if (userId) {
          getUserDetail(userId).then((res) => {
            if (res.signature?.[0]) {
              this.privateImages = [{
                imgUrl: res.signature[0].url,
                name: res.name
              }];
            }
          }).catch(() => {});
        }
      } catch (e) {
        console.error('获取签章失败:', e);
      }
    },
    /* 签章拖拽开始，写入 imageData */
    handleDragStart(e, img, type) {
      const data = {
        url: img.imgUrl,
        name: img.name,
        imgId: type === 'public' ? img.id : '',
        sealType: type
      };
      e.dataTransfer.setData('imageData', JSON.stringify(data));
      e.dataTransfer.effectAllowed = 'copy';
    },
    async save(type) {
      try {
        // 校验子组件 mainBodyTemplate 的必填项
        const mainBodyValid = await this.$refs.mainBodyTemplate.$refs.form.validate().catch(() => false);
        if (!mainBodyValid) {
          this.$message.warning('请完善稿纸信息的必填项');
          return;
        }

        // 获取自定义字段数据
        const customFields = this.$refs.mainBodyTemplate.generateCustomFields();

        // 将 customFields 放到 formData 字段
        this.formData.fields = customFields;

        this.formData.status = this.formData.status ? 1 : 0;

        if(this.routerQuery.type == 'add') {
          this.formData.templateId = this.formData.id;
          delete this.formData.id;
        }

        console.log('提交数据:', this.formData);

        // 提交到后端
        const loading = this.$loading({ lock: true });
        const requestUrl = this.routerQuery.type == 'add' ? noticeDocumentCreateAPI : noticeDocumentUpdateAPI;
   
        requestUrl(this.formData)
          .then((res) => {
            if(type == 1) {
              loading.close();
              this.submit(res);
            }else {
              loading.close();
              this.$message.success('保存成功');
              this.cancel();
            }
          })
          .catch((e) => {
            loading.close();
            console.error('保存失败:', e);
          });

      } catch (error) {
        console.error('保存异常:', error);
      }
    },

    async submit(res) {
        const data = await noticeDocumentByIdAPI(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
              businessId: data.id,
              businessKey: 'fm_notice_document_approval',
              formCreateUserId: data.createUserId,
              variables: {
                businessCode: data.docNo,
                businessName: data.title,
                businessType: '通知公文'
              }
            };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },

    cancel() {
      this.tabValue = '1';
      this.$emit('done');
    },
  }
}
</script>
<style scoped>
.el-card {
  min-height: 600px;
}
.footer {
  text-align: center;
  margin-top: 20px;
}

.file-container {
  padding: 20px;
}
.file-item {
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.delete-icon {
  color: red;
  cursor: pointer;
  margin-left: 20px;
}
/* 编辑器 + 签章面板布局 */
.editor-wrapper {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}
.editor-main {
  flex: 1;
  min-width: 0;
}
.seal-panel {
  flex: 0 0 200px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 12px;
  max-height: 525px;
  overflow-y: auto;
}
.seal-section {
  margin-bottom: 12px;
}
.seal-section:last-child {
  margin-bottom: 0;
}
.panel-title {
  font-weight: 600;
  font-size: 13px;
  color: #0f172a;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #e2e8f0;
}
.seal-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}
.seal-item {
  background: #fff;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  padding: 6px;
  cursor: grab;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.seal-item:hover {
  border-color: #3b82f6;
  background: #eff6ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59,130,246,0.15);
}
.seal-item:active {
  cursor: grabbing;
}
.seal-item img {
  width: 100%;
  height: 60px;
  object-fit: contain;
  pointer-events: none;
  border-radius: 4px;
  background: #f1f5f9;
}
.seal-name {
  font-size: 11px;
  color: #64748b;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}
.no-seal {
  grid-column: 1 / -1;
  text-align: center;
  color: #94a3b8;
  font-size: 12px;
  padding: 12px 0;
}
</style>
