<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 prop="imageList" required v-if="pagesData.applicationId == 2">
                    <template #label>
                      <div class="label-title">
                        <span><em class="no">1</em> 上传图片</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">
                          <div class="swiper-wrapper">
                            <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>
                          </div>
                          <!-- 左右箭头 -->
                          <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">
                          <i class="el-icon-plus" v-if="ruleForm.imageList.length"></i>
                          <div class="el-upload__info" v-else>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">点击或将图片拖拽到这里上传，最多上传 5 张图片</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="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' : '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>
                    </template>
                    <el-input
                      type="textarea"
                      :rows="5"
                      :placeholder="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>
                  <template v-if="pagesData.applicationId == 2">
                    <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>
  </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'
// 引入 Swiper 及样式
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'
export default {
  components: {
  },
  data() {
    return {
      action: api.fileUrl,
      uploading: false,
      comfirmLoading: false,
      viewLoading: false,
      resultImage: '',
      pagesData: {},
      pagesId: null,
      replaceIndex: null,
      isSave: false,
      workId: null,
      ruleForm: {
        imageUrl: '',
        imageList: [],
        screenDescription: '',
        imageRatioList: '',
        imageSizeSelect: '',
        imageSize: {}
      },
      ratioList: ['3:2', '16:9', '1:1', '2:3', '3:4', '9:16'],
      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" }
        ],
        screenDescription: [
          { 
            validator: (rule, value, callback) => {
              // 根据条件动态判断是否必填
              if (this.pagesData.applicationId != 3 && !value) {
                callback(new Error('请输入画面描述'))
              } else if (value && value.length < 3) {
                callback(new Error('画面描述至少需要 3 个字符'))
              } else {
                callback()
              }
            },
            trigger: ['blur']
          }
        ]
      },
      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: '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 更新
          }
        })
      }
    }
  },
  methods: {
    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,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      })
    },
    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();
      }
    },
    submitForm() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          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 {
                  this.$message.error(data.msg || data.errorContent || '请求出错，请联系管理员！');
                }
              } else {
                console.log('JSON 对象12', result)
                if (result.code == 200) {
                  this.resultImage = result.image
                  this.srcList = [result.image]
                } 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

      // 清空上传队列
      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 {
        if (res.code == 200) {
          this.ruleForm.imageUrl = res.data.url
        } else {
          this.$message.error('上传失败，请重新上传！');
        }
      }
    },
    imgUploadDel(groupIndex, 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 = ''
        }
        
        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
      })
    }
  }
};
</script>

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