<template>
  <div class="workflow-add container-height">
    <Breadcrumb />
    <div class="flex-between mt10">
      <div class="flex_1 mr20">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-position="top" class="page-add">
          <div class="padding16 bg_color_fff border_radius_10 box_shadow_card"  v-show="!isFullscreen">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold"><span class="color_required font_size16">*</span>{{$t('workflowTrade.fileUpload')}}</div>
              <div class="gray999 font_size14">{{$t('workflowTrade.supportFormat')}}：JSON、YAML、ZIP（{{$t('common.maxSize')}}10MB）</div>
            </div>
            <div class="mt10">
              <el-form-item label="" prop="workflowFile">
                <!-- 上传 -->
                <FileUploader
                  ref="fileUploader"
                  accept=".json,.yaml,.yml,.zip"
                  :multiple="false"
                  :limit="1"
                  :auto-upload="true"
                  :drag="true"
                  v-model="files"
                  :tip="$t('workflowTrade.workflowFileUploadTip')"
                />
              </el-form-item>
            </div>
          </div>
          <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('common.basicInfo')}}</div>
            </div>
            <div class="mt10">
              <el-form-item :label="$t('workflowTrade.workflowTitle')" prop="workflowTitle"  v-show="!isFullscreen">
                <el-input v-model="ruleForm.workflowTitle" :placeholder="$t('workflowTrade.placeholderWorkflowTitle')"  maxlength="50" show-word-limit/>
              </el-form-item>
              <el-form-item :label="$t('workflowTrade.workflowCategory')" prop="categoryId3"  v-show="!isFullscreen">
                <el-cascader 
                  v-model="categoryIdList"
                  :options="categoryListTree"
                  :placeholder="$t('workflowTrade.placeholderWorkflowCategory')"
                  style="width:100%"
                  :props="{
                    label: 'categoryName',
                    value: 'categoryId',
                    children: 'children',
                  }"
                />
              </el-form-item>
              <el-form-item :label="$t('workflowTrade.workflowDescription')" prop="description"  v-show="!isFullscreen">
                <el-input type="textarea" 
                v-model="ruleForm.description" 
                :autosize="{ minRows: 5 }"
                :placeholder="$t('workflowTrade.placeholderWorkflowDescription')"  
                maxlength="500" show-word-limit/>
              </el-form-item>
              <el-form-item :label="$t('common.coverImage')" prop="coverImage"  v-show="!isFullscreen">
                <!-- 图片类型 -->
                <FileUploader
                  ref="fileUploader"
                  accept="image/*"
                  :multiple="false"
                  :limit="1"
                  :auto-upload="true"
                  list-type="picture-card"
                  :data="{ directory: 'workflow' }"
                  buttonText=""
                  v-model="coverImage"
                  tip=""
                  @success="handleUploadSuccess"
                  @error="handleUploadError"
                  @progress="handleUploadProgress"
                />
              </el-form-item>
              <el-form-item :label="$t('common.workflowPreview')"  v-show="!isFullscreen">
                <div>{{$t('workflowTrade.supportBatchUpload')}}</div>
                <!-- 图片类型 -->
                <FileUploader
                  ref="fileUploader"
                  accept="image/*"
                  :multiple="true"
                  :limit="5"
                  :auto-upload="true"
                  list-type="picture-card"
                  :data="{ directory: 'workflow' }"
                  buttonText=""
                  v-model="images"
                  tip=""
                  @success="handleUploadSuccess"
                  @error="handleUploadError"
                  @progress="handleUploadProgress"
                />
              </el-form-item>
              <!-- <el-form-item :label="$t('common.Detail')" prop="workflowContent">
                <BlockNoteEditor v-model="editorContent" :editable="true" class="border"/>
              </el-form-item> -->
              <el-form-item :label="$t('common.Detail')" prop="workflowContent">
                <div class="editor-container" :class="{ 'fullscreen': isFullscreen }">
                  <div class="editor-header" v-if="isFullscreen">
                    <span class="editor-title">{{$t('common.Detail')}}</span>
                    <el-button 
                      icon="FullScreen" 
                      @click="toggleFullscreen"
                      size="small"
                      class="exit-fullscreen-btn"
                    >
                      {{$t('common.exitFullscreen')}}
                    </el-button>
                  </div>
                  <div class="editor-content">
                    <BlockNoteEditor 
                      v-model="editorContent" 
                      :editable="true" 
                      class="border"
                      :class="{ 'fullscreen-editor': isFullscreen }"
                    />
                  </div>
                  <el-button 
                    v-if="!isFullscreen"
                    icon="FullScreen" 
                    @click="toggleFullscreen"
                    size="small"
                    class="fullscreen-btn"
                  >
                    {{$t('common.fullscreenEdit')}}
                  </el-button>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card" v-show="!isFullscreen">
            <div class="gap10 mb20">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTrade.priceSetting')}}</div>
            </div>
          
            <el-form-item :label="$t('workflowTrade.paySetting')" style="width: 600px">
              <div class="gap20 mt10 mb20">
                <div class="payType gap10" @click="workflowPriceType = 'pay'" 
                :class="{'active': workflowPriceType === 'pay'}">
                  <div class="checkType"></div>
                  <div>{{$t('workflowTrade.paySettingTip')}}</div>
                </div>
                <div class="payType gap10" @click="workflowPriceType = 'free';ruleForm.workflowPrice=''" 
                :class="{'active': workflowPriceType === 'free'}">
                  <div class="checkType"></div>
                  <div>{{$t('workflowTrade.freeSettingTip')}}</div>
                </div>
              </div>
              <el-input v-model="ruleForm.workflowPrice" :placeholder="$t('workflowTrade.placeholderPrice')"  maxlength="50" type="number" v-if="workflowPriceType === 'pay'">
                <template #append>{{$t('common.baomibi')}}</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="mt20"  v-show="!isFullscreen">
            <el-button type="primary" class="font_size16 gradient" 
            :loading="isSubmiting"
            @click="submitForm"  size="large">
              <el-icon><Promotion /></el-icon>
              <span class="ml10">{{$t('common.publishWorkflow')}}</span>
            </el-button>
            <el-button class="font_size16" @click="goBack"  size="large">
              <el-icon><Close /></el-icon>
              <span class="ml10">{{$t('common.cancel')}}</span>
            </el-button>
          </div>
        </el-form>
      </div>
      <!-- 右边内容 -->
      <div class="detail_right">
        <div class="detail_right_content detail_right">
           <div class="padding16 bg_color_fff border_radius_16 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTradeAdd.publishRules')}}</div>
            </div>
            <!-- 无序列表 -->
            <div class="font_size16 ql-container">
              <div class="ql-editor">
                <div v-html="release_rules"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watchEffect, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FileUploader from '@/components/FileUploader.vue'
import DGTMessage from '@/utils/message'
import BlockNoteEditor from '@/components/BlockNoteEditor.vue';
const route = useRoute()
const router = useRouter()

import { getCategoryListTree } from '@/api/category.js'
import { getAgreementType } from '@/api/common.js'
import { publishAdd, getPublishDetail,publishEdit } from '@/api/publish.js'

import { useI18n } from 'vue-i18n' 
const { t } = useI18n()

// 防止重复提交的加载状态
const isSubmiting = ref(false)
// 发布规则
const release_rules = ref('');


// 从路由参数中获取 activePlatform
const activePlatform = ref(route.query.activePlatform || '');
// 从路由参数中获取 publishId
const publishId = ref(route.query.id || '');

// 图片
const images = ref([]);
const coverImage = ref([]);
//附件
const files = ref([]);
// 分类列表树
const categoryListTree = ref([]);
// 选择的分类id列表
const categoryIdList = ref([])
// 编辑器内容
const editorContent = ref(null);
const workflowPriceType = ref('pay'); // 价格类型，默认免费
// 表单实例
const ruleFormRef = ref(null)
const ruleForm = reactive({
  publishId: '',
  workflowTitle: '',
  categoryId1: '',
  categoryId2: '',
  categoryId3: '',
  workflowFile: '',
  workflowPrice: '',
  description: '',
  previewImage: '',
  coverImage: '',
  workflowContent: '',
})
watchEffect(() => {
  // 将选择的分类id列表赋值给表单的categoryId1、categoryId2、categoryId3
  ruleForm.categoryId1 = categoryIdList.value[0] || ''
  ruleForm.categoryId2 = categoryIdList.value[1] || ''
  ruleForm.categoryId3 = categoryIdList.value[2] || ''
  // 将编辑器内容赋值给表单的workflowContent
  ruleForm.workflowContent = JSON.stringify(editorContent.value);
  ruleForm.coverImage = coverImage.value.map(img => img.url).join(',');
  ruleForm.workflowFile = files.value[0]?.url || '';
  ruleForm.previewImage = images.value.map(img => img.url).join(',');

})
// 校验规则
const rules = reactive({
  workflowFile: [
    { required: true, message: t('workflowTrade.placeholderWorkflowFileUpload'), trigger: 'change' },
  ],
  workflowTitle: [
    { required: true, message: t('workflowTrade.placeholderWorkflowTitle'), trigger: 'blur' },
  ],
  categoryId3: [
    { required: true, message: t('workflowTrade.placeholderWorkflowCategory'), trigger: 'blur' },
  ],
  description: [
    { required: true, message: t('workflowTrade.placeholderWorkflowDescription'), trigger: 'blur' },
  ],
  coverImage: [
    { required: true, message: t('workflowTrade.placeholderCoverImageUpload'), trigger: 'change' },
  ],
  workflowContent: [
    { required: true, message: t('workflowTrade.placeholderWorkflowContent'), trigger: 'change' },
  ],
})


// 在现有代码后添加键盘事件处理
const handleKeyDown = (e) => {
  // ESC键退出全屏
  if (e.key === 'Escape' && isFullscreen.value) {
    toggleFullscreen();
  }
};


onMounted(() => {

  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown);
  getCategoryListTreeFn();
  if(publishId.value){
    getDetail();
  }
  getAgreementTypeFn();
});

// 提交表单
const submitForm = async () => {
 

  // if(!ruleForm.workflowFile){
  //   DGTMessage.warning('请上传工作流文件')
  //   return
  // }
  if(!editorContent.value || editorContent.value.length === 0){
    DGTMessage.warning(t('workflowTrade.placeholderWorkflowContent'))
    return
  }
  if(workflowPriceType.value === 'pay'){
    if(!ruleForm.workflowPrice){
      DGTMessage.warning(t('workflowTrade.placeholderPrice'))
      return
    }
  }
  console.log('工作流详情内容',ruleForm)
  await ruleFormRef.value.validate((valid, fields) => {
    console.log(valid, fields)
    if (!valid) {
      //报错第一个key
      let firstKey = Object.keys(fields)[0]
      DGTMessage.warning(fields[firstKey][0].message)
      return
    }
     let req = publishAdd;
    if(publishId.value){
      req = publishEdit;
    }
    // 设置提交状态为true，禁用按钮
    isSubmiting.value = true
    req(ruleForm).then(res => {
      console.log(res)
      if(res.code === 200){
        DGTMessage.success(t('workflowTrade.publishSuccess'))
        setTimeout(() => {
          goBack();
        }, 2000);
      }
    }).finally(() => {
      // 提交完成后，将提交状态设置为false，启用按钮
      setTimeout(() => {
        isSubmiting.value = false
      }, 1000)
    })
  })
}

  // 上传成功处理
const handleUploadSuccess = (response, rawFile, uploadedFiles) => {
  // DGTMessage.success('文件上传成功')
  console.log('上传成功:', response,uploadedFiles)
}

// 上传失败处理
const handleUploadError = (error, rawFile, uploadedFiles) => {
  // DGTMessage.error('文件上传失败')
  console.error('上传失败:', error)
}

// 上传进度处理
const handleUploadProgress = (event, file, uploadedFiles) => {
  console.log('上传进度:', event.percent)
};

const goBack = () => {
  router.back()
};

const getCategoryListTreeFn = () => {
  getCategoryListTree().then(res => {
    console.log(res)
    categoryListTree.value = res.rows || [];
  })
};
const getDetail = () => {
  getPublishDetail({id:publishId.value}).then(res => {
    const detail = res.data || {};
    for(let key in ruleForm){
      ruleForm[key] = detail[key];
    }
    nextTick(() => {
      if(ruleForm.workflowFile){
        files.value = [{url: ruleForm.workflowFile}];
      };
      if(ruleForm.coverImage){
        coverImage.value = ruleForm.coverImage.split(',').map(item => ({url: item}));
      };
      if(ruleForm.previewImage){
        images.value = ruleForm.previewImage.split(',').map(item => ({url: item}));
      };
      if(ruleForm.categoryId1){
        categoryIdList.value = [ruleForm.categoryId1, ruleForm.categoryId2, ruleForm.categoryId3];
      };

      setTimeout(() => {
        if(detail.workflowContent){
          editorContent.value = JSON.parse(detail.workflowContent);
        }
        console.log('editorContent.value',editorContent.value,ruleForm)
      }, 500);
    });
  })
};
// 在 script setup 中添加
const isFullscreen = ref(false);

// 切换全屏的方法
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
  
  if (isFullscreen.value) {
    // 进入全屏时可能需要调整编辑器焦点
    nextTick(() => {
      // 如果 BlockNoteEditor 有 focus 方法，可以调用
    });
  }
};
const getAgreementTypeFn = () => {
  getAgreementType({agreementType: 'workflow_rules'}).then(res => {
    console.log(res)
    release_rules.value = res.data.content || '';
  })
};
</script>
<style lang="scss">
.workflow-add{
  .payType{
    background: #EAF0FF;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid transparent;
    padding: 10px 16px;
    &.active{
      background: #EAF0FF;
      border-color: $primary-color;
      .checkType{
        border-color: $primary-color;
      }
    }
    .checkType{
      width: 14px;
      height: 14px;
      border:4px solid transparent;
      border-radius: 50%;
      background-color: #ffffff;
    }
  }
}
</style>
<style lang="scss">
.editor-container {
  position: relative;
  width: 100%;
  
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background: #f5f5f5;
    border-bottom: 1px solid #dcdfe6;
    
    .editor-title {
      font-weight: bold;
      color: #303133;
    }
    
    .exit-fullscreen-btn {
      margin-left: auto;
    }
  }


  
  
  .fullscreen-btn {
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10;
  }
  // .exit-fullscreen-btn{

  // }
  
  .fullscreen-btn {
    bottom: 10px;
    top: auto;
  }
  
  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: white;
    z-index: 9999;
    padding: 20px;
    
    .blocknote-editor {
      height: calc(100vh - 100px) !important; // 减去头部和按钮的高度
    }
    .editor-content {
      height: calc(100vh - 100px);
    }
  }
}
</style>
