<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 v-show="tabValue === '2'" style="min-height: 525px;">
                        <tinymce-editor v-if="tinymceConfig && tabValue === '2'" :disabled="disabled" v-model="formData.content" :init="tinymceConfig" />
                     </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'
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: [],
      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('文件上传失败');
            });
        }
      },
    }
  },
  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;
    },
    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;
}
</style>
