<template>
    <div class="design-container AI-Design-container">
        <div class="header">
            <van-nav-bar :title="wallType == 'outside' ? '外墙一键诊断' : '内墙一键诊断'" 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">
                <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="diagnoseBox">
                <img src="../../assets/AIDesign/diagnoseTit.png" class="diagnoseTitBg">
                <!-- 图片选择 -->
                <div class="image-selection">
                    <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">
                            <p class="placeholder-text">请上传一张待诊断的<span class="red-name-title">{{ wallType == "outside" ? "【外墙】" : "【内墙】" }}</span>房屋照片</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">
                                    <van-icon name="photo" size="20" />
                                    <span>选择图片</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>


                <!-- 文字描述 -->
                <div class="decInfo">
                    <van-icon name="play" color="#2484F2" size="26" class="triangle" />
                    <p>上传照片一键诊断空鼓、脱落、开裂等墙面问题，生成可视化报告，推荐工艺及产品整体解决方案。</p>
                </div>
                <!-- 一键诊断按钮 -->
                <div class="generate-section">
                    <van-button v-show="AIBtnDisabled" type="primary" block color="#2484F2" disabled loading
                        loading-type="spinner" loading-text="一键诊断"></van-button>
                    <!-- <van-button v-show="!AIBtnDisabled" type="primary" block @click="generateDesign"
                        :color="selectedImage ? '#2484F2':'#7F7F7F'" >一键诊断</van-button> -->
                    <van-button v-show="!AIBtnDisabled" type="primary" block @click="generateDesign"
                        color="#2484F2">一键诊断</van-button>
                    <div class="btn-note">*AI建议仅作参考，请结合专业人员现场复核</div>
                </div>
            </div>
        </div>
        <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">知道了</div>
            </div>
        </van-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { diagCreateDesign, diagGetEntity, diagGetReadState, diagUpdateReadState } from "@/api/indexAI";
import { ImagePreview } from 'vant';
import { Dialog } from 'vant';
import { getWecomType, toLBHome } from '@/utils/index';
declare let wx: any;
import axios from "axios";

@Component
export default class extends Vue {
    private serviceCodeArray = [];
    private selectedImage: string | null = null;  // 存储选择的图片
    private readState = true;
    private AIBtnDisabled = false;
    private dialogShow = false;
    private dialogContent = '';
    private wallType = '';
    created() {
        if (window.localStorage.getItem('agentFromAI') === 'stoneLikePaint') {
            this.getServiceCode();
        }
    }
    activated() {
        // 初始化数据
        this.initialize();
        this.GetReadStateFn();
        if (this.$route.query.F_id) {
            this.GetEntityData(this.$route.query.F_id);
        } 
    }
    initialize() {
        this.serviceCodeArray = [];
        this.selectedImage = null;
        this.readState = true;
        this.AIBtnDisabled = false;
        this.dialogShow = false;
        this.dialogContent = '';
        this.wallType = this.$route.query.wallType || 'outside';
        this.Userfile1 = null;
        this.oldf_id = null;
        sessionStorage.removeItem("diagnoseSelectedImage")
    }
    private getServiceCode() {
        let that = this;
        const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
        let serviceCodeArray = [];
        // if (userInfo && userInfo.loginTypeList && userInfo.loginTypeList.length > 0) {
        //   userInfo.loginTypeList.forEach(item => {
        //     if (item.shopType == 'stoneLikePaint') {
        //       item.shopList.forEach(childItem => {
        //         serviceCodeArray.push(childItem.shop_code);
        //       })
        //     }
        //   })
        // }
        if (userInfo && userInfo.ServiceCode) {
            serviceCodeArray = userInfo.ServiceCode.split(',').map(item => item.trim()).filter(item => item !== '');
        }
        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) {
        // 生成图片预览（如果需要，和 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 = '';
    }

    private generateDesign() {
        let that = this;
        if (!this.Userfile1 && !this.oldf_id) {
            this.$toast.fail('请选择图片');
            return;
        }
        const formData = new FormData();
        // 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);
        //             })
        //         }
        //     })
        // }
        // // 用户企微ID
        // formData.append('WXuserid', userInfo.loginName);
        // 企微类型
        const agentFrom = window.localStorage.getItem('agentFromAI');
        // const wecomType = getWecomType(agentFrom);
        // 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);
        // // 立邦员工，返回新增字段(hbs立邦员工);
        // if (agentFrom === 'hbs') {
        //     //销售部及ID---立邦员工取值orgName和orgCode
        //     formData.append('salesDepartment', userInfo.sysUserExt && userInfo.sysUserExt.orgName ? userInfo.sysUserExt.orgName : '');
        //     formData.append('salesDepartmentCode', userInfo.sysUserExt && userInfo.sysUserExt.orgCode ? userInfo.sysUserExt.orgCode : '');
        // } else {
        //     //销售部---原服务商用户、新增经销商用户
        //     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);
        }
        // 0外墙 1内墙
        const Entrytype = this.wallType === 'inside' ? 1 : 0;
        formData.append('Entrytype', Entrytype);
        that.AIBtnDisabled = true;
        // 遍历打印
        // formData.forEach((value, key) => {
        //     console.log(`key: ${key}, value: ${value}`);
        // });
        diagCreateDesign(formData).then(response => {
            if (response.StatusCode == 200) {
                that.AIBtnDisabled = false;
                sessionStorage.setItem("diagnoseSelectedImage", that.selectedImage)
                that.$router.push({
                    path: '/AIDesign/diagnoseResult',
                    query: {
                        F_id: response.Data.F_ID,
                        wallType: that.wallType,
                    }
                });

            } else if (response.StatusCode == 410) {
                that.dialogContent = response.Info;
                that.AIBtnDisabled = false;
                that.dialogShow = true;
            } else {
                that.AIBtnDisabled = false;
                that.$toast(response.Info);
            }
        })
            .catch((err) => {
                that.AIBtnDisabled = false;//ai生成按钮
            })
    }
    imgClick(url) {
        ImagePreview([url]);
    }

    GetReadStateFn() {
        const formData = new FormData();
        // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfoV1")!);
        // formData.append('WXuserid', userInfo.loginName);
        // 0外墙 1内墙
        const Entrytype = this.wallType === 'inside' ? 1 : 0;
        formData.append('Entrytype', Entrytype);
        diagGetReadState(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);
        // 0外墙 1内墙
        const Entrytype = this.wallType === 'inside' ? 1 : 0;
        formData.append('Entrytype', Entrytype);
        diagUpdateReadState(formData).then(response => { });
    }

    GetEntityData(F_id) {
        const formData = new FormData();
        formData.append('F_id', F_id);
        diagGetEntity(formData).then(response => {
            if (response.StatusCode == 200) {
                if (response.Data) {
                    if (response.Data.F_UserFilePath) {
                        this.selectedImage = response.Data.F_UserFilePath;
                    }
                    this.oldf_id = response.Data.F_ID;
                }
            }
        })
    }
    // 添加一个新的辅助方法用于将图片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();
        // 实现查看历史生成逻辑
        this.$router.push({ path: '/AIDesign/diagnoseHistory', query: { wallType: this.wallType } });
    }
    returnPage() {
        this.$router.push({ path: "/AIDesign" });
    }
    toHome() {
        toLBHome()
    }
}
</script>

<style scoped lang="scss">
.design-container {
    /* margin: 0 auto;
  max-width: 750px; */
    background-color: rgb(247, 247, 247);
    min-height: 100vh;
    flex-direction: column;
    // overflow: hidden;
}

.container {
    // padding: 0 16px;
    height: 100%;
}

.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 10px;
    padding: 0 16px;
    height: 46px;
}

.history-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    background-color: #ffffff;
    border-radius: 8px;
    font-size: 14px;
}

.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: 8px;
    background-color: white;
    text-align: center;
    // border: 1px dashed #ddd;
}

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

.diagnoseBox {
    width: 100%;
    flex: 1;
    margin: 0 auto;
    text-align: center;
    // border-radius: 40px 40px 0 0;
    // background: linear-gradient(180deg, rgb(250, 250, 250), rgb(247, 247, 247));
    // border-top: 2px solid #ffffff;

    .image-selection {
        text-align: center;
        padding: 0 16px;
    }

    .image-placeholder {
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 180px;
        margin-bottom: 48px;
        background-color: #ffffff;
        border-radius: 8px;
        padding: 10px;
        padding-bottom: 50px;

        .placeholder {
            margin-top: 30px;
        }
    }

    .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;
        bottom: 10px;
        display: flex;
        // gap: 16px;
        width: 130px;
        justify-content: center;
    }

    .image-btn {
        width: 13rem;
        padding: 8px 16px;
        text-align: center;
        border: none;
        border-radius: 8px;
        background-color: rgba(36, 132, 242, 1);
        color: white;
        font-size: 16px;
        height: 3.2rem;
        line-height: 3.2rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        transition: all 0.2s ease;

        i {
            margin-top: 3px;
        }
    }

    .diagnoseTitBg {
        width: 228px;
        height: auto;
        // padding: 18px 0;
    }

}


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

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

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

.option-item {
    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-image {
    width: 141px;
    height: 100px;
    object-fit: cover;
    border-radius: 4px;
    margin-bottom: 8px;
}

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

/* 仿石漆电子色卡特殊样式 - 横向滚动 */
.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 {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
    font-size: 15px;
}

.split-icon,
.railing-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;
}

.decInfo {
    position: relative;
    padding: 0 20px;
    margin-bottom: 50px;

    .triangle {
        position: absolute;
        top: 0;
        left: 0;
    }

    p {
        padding: 0 10px;
        line-height: 27.5px;
        font-size: 15px;
        text-align: left;
    }


}

.generate-section {
    // position: fixed;
    // bottom: 5vh;
    // left: 5%;
    width: 90%;
    margin: 0 auto 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}


.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;
}

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

/* 样式调整：隐藏原生 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;
        font-size: 16px;
    }
}
</style>