<template>
  <div class="design-container AI-Design-container">
    <div class="header">
      <van-nav-bar title="外墙设计" left-arrow @click-left="returnPage" @click-right="toHome">
        <template #right>
          <van-icon name="wap-home-o" color="#333" size="26" />
        </template>
      </van-nav-bar>
    </div>
    <div class="container">
      <!-- 历史生图 -->
      <div class="history-section padded-lr-20">
        <div class="history-header" @click="viewHistory">
          <van-icon name="clock-o" color="#EC8868" />
          <span>历史生图</span>
          <span v-if="!readState" class="badge-dot"></span>
        </div>
      </div>
      <!-- 关联项目 -->
      <div class="image-selection padded-lr-20" v-show="projectBoxShow">
        <div class="project-placeholder">
          <div class="project-add-box">
            <span style="font-weight: 700;"><span style="color: red;margin-right: 5px;">*</span>关联项目</span>
            <van-popover placement="bottom-end" :offset="[17, 4]" v-model="showProjectPopover" theme="dark"
              trigger="click">
              <div role="menu" class="van-popover__content">
                <div role="menuitem" class="van-popover__action van-popover__action--with-icon" @click="toProjectLink">
                  <img width="30px" :src="require('@/assets/AIDesign/projectIcon.png')" alt="">
                  <div class="van-popover__action-text van-hairline--bottom">我要报备</div>
                </div>
              </div>
              <template #reference>
                <van-icon name="plus" size="20" />
              </template>
            </van-popover>
          </div>
          <div class="list-item-checked" v-if="checkedProject != null">
            <div class="title-item" v-show="checkedProject.fulladdress">
              <span class="title" style="text-align: left;">{{ checkedProject.fulladdress }}</span>
              <span class="status">已报备</span>
            </div>
            <div class="user-item" v-show="checkedProject.contact">
              <van-icon name="user-o" />
              <span class="txt">{{ checkedProject.contact }}</span>
            </div>
            <div class="user-item" v-show="checkedProject.tel">
              <van-icon name="phone-o" />
              <span class="txt">{{ checkedProject.tel }}</span>
            </div>
            <!-- <div class="user-item">
              <van-icon name="info-o" color="#D43030" />
              <span class="txt" style="color: #D43030;">剩余免费生成次数：{{ checkedProject.AvailableQuantity }}</span>
            </div> -->
          </div>
          <div class="placeholder" style="width: 100%">
            <p v-if="checkedProject == null" class="placeholder-text">当前暂无已关联的项目，请选择已报备项目</p>
            <van-button type="primary" color="#2484F2" block @click="chooseProject" :loading="showChooseProject"
              :disabled="showChooseProject" loading-type="spinner" loading-text="选择项目"
              style="width: 80%;margin-left: 10%;">选择项目</van-button>
          </div>
        </div>
      </div>
      <!-- 图片选择 -->
      <div class="image-selection padded-lr-20">
        <div class="image-placeholder">
          <div v-if="selectedImage" class="selected-image-preview">
            <img :src="selectedImage" alt="预览图片" class="preview-image" @click="imgClick(selectedImage)" />
          </div>
          <div v-else class="placeholder">
            <img width="50" :src="require('@/assets/AIDesign/picture.png')" />
            <p class="placeholder-text">请上传一张待设计外墙的房屋照片</p>
            <p class="placeholder-text-tit">（避免模糊、光线不佳）</p>
          </div>
          <div class="image-buttons">
            <!-- 原生上传按钮 -->
            <div class="upload-container">
              <input type="file" accept="image/*" class="native-upload-input" @change="handleFileChange">
              <button class="image-btn">
                <span>选择图片</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- 服务商不展示 -->
      <section v-show="wecomType != 2" class="padded-lr-20">
        <van-tabs v-model="activeName" @change="tabsChange" title-active-color="#383838" color="#383838"
          title-inactive-color="#b3b3b3" line-width="78" line-height="4">
          <van-tab title="外墙质感" name="外墙质感"></van-tab>
          <van-tab title="外墙平涂" name="外墙平涂"></van-tab>
        </van-tabs>
      </section>
      <!-- 外墙质感选项 -->
      <section v-show="activeName === '外墙质感'" class="padded-lr-20">
        <!-- 设计风格 -->
        <div class="design-option">
          <div class="option-title option-title-tit">
            <div>设计风格</div>
            <van-popover v-model="showPopover" trigger="click" :actions="popover_actions" placement="right"
              custom-class="my-custom-popup">
              <template #reference>
                <van-icon name="info-o" color="#2484F2" size="16" />
              </template>
            </van-popover>
          </div>
          <div class="option-grid stone-colors-grid" ref="designsRef">
            <div v-for="(style, index) in designStyles" :key="index" class="option-item"
              :class="{ active: DesignStyle === style.value }" @click="selectStyle(style.value, 'designsRef', index)">
              <img :src="imgBaseUrl + style.imgPath" alt="" class="style-image" />
              <div class="style-name">{{ style.text }}</div>
            </div>
            <div class="rightArrows">
              <img width="12" :src="require('@/assets/AIDesign/rightjt.png')" />
            </div>
          </div>
        </div>

        <!-- 仿石漆电子色卡 -->
        <div class="design-option">
          <div class="option-title">仿石漆电子色卡</div>
          <div class="option-grid stone-colors-grid" ref="stoneColorsRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(color, index) in stoneColors" :key="index" class="option-item"
              :class="{ active: ColorCard === color.value }" @click="selectColor(color.value, 'stoneColorsRef', index)">
              <div class="split-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${color.imgPath})` }"></div>
              <div class="split-name">{{ color.text }}</div>
            </div>
          </div>
          <div class="rightArrows">
            <img width="12" :src="require('@/assets/AIDesign/rightjt.png')" />
          </div>
        </div>

        <!-- 墙面工艺 -->
        <div class="design-option">
          <div class="option-title">墙面工艺</div>
          <div class="option-grid stone-colors-grid" ref="processesRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(process, index) in deepSlotProcesses" :key="index" class="option-item"
              :class="{ active: selectedProcess === process.value }"
              @click="selectProcess(process.value, 'processesRef', index)">
              <div v-if="process.value" class="split-icon"
                :style="{ backgroundImage: `url(${imgBaseUrl}${process.imgPath})` }"></div>
              <div v-else class="split-icon">
                <img width="50" :src="require('@/assets/AIDesign/nothing1.png')" />
              </div>
              <div class="split-name">{{ process.text }}</div>
            </div>
          </div>
        </div>
        <!-- 墙面分割线 -->
        <div class="design-option" v-show="selectedProcess != '无'">
          <div class="option-title">墙面分割线</div>
          <div class="option-grid stone-colors-grid" ref="splitsRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(split, index) in splitWays" :key="index" class="option-item"
              :class="{ active: selectedSplit === split.value }" @click="selectSplit(split.value, 'splitsRef', index)">
              <div class="split-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${split.imgPath})` }"></div>
              <div class="split-name">{{ split.text }}</div>
            </div>
          </div>
        </div>
        <!-- 罗马柱样式 -->
        <div class="design-option" v-if="ColumnTypes.length > 0">
          <div class="option-title">罗马柱</div>
          <div class="option-grid stone-colors-grid" ref="ColumnTypeRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(Column, index) in ColumnTypes" :key="index" class="option-item"
              :class="{ active: selectedColumnType === Column.value }"
              @click="selectColumnType(Column.value, 'ColumnTypeRef', index)">
              <div class="railing-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${Column.imgPath})` }"></div>
              <div class="railing-name">{{ Column.text }}</div>
              <div v-show="Column.value != '无' && Column.value != 'CUSTOM'" class="magnifyingGlassBox"
                @click.stop="openComponentPreview(index - 1)">
                <img :src="require('@/assets/AIDesign/magnifyingGlassIcon.png')" />
              </div>
            </div>
          </div>
        </div>
        <!-- 罗马柱图片预览 -->
        <van-image-preview v-model="showPreviewList" :images="imgValuesArray" @change="onChangePreviewList" :loop="true"
          :start-position="startIndex">
          <template v-slot:index>
            {{ currentTitle }} ({{ currentIndex + 1 }}/{{ imgValuesArray.length }})
          </template>
        </van-image-preview>
        <!-- 浇筑栏杆 -->
        <div class="design-option">
          <div class="option-title">栏杆</div>
          <div class="option-grid stone-colors-grid" ref="railingsRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(railing, index) in railings" :key="index" class="option-item"
              :class="{ active: selectedRailing === railing.value }"
              @click="selectRailing(railing.value, 'railingsRef', index)">
              <div class="railing-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${railing.imgPath})` }"></div>
              <div class="railing-name">{{ railing.text }}</div>
            </div>
          </div>
        </div>

        <!-- 窗套样式 -->
        <div class="design-option">
          <div class="option-title">窗套样式</div>
          <div class="option-grid stone-colors-grid" ref="windowsRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(windowFrame, index) in windowFrames" :key="index" class="option-item"
              :class="{ active: selectedWindowFrame === windowFrame.value }"
              @click="selectWindowFrame(windowFrame.value, 'windowsRef', index)">
              <div v-if="windowFrame.value" class="split-icon"
                :style="{ backgroundImage: `url(${imgBaseUrl}${windowFrame.imgPath})` }">
              </div>
              <div v-else class="split-icon">
                <img width="50" :src="require('@/assets/AIDesign/nothing1.png')" />
              </div>
              <div class="split-name">{{ windowFrame.text }}</div>
            </div>
          </div>
          <div class="rightArrows">
            <img width="12" :src="require('@/assets/AIDesign/rightjt.png')" />
          </div>
        </div>
        <!-- 墙裙 -->
        <div class="design-option">
          <div class="option-title">墙裙</div>
          <div class="option-grid stone-colors-grid" ref="skirtTypesRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(skirt, index) in skirtTypes" :key="index" class="option-item"
              :class="{ active: selectedSkirtType === skirt.value }"
              @click="selectSkirtType(skirt.value, 'skirtTypesRef', index)">
              <div class="tile-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${skirt.imgPath})` }"></div>
              <div class="tile-name">{{ skirt.text }}</div>
            </div>
          </div>
          <div class="rightArrows">
            <img width="12" :src="require('@/assets/AIDesign/rightjt.png')" />
          </div>
        </div>
        <!-- 琉璃瓦 -->
        <div class="design-option">
          <div class="option-title">琉璃瓦</div>
          <div class="option-grid stone-colors-grid" ref="tilesRef" @mousedown="handleMouseDown"
            @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
            <div v-for="(tile, index) in tiles" :key="index" class="option-item"
              :class="{ active: selectedTile === tile.value }" @click="selectTile(tile.value, 'tilesRef', index)">
              <div class="tile-icon" :style="{ backgroundImage: `url(${imgBaseUrl}${tile.imgPath})` }"></div>
              <div class="tile-name">{{ tile.text }}</div>
            </div>
          </div>
          <div class="rightArrows">
            <img width="12" :src="require('@/assets/AIDesign/rightjt.png')" />
          </div>
        </div>
      </section>
      <!-- 外墙平涂选项 -->
      <section v-show="activeName === '外墙平涂'" class="radio-group-container1">
        <!--外墙平涂-放大版 -->
        <div class="color-plus" v-if="color_selItem">
          <div class="cardImg" :style="{ backgroundColor: color_selItem.value.slice(0, 7) }"></div>
          <div class="color-plus-info">
            <div class="color-plus-tit">{{ color_selItem.text }}</div>
            <p>{{ color_selItem.ext1 }}</p>
          </div>
        </div>
        <van-radio-group v-model="color_selValue" class="custom-radio-group4 padded-lr-20" @change="handleColorChange">
          <van-radio v-for="(item, index) in color_options" :key="index" :name="item.value"
            class="custom-radio custom-radio4">
            <div class="radio-content radio-content-color">
              <div class="cardImg" :style="{ backgroundColor: item.value.slice(0, 7) }"></div>
              <div v-if="color_selValue === item.value" class="check-indicator">
                <van-icon name="success" color="#fff" size="10" />
              </div>
              <div class="custom-radio-text">{{ item.text }}</div>
            </div>
          </van-radio>
        </van-radio-group>
      </section>
      <!-- AI生成按钮 -->
      <div class="generate-section padded-lr-20">
        <van-button v-show="AIBtnDisabled" type="primary" block color="#E87838" disabled loading loading-type="spinner"
          loading-text="AI生成"></van-button>
        <van-button v-show="!AIBtnDisabled" type="primary" block @click="generateDesign"
          color="#E87838">AI生成</van-button>
        <div class="btn-note">*效果图仅供参考, 不作为交付标准</div>
      </div>
    </div>
    <van-action-sheet v-model="projectActionShow">
      <div class="project-action-box">
        <img src="../../assets/AIDesign/project_action_null.png">
        <div class="tip">您还没有已报备的项目</div>
        <div class="tip-content">创建一个报备项目后，就能进行AI生图！<br />快去试试吧~</div>
        <div class="btn" @click="toProjectLink">我要报备</div>
        <div class="btn2" @click="projectActionShow = false">稍后再说</div>
      </div>
    </van-action-sheet>
    <van-action-sheet v-model="projectActionNumShow">
      <div class="project-action-box">
        <img src="../../assets/AIDesign/project_action_num_0.png">
        <div class="tip" style="margin-top: 20px;">该项目的免费生成次数已用完</div>
        <div class="tip-content">希望这3张AI效果图能满足您的设计需求，<br />如需进一步沟通，可点击<span
            style="color: #2484F2;text-decoration: underline;" @click="toXiaoCX">转人工设计</span></div>
        <div class="btn" @click="projectActionNumShow = false">我知道了</div>
      </div>
    </van-action-sheet>
    <van-action-sheet v-model="projectActionLoadingShow">
      <div class="project-action-box">
        <img src="../../assets/AIDesign/project_action_loading.png">
        <div class="tip" style="margin-top: 20px;">正在为您飞速上传...</div>
        <div class="tip-content">为了给您更好的生图效果，请避免上传模糊、光线不佳、非外墙的图片。<br />立邦AI效果图仅为意向图，不作为施工交付标准。</div>
        <div class="btn" @click="projectActionLoadingShow = false">我知道了</div>
      </div>
    </van-action-sheet>
    <van-action-sheet v-model="projectActionListShow">
      <div class="project-action-list-box">
        <div class="search-box-bg">
          <div class="search-box">
            <van-search v-model="projectSearchValue" style="flex-grow: 1" shape="round" placeholder="项目地址/业主姓名/业主电话" />
            <van-button type="primary" size="mini" color="#2484F2" class="btn" @click="onSearch">搜索</van-button>
          </div>
        </div>
        <div style="width: 90%;height: 50px;"></div>
        <div class="list-item" :style="checkedProjectId == index ? 'border: 1px solid #2484F2;' : ''"
          v-for="(item, index) in projectList" :key="index" @click="checkedProjectId = index">
          <div class="title-item">
            <span class="title">{{ item.fulladdress }}</span>
            <span class="status">已报备</span>
          </div>
          <div class="user-item">
            <van-icon name="user-o" />
            <span class="txt">{{ item.contact }}</span>
          </div>
          <div class="user-item">
            <van-icon name="phone-o" />
            <span class="txt">{{ item.tel }}</span>
          </div>
          <!-- <div class="user-item">
            <van-icon name="info-o" color="#D43030" />
            <span class="txt" style="color: #D43030;">剩余免费生成次数：{{ item.AvailableQuantity }}</span>
          </div> -->
          <div class="img-item" v-show="checkedProjectId == index">
            <img src="../../assets/AIDesign/project_checked.png" class="img-checked">
          </div>
        </div>
        <div style="width: 90%;height: 80px;"></div>
        <div class="btn-box">
          <div class="btn-item">
            <img src="../../assets/AIDesign/project_btn_left_icon.png" class="img-left-icon">
            <div class="btn" @click="chooseSure">确认选择</div>
          </div>
        </div>
      </div>
    </van-action-sheet>
    <van-dialog v-model="dialogShow" :show-confirm-button="false">
      <div class="dialog-box">
        <div class="dialog-content">{{ dialogContent }}</div>
        <!-- <div class="dialog-btn" @click="dialogShow = false">知道了（{{countdownValue}}）</div> -->
        <div class="dialog-btn" @click="dialogShow = false">知道了</div>
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { CreateDesign, GetEntity, GetReadState, UpdateReadState, GetProjectlist, GetDictList } from "@/api/indexAI";
import { ImagePreview, Popover } from 'vant';
import { Dialog } from 'vant';
import { getWecomType, toLBHome, toXiaoChengxu } from '@/utils/index';
declare let wx: any;
import axios from "axios";

@Component({
  components: {
    VanPopover: Popover,
    VanImagePreview: ImagePreview.Component
  },
})
export default class extends Vue {
  // 添加鼠标拖拽相关引用
  $refs!: {
    stoneColorsRef: HTMLDivElement;
    processesRef: HTMLDivElement;
    splitsRef: HTMLDivElement;
    windowsRef: HTMLDivElement;
    railingsRef: HTMLDivElement;
    tilesRef: HTMLDivElement;
    skirtTypesRef: HTMLDivElement;
  };

  private readState = true;
  private projectActionShow = false;
  private projectActionNumShow = false;
  private projectActionListShow = false;
  private projectActionLoadingShow = false;

  // 添加鼠标拖拽相关数据
  private isMouseDown = false;
  private startX = 0;
  private scrollLeft = 0;
  private currentScrollElement: HTMLElement | null = null;

  private addProjectLink = '';
  private serviceCodeArray = [];
  private countdownValue = 3;
  private countdownInterval;
  private isRunning = false;
  private dialogShow = false;
  private dialogContent = '';
  private AIBtnDisabled = false;
  private projectBoxShow = false;
  private save_projectBoxShow_org = false;
  private projectSearchValue = '';
  private checkedProjectId = null;
  private checkedProject = null
  private projectList = [];
  private wecomType = null;
  private selectedImage: string | null = null;  // 存储选择的图片
  // 当前选中的选项
  private oldf_id = null;
  private Userfile1 = null;

  private designStyles = []; // 设计风格选项
  private stoneColors = [];// 仿石漆电子色卡选项
  private deepSlotProcesses = []; // 墙面工艺选项
  private splitWays = [];// 墙面分割线选项
  private windowFrames = [];// 窗套样式选项
  private railings = []; // 浇筑栏杆选项
  private tiles = []; // 琉璃瓦选项
  private ColumnTypes = [];// 罗马柱选项
  private skirtTypes = [];// 墙裙

  // 外墙质感
  private DesignStyle = null;//设计风格
  private ColorCard = null;//电子色卡
  private selectedProcess = null;//墙面工艺
  private selectedSplit = null;//墙面分割线
  private selectedColumnType = null;//罗马柱
  private selectedRailing = null;//栏杆
  private selectedWindowFrame = null;//窗套样式
  private selectedTile = null;//琉璃瓦
  private selectedSkirtType = null;//墙裙


  private color_options = [];//外墙平涂列表
  private color_selItem = null;//选中的外墙平涂
  private color_selValue = '';// 外墙平涂选中的值

  private activeName = "外墙质感";// tab选中的项
  private imgBaseUrl = '';//图片头
  private isNeedProject = null;//是否展示项目

  private showPreviewList = false;//罗马柱图片预览
  private imgValuesArray = [];//罗马柱图片列表
  private titlesArray = [];//罗马柱名称列表
  private startIndex = 0;//罗马柱预览开始索引
  private currentIndex = 0;//罗马柱预览索引
  private currentTitle = null;//罗马柱预览名称

  private showPopover = false;//设计风格提示
  private popover_actions = [{ text: "风格主要对应罗马柱类型，请按需选择", className: "actionsTit" }];
  private showChooseProject = false;
  private showProjectPopover = false;
  created() {
    // this.getServiceCode();
    // 图片头
    if (window.location.href.indexOf('aidesign.') > -1) {
      this.imgBaseUrl = 'https://aidesign.nipponpaint.com.cn'
    } else {
      this.imgBaseUrl = 'https://aidesigntest.nipponpaint.com.cn'
    }
  }

  activated() {
    // 初始化数据
    this.initialize();
    this.getPicList();//获取完选项各列表之后再去判断F_id并取值
    this.GetReadStateFn();
  }
  private initialize() {
    // 企微类型
    const agentFrom = window.localStorage.getItem('agentFromAI');
    this.wecomType = getWecomType(agentFrom);
    this.selectedImage = '';
    this.projectActionLoadingShow = false;
    this.AIBtnDisabled = false;
    this.checkedProjectId = null;
    this.checkedProject = null;
    this.oldf_id = null;
    this.Userfile1 = null;
    this.DesignStyle = null;
    this.ColorCard = null;
    this.selectedProcess = null;
    this.selectedSplit = null;
    this.selectedWindowFrame = null;
    this.selectedRailing = null;
    this.selectedColumnType = null;//罗马柱
    this.selectedTile = null;
    this.selectedSkirtType = null;
    this.showChooseProject = false;
    this.isNeedProject = null;
    this.showPreviewList = false;
    this.imgValuesArray = [];
    this.titlesArray = [];
    this.startIndex = 0;
    this.currentIndex = 0;
    this.currentTitle = null;
    this.activeName = "外墙质感";// tab选中的项
    this.color_selItem = null;//选中的外墙平涂
    this.color_options = [];//外墙平涂列表
    this.color_selValue = '';// 外墙平涂选中的值
  }
  tabsChange(value: string) {
    if (value === '外墙平涂') {
      // 色卡默认第一个
      this.color_selItem = this.color_options[0];
      this.color_selValue = this.color_options[0].value;
      this.projectBoxShow = false;
    } else {
      this.projectBoxShow = this.save_projectBoxShow_org;
    }
  }
  // 选择外墙平涂
  handleColorChange(value: string | number) {
    const selectedItem = this.color_options.find(
      item => item.value === value
    );
    this.color_selItem = selectedItem || null;
  }
  private getServiceCode() {
    let that = this;
    const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    let serviceCodeArray = [];
    if (userInfo.loginTypeList.length > 0) {
      userInfo.loginTypeList.forEach(item => {
        if (item.shopType == 'stoneLikePaint') {
          item.shopList.forEach(childItem => {
            serviceCodeArray.push(childItem.shop_code);
          })
        }
      })
    }
    that.serviceCodeArray = serviceCodeArray;
  }
  // 处理文件选择（对应 beforeRead + afterRead）
  handleFileChange(e) {
    const file = e.target.files[0]; // 获取选中的文件
    if (!file) return; // 未选择文件直接返回

    // 1. 校验文件类型（对应 beforeRead 的类型检查）
    if (!file.type.match('image.*')) {
      this.$toast('请选择图片文件');
      this.clearInput(e.target); // 清除选择，避免重复触发同一文件
      return;
    }
    let FileSize = (file.size / 1024 / 1024).toFixed(2);
    // console.log("用户选择的图片大小=", file.size + 'KB', '  =', FileSize + 'M')
    // 2. 校验文件大小（对应 beforeRead 的大小检查）
    const maxSize = 20 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      this.$toast('图片大小不能超过10MB');
      this.clearInput(e.target);
      return;
    }

    // 3. 处理选中的文件（对应 afterRead）
    this.handleAfterRead(file);

    // 清除 input 值，确保同一文件能被再次选择
    this.clearInput(e.target);
  }

  // 处理校验通过后的文件（对应 afterRead）
  handleAfterRead(file) {
    console.log("选中的图片信息：", file);
    // 生成图片预览（如果需要，和 van-uploader 的 content 类似）
    const reader = new FileReader();
    reader.onload = (event) => {
      this.selectedImage = event.target.result; // 预览图的 base64
    };
    reader.readAsDataURL(file); // 转换为 base64

    this.Userfile1 = file; // 保存原始文件对象（用于后续上传）
  }

  // 清除 input 值（解决同一文件无法重复选择的问题）
  clearInput(input) {
    input.value = '';
  }
  beforeRead(file) {
    // 检查文件类型
    if (!file.type.match('image.*')) {
      this.$toast('请选择图片文件');
      return false;
    }
    // 检查文件大小（例如限制为10MB）
    const maxSize = 10 * 1024 * 1024;
    if (file.size > maxSize) {
      this.$toast('图片大小不能超过10MB');
      return false;
    }
    return true;
  }

  afterRead(file) {
    // console.log(file.file);
    this.selectedImage = file.content;
    this.Userfile1 = file.file;
  }

  returnPage() {
    this.$router.push({ path: "/AiDesign" });
  }
  toHome() {
    toLBHome()
  }
  imgClick(url) {
    ImagePreview([url]);
  }

  // 处理罗马柱
  openComponentPreview(initIndex: number) {
    if (this.ColumnTypes.length > 0) {
      const imgArray = this.ColumnTypes
        .filter(item => item.value != '无' && item.imgPath);
      this.imgValuesArray = imgArray.map(item => this.imgBaseUrl + item.imgPath);
      this.titlesArray = imgArray.map(item => item.text);
      this.startIndex = Math.max(0, Math.min(initIndex, this.imgValuesArray.length - 1));
      this.currentIndex = this.startIndex;
      this.currentTitle = this.titlesArray[initIndex] || "无标题";
      this.showPreviewList = true;
    } else {
      this.$toast('暂无图片');
    }
  }
  onChangePreviewList(index) {
    this.currentTitle = this.titlesArray[index] || "无标题";
    this.currentIndex = index;
  }
  GetReadStateFn() {
    const formData = new FormData();
    const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    // formData.append('WXuserid', userInfo.loginName);
    const outsideType_val = this.activeName === '外墙质感' ? 0 : 1;
    formData.append('outsideType', outsideType_val);
    GetReadState(formData).then(response => {
      if (response.StatusCode == 200) {
        this.readState = response.Data.readState;
      }
    });
  }

  UpdateReadStateFn() {
    const formData = new FormData();
    // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    // formData.append('WXuserid', userInfo.loginName);
    const outsideType_val = this.activeName === '外墙质感' ? 0 : 1;
    formData.append('outsideType', outsideType_val);
    UpdateReadState(formData).then(response => { });
  }

  GetEntityData(F_id) {
    let that = this;
    const formData = new FormData();
    formData.append('F_id', F_id);
    const outsideType_val = this.activeName === '外墙质感' ? 0 : 1;
    formData.append('outsideType', outsideType_val);
    GetEntity(formData).then(response => {
      // console.log(response);
      if (response.StatusCode == 200) {
        if (response.Data) {
          if (response.Data.F_UserFilePath) {
            this.selectedImage = response.Data.BaseUrl + response.Data.F_UserFilePath;
          }
          if (response.Data.F_Color) {
            this.DesignStyle = this.designStyles[0].value;
          } else {
            this.DesignStyle = response.Data.F_DesignStyle || this.designStyles[0].value;
          }
          this.ColorCard = response.Data.F_ColorCard || this.stoneColors[0].value;
          this.selectedProcess = response.Data.F_DeepGrooveTech || this.deepSlotProcesses[0].value;
          // 有墙面工艺
          if(this.selectedProcess ){
            const selectedProcessSelctIndex = this.deepSlotProcesses.findIndex(item => item.value === this.selectedProcess);
            // 墙面分割线选项
            this.splitWays = this.deepSlotProcesses[selectedProcessSelctIndex].subitems;
          }
          this.selectedSplit = response.Data.F_DivisionMethod || this.splitWays[0].value;
          this.selectedWindowFrame = response.Data.F_WindowsColor || this.windowFrames[0].value;
          this.selectedRailing = response.Data.F_CastRailing || this.railings[0].value;
          this.selectedTile = response.Data.F_GlazedTile || this.tiles[0].value;//新琉璃瓦
          this.selectedSkirtType = response.Data.F_SkirtType || this.skirtTypes[0].value;//墙裙
          this.oldf_id = response.Data.F_ID;
          this.color_selValue = response.Data.F_Color || null;// 外墙平涂选中的值
          if (this.color_selValue) {
            // 找到选中的外墙平涂
            const selectedItemColor = this.color_options.find(
              item => item.value === this.color_selValue
            );
            this.color_selItem = selectedItemColor;
          }
          // 判断如果不是服务商，也不用展示
          if (that.serviceCodeArray.length == 0) {
            that.projectBoxShow = false;
          } else {
            that.projectBoxShow = that.isNeedProject;
          }
          that.save_projectBoxShow_org = that.projectBoxShow;
          if (this.color_selValue) {
            this.activeName = '外墙平涂';
            this.projectBoxShow = false;
          } else if (this.ColorCard != '无') {
            this.activeName = '外墙质感';
          } else {
            this.activeName = '';
          }
          if (response.Data.ProjectID) {
            this.checkedProject = {
              projectid: response.Data.ProjectID
            }
          }
          let projectId = this.$route.query.projectId || null;
          if (projectId) {
            this.updateCheckedProjectLastNum(projectId);
          }
          // 罗马柱选项-重新渲染
          let F_ColumnType = response.Data.F_ColumnType || '无';
          if (!response.Data.F_ColumnType && response.Data.F_DesignStyle == 'CUSTOM') {
            F_ColumnType = '';
            this.ColumnTypes = [];
          } else {
            const DesignStyleSelctIndex = this.designStyles.findIndex(item => item.value === this.DesignStyle);
            const designStyles = this.designStyles;
            if (designStyles[DesignStyleSelctIndex] && designStyles[DesignStyleSelctIndex].subitems) {
              this.ColumnTypes = designStyles[DesignStyleSelctIndex].subitems || [];
            } else {
              this.ColumnTypes = [];
            }
          }
          this.selectedColumnType = F_ColumnType;//罗马柱
        }
      }
    })
  }

  // 添加一个新的辅助方法用于将图片URL转换为File对象
  private async urlToFile(url: string, filename: string): Promise<File> {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      return new File([blob], filename, { type: blob.type });
    } catch (error) {
      console.error('图片转换失败:', error);
      this.$toast('图片加载失败');
      throw error;
    }
  }

  private viewHistory() {
    this.UpdateReadStateFn();
    // console.log('查看历史生成');
    // 实现查看历史生成逻辑   
    this.$router.push({ path: '/AIDesign/history', query: { wallType: "outside" } });
  }

  // 方法
  private goBack() {
    this.$router.back();
  }

  // private takePhoto() {
  //   // 实现拍照功能
  //   console.log('拍摄图片');
  // }
  private autoScrollToActive(refsName: string, selcIndex: number) {
    // console.log("refsName=", refsName)
    const container = this.$refs[refsName];
    const activeItem = container.children[selcIndex];
    const itemWidth = activeItem.offsetWidth * 1.1;
    // 判断选中项是否完全在可视范围内
    const containerRect = container.getBoundingClientRect(); // 容器可视区域
    const itemRect = activeItem.getBoundingClientRect(); // 选中项位置
    // 完全可见的条件：左≥容器左，右≤容器右
    const isFullyVisibleL = itemRect.left >= containerRect.left;
    const isFullyVisibleR = itemRect.right <= containerRect.right;
    if (!isFullyVisibleL) {
      container.scrollBy({
        left: -itemWidth, // 右边滑一格多的距离
        behavior: 'smooth' // 平滑滚动
      });
    } else if (!isFullyVisibleR) {
      container.scrollBy({
        left: itemWidth, // 左滑一格多的距离
        behavior: 'smooth' // 平滑滚动
      });
    }
  }
  private selectStyle(value: string, refsName: string, selcIndex: number) {
    this.DesignStyle = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
    // 罗马柱
    const designStyles = this.designStyles;
    this.ColumnTypes = designStyles[selcIndex].subitems || [];
    if (designStyles[selcIndex] && designStyles[selcIndex].subitems && designStyles[selcIndex].subitems[0]) {
      this.selectedColumnType = designStyles[selcIndex].subitems[0].value;
    } else {
      this.selectedColumnType = '无';
    }
  }

  private selectColor(code: string, refsName: string, selcIndex: number) {
    this.ColorCard = code;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectProcess(value: string, refsName: string, selcIndex: number) {
    this.selectedProcess = value;
    this.splitWays = this.deepSlotProcesses[selcIndex].subitems;
    this.selectedSplit = this.splitWays[0].value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectSplit(value: string, refsName: string, selcIndex: number) {
    this.selectedSplit = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectWindowFrame(value: string, refsName: string, selcIndex: number) {
    this.selectedWindowFrame = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectRailing(value: string, refsName: string, selcIndex: number) {
    this.selectedRailing = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectTile(value: string, refsName: string, selcIndex: number) {
    this.selectedTile = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectSkirtType(value: string, refsName: string, selcIndex: number) {
    this.selectedSkirtType = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  private selectColumnType(value: string, refsName: string, selcIndex: number) {
    this.selectedColumnType = value;
    this.autoScrollToActive(refsName, selcIndex); // 选中后触发自动滚动
  }

  // 添加鼠标滚轮事件处理
  private handleWheel(e: WheelEvent) {
    const container = e.currentTarget as HTMLElement;
    if (container) {
      container.scrollLeft += e.deltaY;
    }
  }

  // 添加鼠标按下事件处理
  private handleMouseDown(e: MouseEvent) {
    this.isMouseDown = true;
    this.currentScrollElement = e.currentTarget as HTMLElement;
    if (this.currentScrollElement) {
      this.currentScrollElement.style.cursor = 'grabbing';
      this.startX = e.pageX - this.currentScrollElement.offsetLeft;
      this.scrollLeft = this.currentScrollElement.scrollLeft;
    }
  }

  // 添加鼠标移动事件处理
  private handleMouseMove(e: MouseEvent) {
    if (!this.isMouseDown) return;
    e.preventDefault();
    if (this.currentScrollElement) {
      const x = e.pageX - this.currentScrollElement.offsetLeft;
      const walk = (x - this.startX) * 2;
      this.currentScrollElement.scrollLeft = this.scrollLeft - walk;
    }
  }

  // 添加鼠标释放事件处理
  private handleMouseUp() {
    this.isMouseDown = false;
    if (this.currentScrollElement) {
      this.currentScrollElement.style.cursor = 'grab';
    }
    this.currentScrollElement = null;
  }

  private generateDesign() {
    let that = this;
    // console.log(this.Userfile1);
    // 实现AI生成功能
    if (that.projectBoxShow == true && this.activeName === '外墙质感') {
      if (that.checkedProject == null) {
        that.$toast.fail('请选择关联项目');
        return;
      }
      // if (that.checkedProject.AvailableQuantity == 0) {
      //   this.projectActionNumShow = true;
      //   return;
      // }
    }
    if (!this.Userfile1 && !this.oldf_id) {
      this.$toast.fail('请选择图片');
      return;
    }
    // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    const formData = new FormData();
    if (this.activeName === '外墙质感') {
      // 如果字典渲染有误，不让提交；墙面工艺、电子色卡都为必填项且没有不需要；
      if (!this.selectedProcess || !this.ColorCard) {
        this.$toast.fail('数据有误，请重试');
        return;
      }
      // 用户选择的选项
      const uDesignStyle = this.DesignStyle === '无' ? '' : this.DesignStyle;
      const uColorCard = this.ColorCard === '无' ? '' : this.ColorCard;
      const uSelectedProcess = this.selectedProcess === '无' ? '' : this.selectedProcess;
      let uSelectedSplit = this.selectedSplit === '无' ? '' : this.selectedSplit;
      const uWindowsColor = this.selectedWindowFrame === '无' ? '' : this.selectedWindowFrame;
      const uCastRailing = this.selectedRailing === '无' ? '' : this.selectedRailing;
      const uColumnType = this.selectedColumnType === '无' ? '' : this.selectedColumnType;//没有传空
      const uGlazedTile = this.selectedTile === '无' ? '' : this.selectedTile;
      const uSkirtType = this.selectedSkirtType === '无' ? '' : this.selectedSkirtType;
      formData.append('DesignStyle', uDesignStyle);
      formData.append('ColorCard', uColorCard);
      formData.append('DeepGrooveTech', uSelectedProcess);
      formData.append('DivisionMethod', uSelectedSplit);
      formData.append('WindowsColor', uWindowsColor);
      formData.append('CastRailing', uCastRailing);
      formData.append('GlazedTile', uGlazedTile);
      formData.append('columnType', uColumnType);//罗马柱
      formData.append('skirtType', uSkirtType);//墙裙

    } else if (this.activeName === '外墙平涂') {
      //  如果字典渲染有误，不让提交；
      if (!this.color_selValue) {
        this.$toast.fail('数据有误，请重试');
        return;
      }
      formData.append('DesignStyle', "CHANGE_COLOR");
      formData.append('Color', this.color_selValue)
    }
    // 其他项
    // let serviceCodeArray = [];
    // if (userInfo.loginTypeList.length > 0) {
    //   userInfo.loginTypeList.forEach(item => {
    //     if (item.shopType == 'stoneLikePaint') {
    //       item.shopList.forEach(childItem => {
    //         serviceCodeArray.push(childItem.shop_code);
    //       })
    //     }
    //   })
    // }
    // // 用户企微ID
    // formData.append('WXuserid', userInfo.loginName);
    // // 项目ID
    // if (this.checkedProject && this.projectBoxShow == true && this.activeName === '外墙质感') {
    //   formData.append('projectid', this.checkedProject.projectid);
    // }
    // 企微类型
    // formData.append('wecomType', 5);
    // // 服务商代码
    // if (serviceCodeArray.length > 0) {
    //   formData.append('serivceCode', serviceCodeArray.join(','));
    // }
    // // 姓名
    // formData.append('userName', userInfo.userName);
    // const customerCode = userInfo.sysUserExt && userInfo.sysUserExt.customerCode ? userInfo.sysUserExt.customerCode : '';
    // // 经销商代码
    // formData.append('distributorCode', customerCode);
    // //原服务商用户、新增经销商用户
    // // 大区
    // formData.append('regionName', userInfo.officeName || '');
    // // 公司名称
    // formData.append('companyName', userInfo.companyName || '');
    // // 员工号
    // let employeeID = userInfo.sysUserExt && userInfo.sysUserExt.sapEmployeeId ? userInfo.sysUserExt.sapEmployeeId : '';
    // formData.append('employeeID', employeeID);
    // //销售部---原服务商用户、新增经销商用户
    // formData.append('salesDepartment', userInfo.subOfficeName || '');
    // // 销售部ID
    // formData.append('salesDepartmentCode', userInfo.subOfficeCode || '');
    // 样式图片
    if (this.Userfile1) {
      formData.append('Userfile1', this.Userfile1);
    } else {
      formData.append('oldf_id', this.oldf_id);
    }
    // 遍历打印
    formData.forEach((value, key) => {
      console.log(`key: ${key}, value: ${value}`);
    });

    that.AIBtnDisabled = true;
    CreateDesign(formData).then(response => {
      // console.log(response);
      if (response.StatusCode == 200) {
        that.projectActionLoadingShow = false;
        that.AIBtnDisabled = false;
        if (that.projectBoxShow == true) {
          that.updateCheckedProjectLastNum(that.checkedProject.projectid);
        }
        window.localStorage.setItem("type", 'design');
        let projectid = null;
        if (this.checkedProject && this.checkedProject.projectid) {
          projectid = this.checkedProject.projectid;
        } else if (this.$route.query.projectId) {
          projectid = this.$route.query.projectId;
        }
        this.$router.push({
          path: '/AIDesign/result',
          query: {
            F_id: response.Data.F_ID,
            fromPage: 'design',
            wallType: 'outside',
            projectid: projectid
          }
        });
      } else if (response.StatusCode == 410) {
        that.dialogContent = response.Info;
        that.projectActionLoadingShow = false;
        that.AIBtnDisabled = false;
        that.dialogShow = true;
        // that.startCountdown();
      } else {
        that.projectActionLoadingShow = false;
        that.AIBtnDisabled = false;
        that.$toast(response.Info);
      }
    })
      .catch((err) => {
        that.projectActionLoadingShow = false;//弹窗
        that.AIBtnDisabled = false;//ai生成按钮
      })
  }

  private startCountdown() {
    let that = this;
    if (that.isRunning) return;
    that.isRunning = true;
    // startBtn.disabled = true;
    // that.countdownValue = 3;

    // that.countdownInterval = setInterval(() => {
    //     that.countdownValue--;
    //     if (that.countdownValue >= 0) {
    //         if (that.countdownValue === 0) {
    //             clearInterval(that.countdownInterval);
    //             that.isRunning = false;
    //             that.dialogShow = false;
    //         }
    //     }
    // }, 1000);
  }

  //更新选中关联项目剩余次数
  private updateCheckedProjectLastNum(projectId) {
    let that = this;
    const formData = new FormData();
    // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    // formData.append('ServiceCode', that.serviceCodeArray.join(','));
    formData.append('projectid', projectId);
    GetProjectlist(formData).then(response => {
      if (response.StatusCode == 200) {
        that.checkedProject = response.Data[0];
      } else {
        // console.log(response.Info)
      }
    });
  }

  //获取关联项目列表
  GetProjectListFn() {
    let that = this;
    const formData = new FormData();
    const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    // formData.append('ServiceCode', that.serviceCodeArray.join(','));
    if (that.projectSearchValue.trim().length != 0) {
      formData.append('keyWord', that.projectSearchValue);
    }
    GetProjectlist(formData).then(response => {
      if (response.StatusCode == 200) {
        if (response.Data.length == 0) {
          that.projectActionShow = true;
        } else {
          that.projectList = response.Data;
          that.projectActionListShow = true;
        }
      } else {
        that.projectActionShow = true;
      }
      that.showChooseProject = false;
    });
  }

  //跳转小程序
  private toXiaoCX() {
    toXiaoChengxu(`${process.env.VUE_APP_BASE_DISID6}`);
  }

  //跳转项目报备链接
  private toProjectLink() {
    this.showProjectPopover = false;
    window.location.href = this.addProjectLink;
  }

  //获取风格选项图片列表
  private getPicList() {
    let that = this;
    const formData = new FormData();
    // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
    // let roleIdArray = [];
    // if (userInfo.roles.length > 0) {
    //   userInfo.roles.forEach(item => {
    //     roleIdArray.push(item.roleId);
    //   })
    // }
    // formData.append('roleIds', roleIdArray.join(','));
    // formData.append('WXuserid', userInfo.loginName);
    formData.append('baseType', 0);
    // formData.append('wecomType', this.wecomType);
    // const isRefresh = userInfo.isRefreshProvider === '是' ? 1 : 0;//0=否 1=是
    // formData.append('isRefresh', isRefresh);
    GetDictList(formData).then(response => {
      if (response.StatusCode == 200) {
        that.isNeedProject = response.Data.isNeedProject;
        that.addProjectLink = response.Data.projectAddress;
        // 字典获取选择列表
        // 设计风格
        this.designStyles = response.Data.dict.DesignStyle;
        // 仿石漆电子色卡选项
        this.stoneColors = response.Data.dict.ColorCard;
        // 墙面工艺选项
        this.deepSlotProcesses = response.Data.dict.DeepGrooveTech;
        if(this.deepSlotProcesses && this.deepSlotProcesses.length > 0){
          // 墙面分割线选项
          this.splitWays = this.deepSlotProcesses[0].subitems;
        }
        // 窗套样式选项
        this.windowFrames = response.Data.dict.WindowsColor;
        // 浇筑栏杆选项
        this.railings = response.Data.dict.CastRailing;
        // 琉璃瓦选项
        this.tiles = response.Data.dict.NewGlazedTile;
        // 外墙平涂
        this.color_options = response.Data.dict.outsideColor;
        // 墙裙
        this.skirtTypes = response.Data.dict.outsideSkirtType;
        // 罗马柱选项
        if (this.designStyles && this.designStyles[0] && this.designStyles[0].subitems) {
          this.ColumnTypes = this.designStyles[0].subitems || [];
          this.selectedColumnType = this.designStyles[0].subitems[0].value || '';
        }
        if (this.$route.query.F_id) {
          this.GetEntityData(this.$route.query.F_id);
        } else {
          // 判断如果不是服务商，也不用展示
          if (that.serviceCodeArray.length == 0) {
            that.projectBoxShow = false;
          } else {
            that.projectBoxShow = that.isNeedProject;
          }
          that.save_projectBoxShow_org = that.projectBoxShow;
          this.zgInitData();
        }
      } else {
        that.$toast(response.Info)
        console.log(response.Info);
      }
    }).catch((err) => {
      that.$toast(err)
    })
  }
  // 初始化外墙质感
  private zgInitData() {
    this.DesignStyle = this.designStyles[0].value;
    this.ColorCard = this.stoneColors[0].value;
    this.selectedProcess = this.deepSlotProcesses[0].value;
    this.selectedSplit = this.splitWays[0].value;
    this.selectedWindowFrame = this.windowFrames[0].value;
    this.selectedRailing = this.railings[0].value;
    this.selectedTile = this.tiles[0].value;
    this.selectedSkirtType = this.skirtTypes[0].value;
  }

  //关联列表模糊查询
  private onSearch() {
    this.GetProjectListFn();
  }

  //选择关联项目
  private chooseProject() {
    let that = this;
    that.showChooseProject = true;
    that.GetProjectListFn();
  }

  //确认选择
  private chooseSure() {
    let that = this;
    // if (that.projectList[that.checkedProjectId].AvailableQuantity == 0) {
    //   this.projectActionNumShow = true;
    //   return;
    // } else {
    that.checkedProject = that.projectList[that.checkedProjectId];
    that.projectActionListShow = false;
    // }
  }
}
</script>
<style>
.actionsTit {
  width: fit-content;
  font-size: 11px;
  height: 34px;
  padding: 5px 10px;
}

.van-popover--dark .van-popover__action {
  background-color: #777A7F;
}

.van-popover--dark[data-popper-placement^=bottom] .van-popover__arrow {
  border-bottom-color: #777A7F;
}

.design-container .van-tab__text {
  font-size: 15px;
  font-weight: 500;
  line-height: 2.6rem;
}

.design-container .van-tab--active .van-tab__text {
  font-size: 17px;
}

.design-container .van-tabs__nav {
  background-color: transparent;
}
</style>
<style scoped lang="scss">
.design-container {
  /* margin: 0 auto;
  max-width: 750px; */
  background-color: #f8f9fa;
  min-height: 100vh;
  flex-direction: column;
}

.container {
  // padding: 0 20px;
}

.padded-lr-20 {
  padding: 0 20px;
}

.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn,
.more-btn {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.title {
  font-size: 15px;
  font-weight: bold;
  color: #333;
}

.history-section {
  margin: 20px 0;
}

.history-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background-color: #ffffff;
  border-radius: 18px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border: 1px solid #e9ecef;
  /* margin-bottom: 10px; */
}

.icon-clock {
  font-size: 12px;
  margin-right: 8px;
}

.history-header span {
  font-weight: 500;
  color: #EC8868;
}

.history-header .badge-dot {
  width: 5px;
  height: 5px;
  background-color: #ff4d4f;
  border-radius: 50%;
}

.history-content {
  padding: 20px;
  border-radius: 12px;
  background-color: white;
  text-align: center;
  border: 1px dashed #ddd;
}

.no-history {
  color: #999;
  font-size: 12px;
}

.image-selection {
  text-align: center;
}

.image-placeholder {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  margin-bottom: 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border: 1px dashed #ddd;
  padding: 10px;
  padding-bottom: 50px;
}

.project-placeholder {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border: 1px dashed #ddd;
  padding: 10px;
  padding-bottom: 30px;
}

.project-add-box {
  width: 100%;
  flex-direction: row;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

::v-deep .van-button--normal {
  font-size: 16px;
  border-radius: 10px;
}

.project-action-box {
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  padding: 15px 5px 45px 5px;
  width: 100%;

  img {
    width: 100%;
    height: auto;
  }

  .tip {
    padding: 0 20px;
    font-size: 16px;
    font-weight: 700;
  }

  .tip-content {
    padding: 0 20px;
    margin-top: 30px;
    font-size: 14px;
  }

  .btn {
    height: 44px;
    line-height: 44px;
    text-align: center;
    margin: 20px;
    font-size: 16px;
    color: #FFFFFF;
    background-color: #2484F2;
    border-radius: 10px;
  }

  .btn2 {
    width: 100%;
    font-size: 14px;
    text-align: center;
  }
}

.project-action-list-box {
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  padding: 0px 15px 0px 15px;

  .search-box-bg {
    left: 0px;
    right: 0px;
    padding: 15px;
    box-sizing: border-box;
    background-color: #ffffff;
    position: absolute;
    z-index: 10;

    .search-box {
      flex-direction: row;
      display: flex;
      border: 1px solid #2484F2;
      background-color: #FFFFFF;
      align-items: center;
      box-sizing: border-box;
      padding-right: 5px;

      .btn {
        width: 50px;
        height: 28px;
        font-size: 11px;
        border-radius: 5px;
      }
    }

    ::v-deep .van-search {
      padding: 0;
      border-radius: 15px;
    }
  }

  .list-item {
    flex-direction: column;
    display: flex;
    box-sizing: border-box;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    margin-top: 20px;
    padding: 15px;
    position: relative;

    .img-item {
      position: absolute;
      bottom: 0;
      right: 5px;
    }

    .img-checked {
      width: 30px;
    }

    .title-item {
      flex-direction: row;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;

      .title {
        font-size: 15px;
        font-weight: 700;
      }

      .status {
        font-size: 14px;
        color: #999999;
        min-width: 45px;
        margin-left: 10px;
      }
    }

    .user-item {
      margin-top: 8px;

      .txt {
        font-size: 14px;
        color: #999999;
        margin-left: 10px;
      }
    }
  }

  .btn-box {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    box-sizing: border-box;
    padding: 15px;
    background-color: #ffffff;
    z-index: 10;

    .btn-item {
      position: relative;
      flex-direction: row;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      border-radius: 8px;
      box-sizing: border-box;
      margin-left: 20px;
      background-color: rgba(134, 144, 156, 1);

      .img-left-icon {
        width: 66px;
        height: 53px;
        position: absolute;
        left: -20px;
        bottom: -3px;
      }

      .btn {
        width: 133px;
        height: 38px;
        line-height: 38px;
        opacity: 1;
        border-radius: 8px;
        text-align: center;
        font-size: 14px;
        color: #FFFFFF;
        background: rgba(36, 132, 242, 1);
      }
    }
  }
}

.list-item-checked {
  width: 100%;
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 15px;
  margin-bottom: 20px;
  position: relative;

  .img-item {
    position: absolute;
    bottom: 0;
    right: 5px;
  }

  .img-checked {
    width: 30px;
  }

  .title-item {
    flex-direction: row;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;

    .title {
      font-size: 15px;
      font-weight: 700;
    }

    .status {
      font-size: 14px;
      color: #999999;
      min-width: 45px;
      margin-left: 10px;
    }
  }

  .user-item {
    flex-direction: row;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 8px;

    .txt {
      font-size: 14px;
      color: #999999;
      margin-left: 10px;
    }
  }
}

.selected-image-preview {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.placeholder-text {
  color: #999;
  font-size: 15px;
  text-align: center;
  margin-bottom: 20px;
  margin-top: 10px;
}

.placeholder-text-tit {
  color: #999;
  font-size: 15px;
  text-align: center;
  margin-bottom: 20px;
  margin-top: -10px;
}

.image-buttons {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
  gap: 16px;
  width: 100%;
  justify-content: flex-end;
}

.image-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  /* background-color: #666; */
  background-color: #07c160;
  color: white;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

/* .image-btn:hover {
  background-color: #555;
} */

.design-option {
  margin: 20px 0;
  position: relative;
}

.rightArrows {
  position: absolute;
  right: -10px;
  top: calc(50% - 10px);

  img {
    height: auto;
  }
}

.option-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.option-title-tit {
  display: flex;
  align-items: center;

  span {
    display: inline-block;
    font-size: 11px;
    color: #959fab;
    line-height: 20px;
  }

  i {
    display: block;
    margin: 0 2px 0 5px;
    line-height: 20px;
    font-weight: bold;
  }
}

/* 修改为grid布局，实现2x2排列 */
.option-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.option-item {
  position: relative;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: white;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.option-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.option-item.active {
  border-color: #E96337;
  /* background-color: #fff8e6; */
}



.style-name {
  font-size: 12px;
  color: #666;
}

.design-colors-grid {
  display: flex;
  overflow-x: auto;
  gap: 12px;
  padding: 4px;
  scroll-behavior: smooth;
  cursor: grab;
  user-select: none;
  /* 防止拖拽时选中文本 */
}

.design-colors-grid::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}

.design-colors-grid .option-item {
  padding: 10px 5px;
  // width: 160px;
  // flex: 0 0 auto; /* 防止压缩 */
}

.style-image {
  // width: 141px;
  // height: 100px;
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 4px;
}

.magnifyingGlassBox {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 14px;
    height: auto;
  }
}

/* 仿石漆电子色卡特殊样式 - 横向滚动 */
.stone-colors-grid {
  display: flex;
  overflow-x: auto;
  gap: 12px;
  padding: 4px;
  scroll-behavior: smooth;
  cursor: grab;
  user-select: none;
  /* 防止拖拽时选中文本 */
}

.stone-colors-grid::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}

.stone-colors-grid .option-item {
  width: 50px;
  height: 80px;
  flex: 0 0 auto;
  /* 防止压缩 */
}

.color-sample {
  width: 50px;
  height: 50px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  margin-bottom: 8px;
}

.color-code {
  font-size: 12px;
  color: #666;
}

.process-icon,
.split-icon,
.railing-icon,
.tile-icon {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 15px;
}

.split-icon,
.railing-icon,
.tile-icon {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.frame-icon {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.tile-color {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.process-name,
.split-name,
.frame-name,
.railing-name,
.tile-name {
  font-size: 12px;
  color: #666;
  line-height: 13px;
  padding-top: 2px;
  display: inline-block;
}

.generate-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  /* 按钮和文字说明之间的间距 */
  margin-bottom: 20px;
}

.generate-btn {
  padding: 16px;
  background-color: #E96337;
  border: none;
  border-radius: 12px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  min-width: 90%;
}

/* .generate-btn:hover {
  background-color: #e68a00;
} */

.btn-text {
  font-size: 16px;
  font-weight: bold;
}

.btn-note {
  font-size: 12px;
  color: #999;
  text-align: center;
  line-height: 1.2;
}

.header {
  /*height: 50px;*/
  /*line-height: 50px;*/
  /*text-align: center;*/
  /*background: #fff;*/
  border-bottom: 1px solid #f8f8f8;

  .van-nav-bar__title {
    font-size: 20px;
    color: #333;
  }

  .van-icon {
    font-size: 20px;
    color: #333 !important;
  }
}

.dialog-box {
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  position: relative;

  .dialog-content {
    padding: 20px 20px 10px 20px;
  }

  .dialog-btn {
    height: 44px;
    line-height: 44px;
    text-align: center;
    margin: 20px;
    font-size: 16px;
    color: #FFFFFF;
    background-color: #2484F2;
    border-radius: 10px;
  }
}

::v-deep .van-button__loading+.van-button__text {
  margin-left: 10px;
}

/* 样式调整：隐藏原生 input，按钮样式保持不变 */
.upload-container {
  position: relative;
  display: inline-block;

  .native-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
    z-index: 1;
  }

  .image-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 8px;
    background-color: #2484F2;
    color: white;
    font-size: 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
  }
}

.radio-group-container1 {
  padding: 16px 0;
  position: relative;


  .color-plus {
    width: 100%;
    height: 90px;
    margin: 10px auto;
    position: relative;
    margin: 0px auto 10px;

    .cardImg {
      width: 100%;
      height: 100%;

      img {
        width: 100%;
        height: auto;
      }
    }

    .color-plus-info {
      position: absolute;
      width: calc(100% - 20px);
      height: 100%;
      top: 0;
      left: 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .color-plus-tit {
        font-size: 16px;
        font-weight: 500;
        line-height: 26px;
        width: 100%;
        color: #000;
      }

      p {
        font-size: 11px;
        line-height: 15px;
        color: rgba(56, 56, 56, 1);
      }

      .color-plus-subheading {
        font-size: 11px;
        line-height: 15px;
        width: 100%;
        color: #86909C;
      }
    }
  }

  // 上图下文字
  .custom-radio-group4 {
    display: flex;
    flex-wrap: wrap;
    // column-gap: 2px;
    // row-gap: 16px;
  }

  .custom-radio4 {
    width: calc(25% - 2px);
    margin: 0 1px 16px;
  }

  .custom-radio4:nth-child(4n) {
    margin-right: 0;
  }

  .radio-content-text {
    padding: 12px 0;
    text-align: center;
    border: 1px solid #E5E5E5;
    border-radius: 4px;
    box-sizing: border-box;
    transition: all 0.2s;
    font-size: 12px;
  }

  /* 选中指示器（橙色三角形背景） */
  .check-indicator {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: #F0A43A;
    /* 三角形效果 */
    clip-path: polygon(0 0, 0 100%, 100% 0);

    .van-icon {
      position: relative;
    }
  }

  /* 选项内容容器 */
  .radio-content {
    position: relative;
    width: 100%;
  }

  .custom-radio-text {
    font-size: 12px;
    text-align: center;
    line-height: 14px;
    width: 100%;
    margin: 0 auto;
    position: absolute;
    z-index: 2;
    color: #000;
    bottom: 4px;
    left: 0;
  }

  .radio-content-color {
    font-size: 12px;
    width: 60px;
    height: 60px;
    position: relative;
    border: 1px solid #E5E5E5;
    margin: 0 auto;

    .cardImg {
      width: 100%;
      height: 100%;
    }

    .check-indicator {
      left: 0;
      top: 0;

      .van-icon {
        top: -5px;
        left: 0px;
      }
    }
  }

  .radio-content-text {
    border-radius: 4px;

    .check-indicator {
      border-radius: 2px 0 0 0;
      top: 0;
      left: 0;

      .van-icon {
        top: -5px;
        left: -3px;
      }
    }
  }

  /* 隐藏Vant默认的选中样式 */
  .custom-radio ::v-deep .van-radio__icon {
    display: none;
  }

  .custom-radio ::v-deep .van-radio__label {
    width: 100%;
    margin-left: 0;
    border-radius: inherit;
    flex: 1;
  }

  /* 单个选项样式 */
  .custom-radio {
    flex-shrink: 0;
    align-items: flex-start;
    justify-content: center;
  }

  /* 选中状态的边框样式 */
  ::v-deep .van-radio__icon--checked+.van-radio__label>.radio-content-text {
    border-color: #F0A43A;
  }

  ::v-deep .van-radio__icon--checked+.van-radio__label>.radio-content-color {
    border-color: #F0A43A;
  }

  ::v-deep .van-button--normal {
    font-size: 16px;
    border-radius: 10px;
  }
}
</style>