<template>
  <div class="design-agent-block">
    <symbol id="icon-aiyoujiantou" viewBox="0 0 1024 1024"><path d="M350.165333 97.834667a42.666667 42.666667 0 0 0-60.330666 60.330666L643.626667 512 289.834667 865.834667a42.666667 42.666667 0 0 0-2.496 57.621333l2.496 2.709333a42.666667 42.666667 0 0 0 60.330666 0l384-384a42.666667 42.666667 0 0 0 0-60.330666l-384-384z"></path></symbol>
    <div class="tool-direct-black">
      <div class="tools-header-block">
        <header class="header-block">
          <h1>
            <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              ><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" /><path d="M20 3v4" /><path d="M22 5h-4" /><path d="M4 17v2" /><path d="M5 18H3" /></svg>
            {{ pagesData.title }}
          </h1>
          <p>
            {{ pagesData.desc }}
          </p>
        </header>
      </div>
      <div class="tool-direct-content-black">
        <!-- <div class="chat-block" v-if="pages == 'chat'">
          <iframe src="https://aids.gloria.com.cn:8443/chat/Q2zXZ4uwp3yN4Tmn" frameborder="0"></iframe>
        </div> -->
        <div class="tools-block">
          <div class="tool-direct-content">
          <div class="tool-direct-left">
            <!-- <div class="tool-direct-left__title">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              ><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" /><path d="M20 3v4" /><path d="M22 5h-4" /><path d="M4 17v2" /><path d="M5 18H3" /></svg>
              <h3>{{ pagesData.title }}</h3>
            </div>
            <div class="tool-direct-left__desc">{{ pagesData.desc }}</div> -->
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" label-position="top">
              <div class="ruleFormContent">
                <el-scrollbar>
                  <!-- 图生图 -->
                  <el-form-item class="batch-form" v-if="pagesData.applicationId == 2">
                    <template #label>
                      <div class="label-title">
                        <span>批量</span>
                      </div>
                      <el-switch v-model="ruleForm.isBatch" @change="handleBatch"></el-switch>
                    </template>
                  </el-form-item>

                  <el-form-item class="images-group-form"  prop="editableTabs" required v-if="ruleForm.isBatch">
                    <template #label>
                      <div class="label-title">
                        <span><em class="no">1</em> 上衣图片</span>
                      </div>
                    </template>
                    <div style="margin-bottom: 10px;display:flex;justify-content: flex-end;">
                      <el-button
                        size="small"
                        @click="addTab(ruleForm.editableTabsValue)"
                      >
                        添加上衣图片项
                      </el-button>
                    </div>
                    <el-tabs v-model="ruleForm.editableTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="clickTabs">
                      <el-tab-pane
                        v-for="(item, parentIndex) in ruleForm.editableTabs"
                        :key="item.name"
                        :label="`图片组 ${parentIndex+1}`"
                        :name="item.name"
                      >
                        <div class="tools-upload">
                          <!-- 自定义显示每个图片的重新上传按钮 -->
                          <div class="swiper-container-block" v-if="item.content.length">
                            <div class="swiper-container my-swiper" :ref="`swiperContainer-${parentIndex}`">
                              <draggable
                                tag="div"
                                class="swiper-wrapper"
                                :list="item.content"
                                :options="{ animation: 150 }"
                              >
                                <div class="swiper-slide" v-for="(group, index) in item.content" :key="index">
                                  <div class="img-group">
                                    <div class="custom-file-list" >
                                      <div class="picture-card-wrapper">
                                        <img :src="group" class="picture-card-image" />
                                        <div class="custom-file__btns">
                                          <el-button 
                                            class="replace-btn" 
                                            @click="replaceFileGroup(index, parentIndex)">
                                            <svg t="1760412251487" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6466" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M902.314667 206.741333a21.333333 21.333333 0 0 1 0 30.122667l-46.933334 47.146667-122.581333 123.178666a21.333333 21.333333 0 0 1-30.229333 0l-31.829334-31.957333a21.333333 21.333333 0 0 1 0-30.122667l42.666667-42.816c13.376-13.44 3.84-36.394667-15.146667-36.394666H375.189333c-46.933333 0-91.157333 18.389333-124.373333 51.733333a175.914667 175.914667 0 0 0-51.52 124.885333v91.712a21.333333 21.333333 0 0 1-21.333333 21.333334H132.970667a21.333333 21.333333 0 0 1-21.333334-21.333334v-91.818666c0-146.090667 118.037333-264.618667 263.530667-264.618667h323.008c18.986667 0 28.522667-22.933333 15.125333-36.373333l-42.666666-42.837334a21.333333 21.333333 0 0 1 0-30.101333l31.829333-31.978667a21.333333 21.333333 0 0 1 30.250667 0l122.581333 123.093334 47.018667 47.146666z m-97.941334 353.706667c0 47.146667-18.325333 91.52-51.541333 124.885333a174.464 174.464 0 0 1-124.373333 51.733334H325.653333c-18.986667 0-28.522667-22.954667-15.125333-36.394667l42.752-42.922667a21.333333 21.333333 0 0 0 0-30.122666l-31.829333-31.957334a21.333333 21.333333 0 0 0-30.229334 0l-122.602666 123.008-46.933334 47.146667a21.333333 21.333333 0 0 0 0 30.08l46.933334 47.146667 122.602666 123.093333a21.333333 21.333333 0 0 0 30.229334 0l31.829333-31.957333a21.333333 21.333333 0 0 0 0-30.101334l-42.453333-42.624c-13.397333-13.44-3.861333-36.394667 15.104-36.394666H628.48c145.493333 0 263.530667-118.528 263.530667-264.618667v-90.538667a21.333333 21.333333 0 0 0-21.333334-21.333333h-44.970666a21.333333 21.333333 0 0 0-21.333334 21.333333v90.538667z" p-id="6467" fill="#ffffff"></path></svg>
                                            重新上传
                                          </el-button>
                                          <el-button 
                                            class="replace-btn" 
                                            @click="imgUploadDelGroup(index, parentIndex)">
                                            <svg t="1760412304801" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7509" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M853.333333 256H170.666667V853.333333a85.333333 85.333333 0 0 0 85.333333 85.333334h512A85.333333 85.333333 0 0 0 853.333333 853.333333V256zM85.333333 170.666667h170.666667V85.333333A85.333333 85.333333 0 0 1 341.333333 0h341.333334a85.333333 85.333333 0 0 1 85.333333 85.333333V170.666667h213.333333a42.666667 42.666667 0 0 1 0 85.333333H938.666667V853.333333a170.666667 170.666667 0 0 1-170.666667 170.666667h-512a170.666667 170.666667 0 0 1-170.666667-170.666667V256H42.666667a42.666667 42.666667 0 1 1 0-85.333333H85.333333zM341.333333 170.666667h341.333334V85.333333H341.333333V170.666667z m42.666667 256c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z m256 0c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z" fill="#ffffff" p-id="7510"></path></svg>
                                            删除图片
                                          </el-button>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </draggable>
                              <!-- 左右箭头 -->
                              <div class="swiper-button-prev swiper-button">
                                <svg t="1760505375902" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10647" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M307.6 104.6c-14.2 14.2-14.2 37.2 0 51.4L655 503.4c2.8 2.9 2.8 7.5 0 10.3L307.6 861.2c-14.2 14.2-14.2 37.2 0 51.4 14.2 14.2 37.2 14.2 51.4 0l347.4-347.4c15.6-15.6 23.4-36 23.4-56.5s-7.8-41-23.4-56.5L359 104.6c-14.2-14.2-37.2-14.2-51.4 0z" p-id="10648"></path></svg>
                              </div>
                              <div class="swiper-button-next swiper-button">
                                <svg t="1760505375902" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10647" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M307.6 104.6c-14.2 14.2-14.2 37.2 0 51.4L655 503.4c2.8 2.9 2.8 7.5 0 10.3L307.6 861.2c-14.2 14.2-14.2 37.2 0 51.4 14.2 14.2 37.2 14.2 51.4 0l347.4-347.4c15.6-15.6 23.4-36 23.4-56.5s-7.8-41-23.4-56.5L359 104.6c-14.2-14.2-37.2-14.2-51.4 0z" p-id="10648"></path></svg>
                              </div>
                            </div>
                          </div>
                          <el-upload
                            :ref="`uploadRef-${parentIndex}`"
                            class="upload-demo"
                            :class="{'upload-demo__data': item.content.length}"
                            drag
                            :action="action"
                            :show-file-list="false" 
                            :headers="{
                              'Authorization': 'Bearer ' + token
                            }"
                            multiple
                            :on-success="handleVideoSuccessGroup" 
                            :before-upload="beforeUploadVideo"
                          >
                            <div v-loading="uploading">
                              <template v-if="item.content.length">
                                <i class="el-icon-plus"></i>
                                <el-button type="primary" size="mini" @click.stop="handleProductRepo('tabs')">产品库</el-button>
                              </template>
                              <div class="el-upload__info" v-else>
                                <i class="el-icon-upload" style="margin: 0;"></i>
                                <div class="el-upload__text">点击或将图片拖拽到这里上传</div>
                                <div class="el-upload__tip" slot="tip">图片要求：支持JPG、PNG和WEBP，最大为20M</div>
                                <div class="el-upload__btn">
                                  <el-button type="primary" size="small" @click.stop="handleProductRepo('tabs')">从产品库选择</el-button>
                                </div>
                              </div>
                            </div>
                          </el-upload>
                        </div>
                        <span class="tips" v-if="item.content.length">拖动图片改变图片位置</span>
                        <div class="tools-sku">
                          SKU <el-input v-model="item.sku" size="small" placeholder="请输入sku"></el-input>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </el-form-item>
                  
                  <el-form-item prop="imageList" required v-if="pagesData.applicationId == 2">
                    <template #label>
                      <div class="label-title">
                        <span><em class="no">{{ ruleForm.isBatch ? 2 : 1 }}</em> {{ ruleForm.isBatch ? '上传姿势图' : '上传图片' }}</span>
                      </div>
                    </template>
                    <div class="tools-upload">
                      <!-- 自定义显示每个图片的重新上传按钮 -->
                      <div class="swiper-container-block" v-if="ruleForm.imageList.length">
                        <div class="swiper-container my-swiper" ref="swiperContainer">
                          <draggable
                            tag="div"
                            class="swiper-wrapper"
                            :list="ruleForm.imageList"
                            :options="{ animation: 150 }"
                          >
                            <div class="swiper-slide" v-for="(group, index) in ruleForm.imageList" :key="index">
                              <div class="img-group">
                                <div class="custom-file-list" >
                                  <div class="picture-card-wrapper">
                                    <img :src="group" class="picture-card-image" />
                                    <div class="custom-file__btns">
                                      <el-button 
                                        class="replace-btn" 
                                        @click="replaceFile(index)">
                                        <svg t="1760412251487" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6466" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M902.314667 206.741333a21.333333 21.333333 0 0 1 0 30.122667l-46.933334 47.146667-122.581333 123.178666a21.333333 21.333333 0 0 1-30.229333 0l-31.829334-31.957333a21.333333 21.333333 0 0 1 0-30.122667l42.666667-42.816c13.376-13.44 3.84-36.394667-15.146667-36.394666H375.189333c-46.933333 0-91.157333 18.389333-124.373333 51.733333a175.914667 175.914667 0 0 0-51.52 124.885333v91.712a21.333333 21.333333 0 0 1-21.333333 21.333334H132.970667a21.333333 21.333333 0 0 1-21.333334-21.333334v-91.818666c0-146.090667 118.037333-264.618667 263.530667-264.618667h323.008c18.986667 0 28.522667-22.933333 15.125333-36.373333l-42.666666-42.837334a21.333333 21.333333 0 0 1 0-30.101333l31.829333-31.978667a21.333333 21.333333 0 0 1 30.250667 0l122.581333 123.093334 47.018667 47.146666z m-97.941334 353.706667c0 47.146667-18.325333 91.52-51.541333 124.885333a174.464 174.464 0 0 1-124.373333 51.733334H325.653333c-18.986667 0-28.522667-22.954667-15.125333-36.394667l42.752-42.922667a21.333333 21.333333 0 0 0 0-30.122666l-31.829333-31.957334a21.333333 21.333333 0 0 0-30.229334 0l-122.602666 123.008-46.933334 47.146667a21.333333 21.333333 0 0 0 0 30.08l46.933334 47.146667 122.602666 123.093333a21.333333 21.333333 0 0 0 30.229334 0l31.829333-31.957333a21.333333 21.333333 0 0 0 0-30.101334l-42.453333-42.624c-13.397333-13.44-3.861333-36.394667 15.104-36.394666H628.48c145.493333 0 263.530667-118.528 263.530667-264.618667v-90.538667a21.333333 21.333333 0 0 0-21.333334-21.333333h-44.970666a21.333333 21.333333 0 0 0-21.333334 21.333333v90.538667z" p-id="6467" fill="#ffffff"></path></svg>
                                        重新上传
                                      </el-button>
                                      <el-button 
                                        class="replace-btn" 
                                        @click="imgUploadDel(index)">
                                        <svg t="1760412304801" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7509" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M853.333333 256H170.666667V853.333333a85.333333 85.333333 0 0 0 85.333333 85.333334h512A85.333333 85.333333 0 0 0 853.333333 853.333333V256zM85.333333 170.666667h170.666667V85.333333A85.333333 85.333333 0 0 1 341.333333 0h341.333334a85.333333 85.333333 0 0 1 85.333333 85.333333V170.666667h213.333333a42.666667 42.666667 0 0 1 0 85.333333H938.666667V853.333333a170.666667 170.666667 0 0 1-170.666667 170.666667h-512a170.666667 170.666667 0 0 1-170.666667-170.666667V256H42.666667a42.666667 42.666667 0 1 1 0-85.333333H85.333333zM341.333333 170.666667h341.333334V85.333333H341.333333V170.666667z m42.666667 256c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z m256 0c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z" fill="#ffffff" p-id="7510"></path></svg>
                                        删除图片
                                      </el-button>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </draggable>
                          <!-- 左右箭头 -->
                          <div class="swiper-button-prev swiper-button">
                            <svg t="1760505375902" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10647" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M307.6 104.6c-14.2 14.2-14.2 37.2 0 51.4L655 503.4c2.8 2.9 2.8 7.5 0 10.3L307.6 861.2c-14.2 14.2-14.2 37.2 0 51.4 14.2 14.2 37.2 14.2 51.4 0l347.4-347.4c15.6-15.6 23.4-36 23.4-56.5s-7.8-41-23.4-56.5L359 104.6c-14.2-14.2-37.2-14.2-51.4 0z" p-id="10648"></path></svg>
                          </div>
                          <div class="swiper-button-next swiper-button">
                            <svg t="1760505375902" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10647" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M307.6 104.6c-14.2 14.2-14.2 37.2 0 51.4L655 503.4c2.8 2.9 2.8 7.5 0 10.3L307.6 861.2c-14.2 14.2-14.2 37.2 0 51.4 14.2 14.2 37.2 14.2 51.4 0l347.4-347.4c15.6-15.6 23.4-36 23.4-56.5s-7.8-41-23.4-56.5L359 104.6c-14.2-14.2-37.2-14.2-51.4 0z" p-id="10648"></path></svg>
                          </div>
                        </div>
                      </div>
                      <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        :class="{'upload-demo__data': ruleForm.imageList.length}"
                        drag
                        :action="action"
                        :show-file-list="false" 
                        :headers="{
                          'Authorization': 'Bearer ' + token
                        }"
                        multiple
                        :on-success="handleVideoSuccess" 
                        :before-upload="beforeUploadVideo"
                      >
                        <div v-loading="uploading">
                          <template v-if="ruleForm.imageList.length">
                            <i class="el-icon-plus"></i>
                            <el-button type="primary" size="mini" @click.stop="handleProductRepo">产品库</el-button>
                          </template>
                          <div class="el-upload__info" v-else>
                            <i class="el-icon-upload" style="margin: 0;"></i>
                            <div class="el-upload__text">点击或将图片拖拽到这里上传，最多上传 5 张图片</div>
                            <div class="el-upload__tip" slot="tip">图片要求：支持JPG、PNG和WEBP，最大为20M</div>
                            <div class="el-upload__btn">
                              <el-button type="primary" size="small" @click.stop="handleProductRepo">从产品库选择</el-button>
                            </div>
                          </div>
                        </div>
                      </el-upload>
                    </div>
                    <span class="tips" v-if="ruleForm.imageList.length">拖动图片改变图片位置</span>
                  </el-form-item>
                  <el-form-item prop="imageUrl" required v-if="pagesData.applicationId == 3">
                    <template #label>
                      <div class="label-title">
                        <span><em class="no">1</em> 上传图片</span>
                      </div>
                    </template>
                    <div class="tools-upload">
                      <el-upload
                        class="upload-demo"
                        drag
                        :action="action" 
                        :show-file-list="false" 
                        :headers="{
                          'Authorization': 'Bearer ' + token
                        }"
                        multiple 
                        :on-success="handleVideoSuccess" 
                        :before-upload="beforeUploadVideo">
                        <div v-loading="uploading">
                          <div v-if="ruleForm.imageUrl" class="avatar-black">
                            <img :src="ruleForm.imageUrl" class="avatar">
                            <div class="custom-file__btns">
                              <el-button 
                                class="replace-btn" 
                                @click="replaceFile()">
                                <svg t="1760412251487" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6466" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M902.314667 206.741333a21.333333 21.333333 0 0 1 0 30.122667l-46.933334 47.146667-122.581333 123.178666a21.333333 21.333333 0 0 1-30.229333 0l-31.829334-31.957333a21.333333 21.333333 0 0 1 0-30.122667l42.666667-42.816c13.376-13.44 3.84-36.394667-15.146667-36.394666H375.189333c-46.933333 0-91.157333 18.389333-124.373333 51.733333a175.914667 175.914667 0 0 0-51.52 124.885333v91.712a21.333333 21.333333 0 0 1-21.333333 21.333334H132.970667a21.333333 21.333333 0 0 1-21.333334-21.333334v-91.818666c0-146.090667 118.037333-264.618667 263.530667-264.618667h323.008c18.986667 0 28.522667-22.933333 15.125333-36.373333l-42.666666-42.837334a21.333333 21.333333 0 0 1 0-30.101333l31.829333-31.978667a21.333333 21.333333 0 0 1 30.250667 0l122.581333 123.093334 47.018667 47.146666z m-97.941334 353.706667c0 47.146667-18.325333 91.52-51.541333 124.885333a174.464 174.464 0 0 1-124.373333 51.733334H325.653333c-18.986667 0-28.522667-22.954667-15.125333-36.394667l42.752-42.922667a21.333333 21.333333 0 0 0 0-30.122666l-31.829333-31.957334a21.333333 21.333333 0 0 0-30.229334 0l-122.602666 123.008-46.933334 47.146667a21.333333 21.333333 0 0 0 0 30.08l46.933334 47.146667 122.602666 123.093333a21.333333 21.333333 0 0 0 30.229334 0l31.829333-31.957333a21.333333 21.333333 0 0 0 0-30.101334l-42.453333-42.624c-13.397333-13.44-3.861333-36.394667 15.104-36.394666H628.48c145.493333 0 263.530667-118.528 263.530667-264.618667v-90.538667a21.333333 21.333333 0 0 0-21.333334-21.333333h-44.970666a21.333333 21.333333 0 0 0-21.333334 21.333333v90.538667z" p-id="6467" fill="#ffffff"></path></svg>
                                重新上传
                              </el-button>
                              <el-button 
                                class="replace-btn" 
                                @click.stop="imgUploadDel()">
                                <svg t="1760412304801" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7509" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M853.333333 256H170.666667V853.333333a85.333333 85.333333 0 0 0 85.333333 85.333334h512A85.333333 85.333333 0 0 0 853.333333 853.333333V256zM85.333333 170.666667h170.666667V85.333333A85.333333 85.333333 0 0 1 341.333333 0h341.333334a85.333333 85.333333 0 0 1 85.333333 85.333333V170.666667h213.333333a42.666667 42.666667 0 0 1 0 85.333333H938.666667V853.333333a170.666667 170.666667 0 0 1-170.666667 170.666667h-512a170.666667 170.666667 0 0 1-170.666667-170.666667V256H42.666667a42.666667 42.666667 0 1 1 0-85.333333H85.333333zM341.333333 170.666667h341.333334V85.333333H341.333333V170.666667z m42.666667 256c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z m256 0c23.552 0 42.666667 19.114667 42.666667 42.666666v256a42.666667 42.666667 0 0 1-85.333334 0v-256c0-23.552 19.114667-42.666667 42.666667-42.666666z" fill="#ffffff" p-id="7510"></path></svg>
                                删除图片
                              </el-button>
                            </div>
                          </div>
                          <div class="el-upload__info" v-else>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">图片要求：支持JPG、PNG和WEBP，最大为20M</div>
                          </div>
                        </div>
                      </el-upload>
                    </div>
                  </el-form-item>
                  <el-form-item prop="screenDescription" class="tool-direct-left__submit">
                    <template #label>
                      <div class="label-title">
                        <span>
                          <em class="no">{{pagesData.applicationId == 1 ? '1' : (ruleForm.isBatch ? '3' : '2')}}</em> 画面描述{{ pagesData.applicationId == 3 ? '（选填）' : '' }}
                        </span>
                        <el-tooltip 
                          class="item" 
                          effect="dark" 
                          :content="pagesData.contentTips" 
                          placement="top"
                        >
                          <i class="el-icon-info" style="color: #ccc;cursor: pointer;" />
                        </el-tooltip>

                        <div class="clothing-type__block" style="margin-left: 20px;" v-if="ruleForm.isBatch">
                          <el-select v-model="ruleForm.clothingType" size="small" placeholder="衣服类型">
                            <el-option
                              v-for="item in clothingTypes"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                            </el-option>
                          </el-select>
                        </div>
                      </div>
                    </template>
                    <el-input
                      type="textarea"
                      :rows="5"
                      :placeholder="ruleForm.isBatch ? '例如：把图2女士身上衣服替换到图1模特身上' : pagesData.placeholder"
                      :maxlength="1000"
                      show-word-limit
                      v-model="ruleForm.screenDescription">
                    </el-input>
                    <span class="clear-block" v-if="ruleForm.screenDescription"  @click.stop="clearDescription()">清除</span>
                  </el-form-item>
                  <el-form-item v-if="pagesData.applicationId == 2 && ruleForm.isBatch">
                    <template #label>
                      <div class="label-title">
                        <span><em class="no">4</em> 批量生产</span>
                      </div>
                    </template>
                    <div>
                      <el-input-number size="small" :min="1" :step="1" step-strictly v-model="ruleForm.batchCount" :controls="false"></el-input-number> 张
                    </div>
                  </el-form-item>
                  <template v-if="pagesData.applicationId == 2 && !ruleForm.isBatch">
                    <el-form-item>
                      <template #label>
                        <div class="label-title">
                          <span><em class="no">3</em> 图片比例（选填）</span>
                        </div>
                      </template>
                      <div class="tool-direct-left__imageRatio">
                        <div class="image-ratio__block">
                          <div class="el-checkbox-group">
                            <div
                              v-for="item in ratioList"
                              :key="item"
                              :class="['el-checkbox', { 'is-checked': ruleForm.imageRatioList === item }]"
                              @click="toggle(item)"
                            >
                              <span class="el-checkbox__input"></span>
                              {{ item }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                    <el-form-item>
                      <template #label>
                        <div class="label-title">
                          <span><em class="no">4</em> 图片尺寸（选填）</span>
                        </div>
                      </template>
                      <div class="tool-direct-left__imageSize">
                        <el-select clearable v-model="ruleForm.imageSizeSelect" placeholder="请选择" size="small">
                          <el-option
                            v-for="item in imageSizes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                        <el-button type="primary" size="small" @click="handleCustom">自定义</el-button>
                      </div>
                      <div class="image-ratio__custom" v-if="hasCustom">
                        <el-input-number :controls="false" v-model="ruleForm.imageSize.width" size="small"></el-input-number>
                        X
                        <el-input-number :controls="false" v-model="ruleForm.imageSize.height" size="small"></el-input-number>
                      </div>
                    </el-form-item>
                  </template>
                </el-scrollbar>
              </div>
              <el-form-item class="el-form-item__btns">
                <div class="tool-direct-left__btns">
                  <el-button class="save" @click="submitForm()" type="primary" :loading="comfirmLoading">
                    生成图片
                  </el-button>
                  <div class="clear" @click="resetForm()">
                    <el-button>清空</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div
            class="tool-direct-right"
            flex="1 ~ col"
            v-loading="viewLoading"
          >
            <!-- <div class="tool-direct-right__title">
              <h3>生成结果</h3>
            </div> -->
            <div
              class="tool-direct-right__result"
              flex="1 ~ col"
              h-full
            > 
              <div
                v-if="comfirmLoading"
                class="tool-direct-right__loading"
                flex="1 ~ col"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  style="color: rgb(154, 120, 110);"
                ><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>
                AI正在为您生成图片...
              </div>
              <template v-else>
                <div class="result-success" v-if="resultImage">
                  <div class="preview-black__images">
                    <div class="images-preview">
                      <el-image
                        :src="resultImage"
                        :preview-src-list="srcList"
                      ></el-image>
                    </div>
                    <!-- <el-tooltip class="item" effect="dark" content="预览" placement="top">
                      <div class="images-preview__search">
                          <el-image
                            :src="resultImage"
                            :preview-src-list="srcList"
                          ></el-image>
                          <svg t="1759203455323" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4663" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M928 886.4l-160-160c128-150.4 120-377.6-20.8-520C596.8 56 353.6 56 204.8 206.4c-72 72-112 169.6-112 272s40 198.4 112 272c72 72 169.6 112 272 112 91.2 0 179.2-32 248-91.2l160 160c12.8 12.8 32 12.8 44.8 0 11.2-12.8 11.2-32-1.6-44.8zM249.6 705.6c-60.8-60.8-94.4-140.8-94.4-225.6s33.6-166.4 94.4-225.6c62.4-62.4 144-92.8 225.6-92.8s163.2 30.4 225.6 92.8c124.8 124.8 124.8 328 0 452.8C640 768 560 801.6 475.2 801.6c-84.8-3.2-164.8-35.2-225.6-96z" fill="#333333" p-id="4664"></path></svg>
                      </div>
                    </el-tooltip> -->
                    <div class="images-preview__icon">
                      <el-tooltip class="item" v-if="!isSave" effect="dark" content="保存到我的作品" placement="top">
                        <div class="like-icons icons" @click="saveUserWork">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="24"
                            height="24"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="#EF4444"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                          ><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z" /></svg>
                        </div>
                      </el-tooltip>
                      <el-tooltip v-else class="item" effect="dark" content="从作品中移除" placement="top">
                        <div class="like-icons icons" @click="updateUserWork(true)">
                          <svg t="1760494995280" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7979" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M512.042667 193.237333a255.914667 255.914667 0 0 1 351.658666 9.728 256 256 0 0 1 10.069334 351.402667l-361.813334 362.325333-361.728-362.325333a256 256 0 0 1 361.813334-361.130667z" fill="#EF4444" p-id="7980"></path></svg>
                        </div>
                      </el-tooltip>
                      <el-tooltip class="item" effect="dark" content="下载" placement="top">
                        <div class="download-icon icons" @click="handleDownload">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="24"
                            height="24"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                          ><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line
                            x1="12"
                            x2="12"
                            y1="15"
                            y2="3"
                          /></svg>
                        </div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
                <div
                  v-else
                  class="result-empty"
                  flex="1 ~ col"
                >
                  <svg t="1760405750612" class="icon" viewBox="0 0 1025 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4580" xmlns:xlink="http://www.w3.org/1999/xlink" width="200.1953125" height="200"><path d="M512.016 1024C229.232 1024 0.016 794.784 0.016 512 0.016 229.216 229.232 0 512.016 0 794.784 0 1024 229.216 1024 512 1024 794.784 794.784 1024 512.016 1024ZM512.016 64C264.976 64 64.016 264.96 64.016 512 64.016 759.024 264.976 960 512.016 960 759.04 960 960 759.024 960 512 960 264.96 759.04 64 512.016 64ZM510.336 833.456C509.056 833.456 507.744 833.488 506.448 833.488 310.992 833.488 229.024 657.12 225.616 649.552 218.336 633.424 225.488 614.496 241.584 607.216 257.712 599.968 276.576 607.088 283.888 623.088 286.64 629.12 352.928 769.488 506.576 769.488 507.584 769.488 508.576 769.456 509.584 769.456 672.896 767.552 738.368 624.768 739.024 623.344 746.176 607.216 765.024 599.872 781.264 607.152 797.392 614.336 804.672 633.248 797.456 649.408 794.176 656.8 714.208 831.056 510.336 833.456ZM671.504 479.84C636.224 479.84 607.664 451.232 607.664 415.984 607.664 380.768 636.224 352.176 671.504 352.176 706.768 352.176 735.344 380.768 735.344 415.984 735.344 451.232 706.768 479.84 671.504 479.84ZM351.504 479.84C316.224 479.84 287.664 451.232 287.664 415.984 287.664 380.768 316.224 352.176 351.504 352.176 386.768 352.176 415.344 380.768 415.344 415.984 415.344 451.232 386.768 479.84 351.504 479.84Z" p-id="4581" fill="#ae8878"></path></svg>
                  等您好久了 <br>
                  在右侧工作区生成图片吧~
                </div>
              </template>
            </div>
          </div>
        </div>
        </div>
      </div>
    </div>
    <product-repo-modal ref="productRepoModal" @setImageList="setImageList"></product-repo-modal>
  </div>
</template>

<script>

import { api } from "@/api/api";
import { getToken } from '@/utils/auth'
import downloadUtil from "@/utils/downloadUtil";
import { genCidHex16, fetchStreamText } from '@/utils/index'
import request from '@/utils/request'
import productRepoModal from './components/productRepoModal'
import draggable from "vuedraggable"; 
// 引入 Swiper 及样式
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'
export default {
  components: {
    productRepoModal,
    draggable
  },
  data() {
    return {
      action: api.fileUrl,
      uploading: false,
      comfirmLoading: false,
      viewLoading: false,
      resultImage: '',
      pagesData: {},
      pagesId: null,
      replaceIndex: null,
      tabParentIndex: 0,
      replaceTabIndex: null,
      isSave: false,
      workId: null,
      hasTabs: null,
      ruleForm: {
        imageUrl: '',
        imageList: [],
        screenDescription: '',
        imageRatioList: '',
        imageSizeSelect: '',
        imageSize: {},
        isBatch: false,
        editableTabsValue: '1',
        editableTabs: [{
          title: '图片组 1',
          name: '1',
          sku: '',
          content: []
        }],
        tabIndex: 1,
        batchCount: 1,
        clothingType: ''
      },
      swiperList: {},
      ratioList: ['3:2', '16:9', '1:1', '2:3', '3:4', '9:16'],
      clothingTypes: [
        {label: '所有上装', value: 1},
        {label: '所有下装', value: 2},
        {label: '连衣裙', value: 3},
        {label: '整套衣服', value: 4}
      ],
      rules: {
        imageUrl: [
          { validator: (rule, value, callback) => this.checkImage(rule, value, callback), trigger: "change" }
        ],
        imageList: [
          { validator: (rule, value, callback) => this.checkImageList(rule, value, callback), trigger: "change" }
        ],
        editableTabs: [
          { validator: (rule, value, callback) => this.checkImageGroup(rule, value, callback), trigger: "change" }
        ],
        screenDescription: [
          { 
            validator: (rule, value, callback) => {
              // 根据条件动态判断是否必填
              if (this.pagesData.applicationId != 3 && !value) {
                callback(new Error('请输入画面描述'))
              } else if (value.trim() && value.trim().length < 3) {
                callback(new Error('画面描述至少需要 3 个字符'))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change']
          }
        ]
      },
      hasCustom: false,
      srcList: [],
      swiper: null
    };
  },
  //页面创建的时候执行
  mounted() {
    if (!this.pagesId) {
      this.pagesId = this.$route.params.id;
    }
    // this.clearFormData();
    if (this.pagesId == 1) {
      this.pagesData = {
        title: '创意生图',
        applicationId: this.pagesId, // 1:文生图 2:图生图 3:图片生成线稿
        desc: '通过详细的文字描述，AI将为您生成符合要求的服装设计方案。',
        contentTips: '请详细描述您想要的服装款式、风格、颜色、材质等',
        placeholder: '例如:一件适合夏季穿着的波西米亚风格长裙，采用丝绸面料，以佩斯利和花纹为主，土色调为橙色和蓝色..'
      }
    }
    if (this.pagesId == 2) {
      this.pagesData = {
        title: '图生图',
        applicationId: this.pagesId, // 1:文生图 2:图生图 3:图片生成线稿
        desc: '上传参考图片，AI将基于图片内容创作新的服装设计。',
        contentTips: '请描述你希望修改或增强的元素',
        placeholder: '例如：“保持整体款式，但改为红色印花，增加轻微褶皱感”'
      }
    }
    if (this.pagesId == 3) {
      this.pagesData = {
        title: '线稿生成',
        applicationId: this.pagesId, // 1:文生图 2:图生图 3:图片生成线稿
        desc: '上传确定好的服装设计图，AI将提取静物轮廓生成专业的线稿。',
        contentTips: '请描述设计草图的关键细节',
        placeholder: '例如：“画出正反面线稿，重点表现领口、袖口和裙摆褶皱”'
      }
    }
  },

  computed: {
    token() {
      return getToken();
    },
    imageSizes() {
      return [
        {label: '1600x1600', value: '1600x1600'},
        {label: '1800x2400', value: '1800x2400'},
        {label: '1600x2400', value: '1600x2400'},
        {label: '1080×1350', value: '1080×1350'},
        {label: '1200×1500', value: '1200×1500'},
        {label: '1920×1080', value: '1920×1080'},
        {label: '2000×2000', value: '2000×2000'}
      ]
    }
  },
  watch: {
    'ruleForm.imageList': {
      deep: true,
      immediate: true, // 页面初次挂载时也会执行一次
      handler(newVal) {
        // 没有图片就不初始化
        if (!newVal || !newVal.length) return

        // 确保 DOM 已经渲染完毕
        this.$nextTick(() => {
          if (!this.swiper) {
            this.initSwiper() // 首次初始化
          } else {
            // this.swiper.update() // 后续新增 slide 更新
          }
        })
      }
    },
    'ruleForm.editableTabs': {
      deep: true,
      immediate: true, // 页面初次挂载时也会执行一次
      handler(newVal) {
        // 没有图片就不初始化
        if (!newVal[this.tabParentIndex] || !newVal[this.tabParentIndex].content || !newVal[this.tabParentIndex].content.length) return
        // 确保 DOM 已经渲染完毕
        this.$nextTick(() => {
          if (!this.swiperList[this.tabParentIndex]) {
            this.initSwiperGroup(this.tabParentIndex) // 首次初始化
          }
        })
      }
    },
    'ruleForm.isBatch'(val) {
      this.$nextTick(() => {
        setTimeout(() => {
          const index = this.tabParentIndex;
          const swiper = this.swiperList[index];

          if (swiper) {
            swiper.destroy(true, true);
            this.$set(this.swiperList, index, null);
          }
          if (this.swiper) {
            this.swiper.destroy(true, true);
            this.swiper = null;
          }
          this.initSwiper();

          if (val) {
            this.initSwiperGroup(index);
          }
        }, 0) // 🔥 给 el-switch / el-tabs 动画时间
      })
    }
  },
  methods: {
    handleBatch() {
      this.$nextTick(() => {
        // this.$refs.ruleForm.clearValidate()
      })
    },
    addTab(targetName) {
      this.tabParentIndex = targetName
      let newTabName = ++this.ruleForm.tabIndex + '';
      this.ruleForm.editableTabs.push({
        title: `图片组 ${targetName}`,
        name: newTabName,
        sku: '',
        content: []
      });
      this.ruleForm.editableTabsValue = newTabName;
    },
    removeTab(targetName) {
      const tabs = this.ruleForm.editableTabs

      if (tabs.length <= 1) {
        this.$message.error('至少存在一个图片组！')
        return
      }

      const tabIndex = tabs.findIndex(tab => tab.name === targetName)
      if (tabIndex === -1) return

      const hasContent = tabs[tabIndex].content.length > 0

      const doRemove = () => {
        this.handleActiveTabChange(targetName)
        this.destroySwiperByIndex(tabIndex)

        this.ruleForm.editableTabs = tabs.filter(tab => tab.name !== targetName)

        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 3000
        })
      }

      if (hasContent) {
        this.$confirm('该组有图片数据，确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(doRemove)
      } else {
        doRemove()
      }
    },
    handleActiveTabChange(removedName) {
      let activeName = this.ruleForm.editableTabsValue

      if (activeName !== removedName) return

      const tabs = this.ruleForm.editableTabs
      const index = tabs.findIndex(tab => tab.name === removedName)

      const nextTab = tabs[index + 1] || tabs[index - 1]
      this.ruleForm.editableTabsValue = nextTab ? nextTab.name : ''
    },
    destroySwiperByIndex(index) {
      const swiper = this.swiperList[index]
      if (!swiper) return

      swiper.destroy(true, true)

      // Vue 2 响应式安全删除
      this.$delete(this.swiperList, index)
    },

    clickTabs(tab) {
      const parentIndex = this.ruleForm.editableTabs.findIndex(
        item => item.name === tab.name
      )
      if (parentIndex !== -1) {
        this.tabParentIndex = parentIndex
        this.initSwiperGroup(parentIndex)
      }
    },
    toggle(item) {
      // 点击已选中 → 取消
      if (this.ruleForm.imageRatioList === item) {
        this.ruleForm.imageRatioList = '';
      } else {
        this.ruleForm.imageRatioList = item;
      }
    },
    initSwiper() {
      const container = this.$refs.swiperContainer

      if (!container) return

      // 初始化实例
      this.swiper = new Swiper(container, {
        slidesPerView: 2.5,
        slidesPerGroup: 2,
        spaceBetween: 10,
        loop: false,
        allowTouchMove: false,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      })
    },
    initSwiperGroup(parentIndex) {
      this.$nextTick(() => {
        const refName = `swiperContainer-${parentIndex}`
        const container = this.$refs[refName]

        if (!container) return

        // 防止重复初始化
        if (this.swiperList && this.swiperList[parentIndex]) {
          this.swiperList[parentIndex].destroy(true, true)
        }

        const swiper = new Swiper(container, {
          slidesPerView: 2.5,
          slidesPerGroup: 2,
          spaceBetween: 10,
          loop: false,
          allowTouchMove: false,
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev'
          }
        })

        // 统一管理 swiper 实例
        if (!this.swiperList) {
          this.swiperList = {}
        }
        this.swiperList[parentIndex] = swiper
      })
    },
    handleCustom() {
      this.hasCustom = !this.hasCustom
      if (!this.hasCustom) {
        this.ruleForm.imageSize = {}
      }
    },
    checkImage(rule, value, callback) {
      if (!this.ruleForm.imageUrl) {
        callback(new Error('请上传图片！'));
      } else {
        callback();
      }
    },
    checkImageList(rule, value, callback) {
      if (!this.ruleForm.imageList.length) {
        callback(new Error('请至少上传一张图片！'));
      } else {
        callback();
      }
    },
    checkImageGroup(rule, value, callback) {
      const imgs = this.ruleForm.editableTabs.filter(acc => acc.content.length)
      const skus = this.ruleForm.editableTabs.filter(acc => acc.sku)
      if (!imgs.length || !skus.length) {
        if (!skus.length) {
          callback(new Error('SKU为必填项！'));
        } else {
          callback(new Error('请至少上传一组上衣图片！'));
        }
      } else {
        callback();
      }
    },
    submitForm() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          if (this.pagesData.applicationId == 2 && this.ruleForm.isBatch) {
            let keyword_1 = '整套服装';
            let keyword_2 = '那套服装';
            let defaultDescription = `任务：进行精确的虚拟服装替换。
            参考图像分析：
            请仔细查看前几张图像（[图片1], [图片2]...[倒数第二张]）。识别这些图像中模特所穿戴的{{s%}}，包括其款式、材质、颜色、图案、纹理以及在直播间灯光下的所有细节。
            目标图像定义：
            请查看最后一张图像（[最后一张图片]）。这张图片定义了目标人物的身份、面部特征、发型、当前的姿势以及所处的背景环境。
            执行操作：
            保持最后一张图像中的人物（脸、发型、身体形态）和背景完全不变。将前几张参考图像中的{{ss%}}，自然、真实地“穿”在最后一张图像的人物身上。
            细节要求：
            1. 新的服装必须完美贴合目标人物的当前姿势。
            2. 必须根据最后一张图像中的环境光线，在衣服上生成极其真实的褶皱、阴影和高光。
            3. 确保服装的材质感（如棉麻、丝绸、牛仔等）得到完美还原。`;
            if (this.ruleForm.clothingType) {
              const keywords = this.clothingTypes.filter(acc => acc.value == this.ruleForm.clothingType);
              if (keywords.length) {
                keyword_1 = keywords[0].label;
                keyword_2 = keywords[0].label;
              }
            }
            defaultDescription = defaultDescription.replace(/{{s%}}/g, keyword_1).replace(/{{ss%}}/g, keyword_2);
            this.comfirmLoading = true;
            let payload = {
              sessionId: `${Date.now() + 10}_${genCidHex16()}`,
              applicationId: 5,
              prompt: this.ruleForm.screenDescription || defaultDescription,
              poseImages: this.ruleForm.imageList,
              count: this.ruleForm.batchCount,
              clothesItems: this.ruleForm.editableTabs.map(acc => {
                return {
                  sku: acc.sku,
                  clothesImages: acc.content
                }
              })
            }
            request({
              url: '/imageTask/submit',
              method: 'post',
              data: payload
            }).then(res => {
              if (res.code == 200) {
                this.$router.push(`/cropList/cropListIndex`);
                this.$message.success(res.msg || '操作成功!');
              }
            }).finally(() => {
              this.comfirmLoading = false;
            })
            return;
          }
          this.comfirmLoading = true;
          this.workId = null;
          this.isSave = false;
          let payload = {
            sessionId: `${Date.now() + 10}_${genCidHex16()}`,
            applicationId: this.pagesData.applicationId,
            prompt: this.ruleForm.screenDescription
          }
          let ajaxName = 'textMessage'
          if (this.pagesData.applicationId == 2) {
            // 图生图
            ajaxName = 'imageMessage'
            let imageRatio = []
            if (this.ruleForm.imageRatioList) {
              imageRatio = this.ruleForm.imageRatioList.trim().split(':').map(s => Number(s.trim()))
            }
            let imageSize = []
            if (this.ruleForm.imageSizeSelect) {
              imageSize = this.ruleForm.imageSizeSelect.split(/[×xX*]/).map(Number)
            }
            if (this.ruleForm.imageSize.height && this.ruleForm.imageSize.width) {
              imageSize = [this.ruleForm.imageSize.width, this.ruleForm.imageSize.height]
            }
            payload = {
              sessionId: `${Date.now() + 10}_${genCidHex16()}`,
              applicationId: this.pagesData.applicationId,
              prompt: this.ruleForm.screenDescription,
              images: this.ruleForm.imageList
            }
            if (imageRatio.length) {
              payload.ratio = imageRatio;
            }
            if (imageSize.length) {
              payload.imageSize = imageSize;
            }
          }

          if (this.pagesData.applicationId == 3) {
            ajaxName = 'generateSketch'
            payload = {
              sessionId: `${Date.now() + 10}_${genCidHex16()}`,
              applicationId: this.pagesData.applicationId,
              prompt: this.ruleForm.screenDescription,
              image: this.ruleForm.imageUrl
            }
          }
          try {
            const result = await fetchStreamText(`/app/ai/send/${ajaxName}`, payload, {
              onChunk: (chunk) => {
                console.log('实时分片：', chunk)
                // this.replyText += chunk // Vue 可实时更新聊天内容
              }
            })
            try {
              if (result && typeof result == 'string') {
                console.log('完整文本:', result)
                const data = JSON.parse(result)
                if (result.code == 200) {
                  this.resultImage = data.image
                  this.srcList = [data.image]
                } else {
                  if (result.code == 401) {
                    this.$router.push(`/login`);
                  } else {
                    this.$message.error(result.msg || result.errorContent || '请求出错，请联系管理员！');
                  }
                }
              } else {
                console.log('JSON 对象12', result)
                if (result.code == 200) {
                  this.resultImage = result.image
                  this.srcList = [result.image]
                } else {
                  if (result.code == 401) {
                    this.$router.push(`/login`);
                  } else {
                    this.$message.error(result.msg || result.errorContent || '请求出错，请联系管理员！');
                  }
                  
                }
              }
            } catch (e) {
              console.error('报错：', e)
            }
          } catch (e) {
            console.error('请求错误：', e)
          } finally {
            this.comfirmLoading = false
          }
        }
      });
    },
    clearFormData() {
      this.$nextTick(() => {
        this.ruleForm = {
          imageUrl: '',
          imageList: [],
          screenDescription: '',
          imageRatioList: '',
          imageSizeSelect: '',
          imageSize: {}
        }
        this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
      })
    },
    resetForm() {
      this.$confirm("确定要清空所有选项吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.clearFormData()
        this.$notify({
          title: "成功",
          message: "操作成功",
          type: "success",
          duration: 3000
        });
      });
    },
    replaceFile(itemIndex) {
      this.replaceIndex = itemIndex

      if (this.$refs.uploadRef) {
        // 清空上传队列
        this.$refs.uploadRef.uploadFiles = []

        // 手动触发上传框选择文件
        const input = this.$refs.uploadRef.$el.querySelector('input[type=file]')
        input.click()
      }
      // 在 handleSuccess 中会替换对应文件
    },
    beforeUploadVideo(file) {
      this.uploading = true;
      const isLt10M = file.size / 1024 / 1024 < 200;
      const imagesTypes = ['image/png','image/jpeg','image/webp']
      if (!imagesTypes.includes(file.type)) {
        this.uploading = false;
        this.$message.error('图片只能是jpg、png和webp格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过20MB哦!');
        return false;
      }
      return true
    },
    handleVideoSuccess(res, file) {
      this.uploading = false
      this.$refs.ruleForm.clearValidate(['imageList']);
      this.$refs.ruleForm.clearValidate(['imageUrl']);

      if (this.ruleForm.imageList.length >= 5) {
        this.$message.error('最多只能上传5张图片！');
        return;
      }
      if (this.pagesData.applicationId == 2) {
        if (this.replaceIndex !== null) {
          // 用新图片替换原有 URL
          if (res.code == 200) {
            this.$set(this.ruleForm.imageList, this.replaceIndex, res.data.url)
          }
          this.replaceIndex = null
        } else {
          // 新增上传
          if (res.code == 200) {
            this.ruleForm.imageList.push(res.data.url)
          } else {
            this.$message.error('上传失败，请重新上传！');
          }
          this.$nextTick(() => {
            if (this.swiper) {
              this.swiper.update()
              const lastIndex = this.ruleForm.imageList.length - 1
              this.swiper.slideTo(lastIndex, 300) // 平滑滚动到最后
            } else {
              this.initSwiper()
            }
          })
        }
      } else {
        if (res.code == 200) {
          this.ruleForm.imageUrl = res.data.url
        } else {
          this.$message.error('上传失败，请重新上传！');
        }
      }
    },
    imgUploadDel(itemIndex) {
      //删除
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (this.pagesData.applicationId == 2) {
          this.ruleForm.imageList.splice(itemIndex, 1);
          this.swiper.update()
        } else {
          this.ruleForm.imageUrl = ''
        }
        if (this.ruleForm.imageList.length == 0) {
          if (this.swiper) {
            this.swiper.destroy(true, true)  // 完全销毁 Swiper
            this.swiper = null
          }
        }
        
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
      });
    },
    replaceFileGroup(itemIndex, parentIndex) {
      this.replaceTabIndex = itemIndex

      if (this.$refs[`uploadRef-${parentIndex}`]) {
        // 清空上传队列
        this.$refs[`uploadRef-${parentIndex}`][0].uploadFiles = []

        // 手动触发上传框选择文件
        const input = this.$refs[`uploadRef-${parentIndex}`][0].$el.querySelector('input[type=file]')
        input.click()
      }
      // 在 handleSuccess 中会替换对应文件
    },
    handleVideoSuccessGroup(res, file) {
      this.uploading = false
      this.$refs.ruleForm.clearValidate(['editableTabs']);

      // if (this.ruleForm.editableTabs[this.tabParentIndex].content.length >= 5) {
      //   this.$message.error('最多只能上传5张图片！');
      //   return;
      // }
      if (this.replaceTabIndex !== null) {
        // 用新图片替换原有 URL
        if (res.code == 200) {
          this.$set(this.ruleForm.editableTabs[this.tabParentIndex].content, this.replaceTabIndex, res.data.url);
        }
        this.tabParentIndex = null
      } else {
        // 新增上传
        if (res.code == 200) {
          this.ruleForm.editableTabs[this.tabParentIndex].content.push(res.data.url)
        } else {
          this.$message.error('上传失败，请重新上传！');
        }
        this.$nextTick(() => {
          if (this.swiperList[this.tabParentIndex]) {
            this.swiperList[this.tabParentIndex].update()
            const lastIndex = this.ruleForm.editableTabs[this.tabParentIndex].content.length - 1
            this.swiperList[this.tabParentIndex].slideTo(lastIndex, 300) // 平滑滚动到最后
          } else {
            this.initSwiper()
          }
        })
      }
      
    },
    imgUploadDelGroup(itemIndex) {
      //删除
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.ruleForm.editableTabs[this.tabParentIndex].content.splice(itemIndex, 1);
        this.swiperList[this.tabParentIndex].update()
        if (this.ruleForm.editableTabs[this.tabParentIndex].content.length == 0) {
          if (this.swiperList[this.tabParentIndex]) {
            this.swiperList[this.tabParentIndex].destroy(true, true)
            delete this.swiperList[this.tabParentIndex]
          }
        }
        
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
      });
    },
    clearDescription() {
      this.$refs.ruleForm.clearValidate(['screenDescription']);
      this.ruleForm.screenDescription = ''
    },
    openPreview() {
      this.$refs.imgRef.$el.click()
    },
    // 视频下载
    async handleDownload() {
      const match = this.resultImage.match(/\/([^\/?#]+)$/);
      if (match) {
        this.viewLoading = true
        const fileName = match[1]
        try {
          const res = await downloadUtil.fileDownload(this.resultImage, fileName);
          if (res) {
            this.$message.success("下载成功");
          }
        } catch (error) {
          this.$message.error(error.message);
        } finally {
          this.viewLoading = false
        }
      }
    },
    saveUserWork() {
      if (this.workId) {
        this.updateUserWork(false);
        return;
      }
      this.viewLoading = true
      request({
        url: '/userWork/add',
        method: 'post',
        data: {
          applicationId: this.pagesData.applicationId,
          image: this.resultImage
        }
      }).then(res => {
        if (res.code == 200) {
          this.isSave = true;
          this.workId = res.data;
          this.$message.success(res.msg || '操作成功!');
        }
      }).finally(() => {
        this.viewLoading = false
      })
    },
    updateUserWork(bool) {
      this.viewLoading = true
      request({
        url: '/userWork/updateDeleteStatus',
        method: 'post',
        data: {
          id: this.workId || '',
          deleted: bool
        }
      }).then(res => {
        if (res.code == 200) {
          this.isSave = !bool;
          this.$message.success(res.msg || '操作成功!');
        }
      }).finally(() => {
        this.viewLoading = false
      })
    },
    setImageList(row = [], dels = []) {
      const isTabs = this.hasTabs === 'tabs';
      const parentIndex = this.tabParentIndex;

      // 1️⃣ 取目标图片数组
      const targetList = isTabs
        ? this.ruleForm.editableTabs[parentIndex].content
        : this.ruleForm.imageList;

      // 2️⃣ 新增图片（去重）
      row.forEach(item => {
        if (!targetList.includes(item)) {
          targetList.push(item);
        }
      })

      // 3️⃣ 删除图片（安全方式）
      if (Array.isArray(dels) && dels.length) {
        const keepSet = new Set(row);
        for (let i = targetList.length - 1; i >= 0; i--) {
          if (!keepSet.has(targetList[i])) {
            targetList.splice(i, 1);
          }
        }
      }

      // 4️⃣ Swiper 更新
      this.$nextTick(() => {
        if (isTabs) {
          const swiper = this.swiperList[parentIndex];
          swiper ? swiper.update() : this.initSwiperGroup(parentIndex);
        } else {
          this.swiper ? this.swiper.update() : this.initSwiper();
        }
      })
    },

    handleProductRepo(type) {
      if (this.$refs.productRepoModal) {
        if (type === 'tabs') {
          this.hasTabs = type;
          this.$refs.productRepoModal.show(this.ruleForm.editableTabs[this.tabParentIndex].content, type);
        } else {
          this.hasTabs = null;
          this.$refs.productRepoModal.show(this.ruleForm.imageList, this.ruleForm.isBatch ? 'tabs' : null);
        }
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "@/styles/layout.scss";
@import "./design-agent.scss";
</style>
