<template>
  <div class="workflow-add container-height">
    <Breadcrumb />
    <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">
        <div class="gap10">
          <div class="line_vertical"></div>
          <div class="font_size20 bold">文件上传</div>
          <div class="gray999 font_size14">支持格式：JSON、YAML、ZIP（最大10MB）</div>
        </div>
        <div class="mt10">
          <!-- 上传 -->
          <FileUploader
            ref="fileUploader"
            accept=".json,.yaml,.yml,.zip"
            :multiple="false"
            :limit="1"
            :auto-upload="true"
            :drag="true"
            v-model="files"
            tip="请上传JSON、YAML、ZIP格式的文件，最大10MB"
          />
        </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">基本信息</div>
        </div>
        <div class="mt10">
          <el-form-item label="工作流标题" prop="workflowTitle">
            <el-input v-model="ruleForm.workflowTitle" placeholder="请输入工作流标题"  maxlength="50"/>
          </el-form-item>
          <el-form-item label="工作流类型" prop="categoryId3">
            <el-cascader 
              v-model="categoryIdList"
              :options="categoryListTree"
              placeholder="请选择工作流类型"
              style="width:100%"
              :props="{
                label: 'categoryName',
                value: 'categoryId',
                children: 'children',
              }"
            />
          </el-form-item>
          <el-form-item label="工作流描述" prop="description">
            <el-input type="textarea" v-model="ruleForm.description" placeholder="请输入工作流描述"  maxlength="500" show-word-limit/>
          </el-form-item>
          <el-form-item label="封面图" prop="coverImage">
            <div>支持批量上传文件，文件格式不限，最多只能上传 5 份文件</div>
            <!-- 图片类型 -->
            <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="工作流预览">
            <div>支持批量上传文件，文件格式不限，最多只能上传 5 份文件</div>
            <!-- 图片类型 -->
            <FileUploader
              ref="fileUploader"
              accept="image/*"
              :multiple="true"
              :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="详情" prop="workflowContent">
            <BlockNoteEditor v-model="editorContent" :editable="true"/>
          </el-form-item>
        </div>
      </div>
      <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card">
        <div class="gap10 mb20">
          <div class="line_vertical"></div>
          <div class="font_size20 bold">价格设置</div>
        </div>
       
        <el-form-item label="付费设置" style="width: 500px">
          <div class="gap20 mt10 mb20">
            <div class="payType gap10" @click="workflowPriceType = 'pay'" 
            :class="{'active': workflowPriceType === 'pay'}">
              <div class="checkType"></div>
              <div>付费（用户需付费后使用）</div>
            </div>
            <div class="payType gap10" @click="workflowPriceType = 'free';ruleForm.workflowPrice=''" 
            :class="{'active': workflowPriceType === 'free'}">
              <div class="checkType"></div>
              <div>免费（所有用户可免费数据）</div>
            </div>
          </div>
          <el-input v-model="ruleForm.workflowPrice" placeholder="请输入暴米币数量"  maxlength="50" type="number" v-if="workflowPriceType === 'pay'">
            <template #append>暴米币</template>
          </el-input>
        </el-form-item>
      </div>
      <div class="mt20">
        <el-button type="primary" class="font_size16 gradient" @click="submitForm"  size="large">
          <el-icon><Promotion /></el-icon>
          <span class="ml10">发布工作流</span>
        </el-button>
        <el-button class="font_size16" @click="goBack"  size="large">
          <el-icon><Close /></el-icon>
          <span class="ml10">取消</span>
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watchEffect } 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 { publishAdd } from '@/api/publish.js'

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

// 图片
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({
  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(',');;

})
// 校验规则
const rules = reactive({
  workflowTitle: [
    { required: true, message: '请输入工作流标题', trigger: 'blur' },
  ],
  categoryId3: [
    { required: true, message: '请输入工作流标题', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入工作流描述', trigger: 'blur' },
  ],
  coverImage: [
    { required: true, message: '请上传封面图', trigger: 'change' },
  ],
  workflowContent: [
    { required: true, message: '请输入工作流详情内容', trigger: 'change' },
  ],
})



onMounted(() => {
  getCategoryListTreeFn();
});

// 提交表单
const submitForm = async () => {
  ruleForm.workflowFile = files.value[0]?.url || '';
  ruleForm.previewImage = images.value.map(img => img.url).join(',');
  
  if(!editorContent.value || editorContent.value.length === 0){
    DGTMessage.warning('请输入工作流详情内容')
    return
  }
  if(workflowPriceType.value === 'pay'){
    if(!ruleForm.workflowPrice){
      DGTMessage.warning('请输入暴米币数量')
      return
    }
  }
  console.log('工作流详情内容',ruleForm)
  await ruleFormRef.value.validate((valid, fields) => {
    console.log(valid, fields)
    if (!valid) {
      DGTMessage.warning(fields.name[0].message)
      return
    }
    publishAdd(ruleForm).then(res => {
      console.log(res)
      if(res.code === 200){
        DGTMessage.success('提交成功')
        setTimeout(() => {
          goBack();
        }, 2000);
      }
    })
  })
}

  // 上传成功处理
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 || [];
  })
};
</script>
<style lang="scss">
.workflow-add{
  .payType{
    background: #EAF0FF;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid transparent;
    padding: 20px 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>
