<template>
    <div class="generate-plan-page 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>
            <!-- 已生成方案区域 -->
            <div class="generated-section">
                <div class="generated-header">
                    <div class="generated-title">已生成</div>
                    <div>
                        <div class="scheme-info"><span class="orgin-color">{{ stoneColors }}</span>{{
                            planParams.F_ColorCard
                            }}</div>
                        <span class="gray-color">|</span>
                        <div class="scheme-process"><span class="orgin-color">{{ planParams.F_DeepGrooveTech }}</span>工艺
                        </div>
                    </div>
                    <van-tag color="#FF8D1A" class="ai-tag">AI效果图</van-tag>
                </div>

                <!-- 效果图 -->
                <div class="scheme-image">
                    <img :src="planParams.BaseUrl + planParams.F_ResultSmallFilePath" alt="房屋效果图"
                        @click="imgClick(imageUrl)" />
                </div>
                <!-- 推荐方案区域 -->
                <div class="recommend-scheme">
                    <h3 class="recommend-title">推荐方案</h3>
                    <section class="recommend-scheme-section">
                        <!-- 施工面积 -->
                        <div class="construction-area">
                            <h3>施工面积</h3>
                            <div class="construction-info">
                                <span>主色</span>
                                <div @click="openAreaPopup">
                                    <span class="area-value">{{ mainArea }} </span>
                                    ㎡
                                    <van-icon name="arrow" size="12" />
                                </div>

                            </div>
                        </div>
                        <!-- 工序 -->
                        <div class="custom-table">
                            <div class="table-header">
                                <div class="table-cell text-left" style="flex:0.95;">工序</div>
                                <div class="table-cell text-left" style="flex:1.7;">别墅之星系列</div>
                                <div class="table-cell text-right" style="flex:0.35;">使用量</div>
                            </div>
                            <div class="table-row" v-for="(item, index) in processData" :key="index">
                                <div class="table-cell text-left" style="flex:0.95;"><span class="gray">{{ index + 1 }}
                                    </span>{{
                                        item.F_ProcedureName }}</div>
                                <div class="table-cell text-left" style="flex:1.7;">{{ item.F_ProductName }}</div>
                                <div class="table-cell text-right" style="flex:0.35;">{{ item.usage }}<span
                                        class="gray">{{
                                            item.F_OrderUnit }}</span>
                                </div>
                            </div>
                        </div>
                        <!-- 预计工期 -->
                        <div class="construction-period custom-table">
                            <h5>预计工期<div>
                                    <span class="orgin-color">2人配合</span>
                                    施工一栋<span class="orgin-color">300㎡</span>房子
                                </div>
                            </h5>
                            <div class="table-row" v-for="(item, index) in processData" :key="index">
                                <div class="table-cell text-left" style="flex:2.4;"><span class="gray">{{ index + 1 }}
                                    </span>{{ item.F_ProcedureName }}</div>
                                <div class="table-cell text-right" style="flex:0.6;">{{ item.F_ConstructionPeriod
                                    }}<span class="gray">天</span>
                                </div>
                            </div>
                        </div>
                    </section>
                    <!-- 提示语 -->
                    <div class="notice-bar">
                        <span>该方案能有效还原意向效果</span>，快去看看吧~
                    </div>

                    <!-- 确认按钮 -->
                    <van-button class="confirm-btn" color="#E87838" block @click="confirmScheme">
                        确认方案 去下单
                    </van-button>
                </div>
            </div>
        </div>

        <!-- 面积输入弹窗 -->
        <van-popup v-model="areaPopupShow" round position="bottom" :style="{ height: '150px', width: '100%' }"
            class="area-popup">
            <!-- 弹窗内容容器：Flex垂直布局，高度100% -->
            <div class="popup-content">
                <h3 class="popup-title">面积</h3>
                <div class="popup-c">
                    <p class="popup-desc">请输入主色施工面积</p>
                    <van-field ref="areaField" type="tel" @input="onNativeInput" class="custom-field"
                        v-model="inputArea" placeholder="输入面积㎡" :maxlength="maxLength" @keyup.enter="confirmInput"
                        @blur="confirmInput" />
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Ref } from 'vue-property-decorator';
import { getWecomType, toLBHome, toXiaoChengxu, getWxconfig, getWecomTypeName } from '@/utils/index';
import { Tag, Field, ImagePreview } from 'vant';
import { GetProductInfo, GetDictList, AddTrackEvent, GetOrderAddress } from "@/api/indexAI";
Vue.use(Tag)
@Component({
    components: {}
})
export default class GeneratePlan extends Vue {
    @Ref('areaField') private areaField!: Field;
    // 工序数据（与原表格数据一致）
    private processData = [];
    private maxLength = 10;//面积最长位数
    // 主色面积
    private mainArea = '300';
    // 面积输入弹窗显示状态
    private areaPopupShow = false;
    // 输入的面积
    private inputArea = '';
    private planParams = {};
    // 数字键盘显示状态（核心：控制键盘自动弹出）
    private showKeyboard = false;
    private imageUrl = ''; // 替换为实际图片路径
    private stoneColors = '';
    created() {
    }

    activated() {
        this.initialize();
        this.getPicList();
        let planParams = sessionStorage.getItem("planParams");
        if (planParams) {
            this.planParams = JSON.parse(planParams)
            const high_Definition_img = this.planParams.F_ResultFilePath || this.planParams.F_ResultlargeFilePath || this.planParams.F_ResultSmallFilePath;
            this.imageUrl = this.planParams.BaseUrl + high_Definition_img;
            this.GetProductInfoFn()
        }
    }

    private initialize() {
        this.processData = [];
        this.mainArea = '300';
        this.areaPopupShow = false;
        this.inputArea = '';
        this.planParams = {};
        this.showKeyboard = false;
    }
    // 推荐方案
    private GetProductInfoFn() {
        let that = this;
        const formData = new FormData();
        formData.append('colorCard', that.planParams.F_ColorCard);
        formData.append('deepGrooveTech', that.planParams.F_DeepGrooveTech);
        GetProductInfo(formData).then(response => {
            if (response.StatusCode == 200 && response.Data.length > 0) {
                let resData = that.processResData(response.Data, that.mainArea);
                that.processData = resData;
            } else {
                that.$toast(`${response.Info}`);
            }
        })
    }
    //获取电子色卡
    private getPicList() {
        let that = this;
        const formData = new FormData();
        // formData.append('WXuserid', userInfo.loginName);
        formData.append('baseType', 0);//必填 0外墙 1内墙
        const agentFrom = window.localStorage.getItem('agentFromAI');
        const wecomType = getWecomType(agentFrom);
        formData.append('wecomType', wecomType);
        GetDictList(formData).then(response => {
            if (response.StatusCode == 200) {
                if (response.Data && response.Data.dict) {
                    // 仿石漆电子色卡选项
                    let stoneColors_option = response.Data.dict.ColorCard;
                    const targetItem = stoneColors_option.find(item => item.value === that.planParams.F_ColorCard);
                    that.stoneColors = targetItem ? targetItem.text : '';
                }
            }
        });
    }
    // 处理数据的函数
    private processResData(data, area) {
        return data.map(item => {
            // 计算usage值：inputArea * F_UsagePerSqM / F_PackagingQuantity
            const usageValue = area * item.F_UsagePerSqM / item.F_PackagingQuantity;
            // 向上取整
            const usage = Math.ceil(usageValue);
            return {
                ...item,
                usage: usage // 新增的使用量属性
            };
        });
    }

    // 打开面积输入弹窗
    private openAreaPopup() {
        this.inputArea = this.mainArea;
        this.areaPopupShow = true;
        this.showKeyboard = true; // 显示数字键盘
        this.$nextTick(() => {
            // 输入框自动获取焦点（可选，增强交互）
            (this.areaField as any).focus();
        });
    }


    // 监听原生输入，限制最多10位
    private onNativeInput(value: string) {
        // 过滤非数字字符
        const pureNum = value.replace(/\D/g, '');
        // 长度校验
        if (pureNum.length > this.maxLength) {
            this.inputArea = pureNum.slice(0, this.maxLength);
            this.$toast(`最多只能输入${this.maxLength}位数字`);
        } else {
            this.inputArea = pureNum;
        }
    }

    // 确认输入（弹窗外的确认方案按钮可调用）
    private confirmInput() {
        const areaNum = Number(this.inputArea);
        if (!isNaN(areaNum) && areaNum > 0) {
            this.mainArea = this.inputArea;
            this.areaPopupShow = false;
            this.processData = this.processResData(this.processData, this.mainArea);
        } else {
            this.$toast('请输入主色施工面积');
        }
    }

    // 确认方案
    private confirmScheme() {
        let that = this;
        if (Number(this.mainArea) > 0) {
            const formData = new FormData();
            formData.append('eventname', '确认方案去下单');//事件名称
            formData.append('eventtype', 'click');//事件类型
            formData.append('menupath', '外墙质感/结果页/确认AI设计/确认方案去下单');//完整菜单路径
            const eventdataObj = {
                wecomType: getWecomTypeName(window.localStorage.getItem('agentFromAI')),
                F_ColorCard: that.planParams.F_ColorCard,
                F_DeepGrooveTech: that.planParams.F_DeepGrooveTech,
                F_UserArea: that.mainArea,
                F_ID: that.planParams.F_ID
            };
            formData.append('eventdata', JSON.stringify(eventdataObj));//事件数据
            AddTrackEvent(formData)//埋点
            // 获取确认下单地址
            GetOrderAddress().then((res) => {
                if (res.StatusCode == 200 && res.Data) {
                    window.location.href = res.Data;
                } else {
                    if (res && res.Info) {
                        this.$toast(res.Info)
                    } else {
                        this.$toast("系统未知错误，请反馈给管理员.")
                    }
                }
            })

        } else {
            this.$toast('请输入有效的主色施工面积');
        }
    }
    imgClick(url) {
        ImagePreview([url]);
    }
    returnPage() {
        this.$router.back();
    }
    toHome() {
        toLBHome()
    }
}
</script>
<style scoped lang="scss">
.generate-plan-page {
    background-color: #f5f5f5;
    min-height: 100vh;
    flex-direction: column;
    padding-bottom: 20px;

    .orgin-color {
        color: rgba(255, 141, 26, 1);
    }

    .generated-section {
        padding: 0 14px;

        .generated-header {
            margin-bottom: 4px;

            .generated-title {
                font-size: 22px;
                font-weight: 600;
                margin-right: 10px;
                line-height: 34px;
                padding-top: 5px;
            }



            .gray-color {
                height: 14px;
                color: rgb(166, 166, 166);
                display: inline-block;
                overflow: hidden;
                margin: 0 4px;
            }

            .scheme-info,
            .scheme-process {
                font-size: 12px;
                color: #000;
                display: inline-block;
            }

            .ai-tag {
                border-radius: 4px;
                margin: 5px 0 3px;
                padding: 1.5px 4px;
            }
        }

        .scheme-image {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 15px;

            img {
                // width: 60%;
                width: 100%;
                height: auto;
                border-radius: 8px;
            }
        }

        .recommend-scheme {
            // background-color: #fff;
            border-radius: 8px;
            // padding: 15px 10px;
            border-bottom: 1px solid rgba(229, 230, 235, 1);

            .recommend-title {
                font-size: 22px;
                font-weight: 600;
                margin-right: 10px;
                line-height: 34px;
                padding-top: 5px;
                margin-bottom: 10px;
            }

            .recommend-scheme-section {
                padding: 10px 6px;
                border-radius: 8px;
                background-color: rgba(248, 248, 248, 1);
                // background-color:#fff;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            // 自定义表格样式
            .custom-table {
                padding: 10px 0;
                // background-color: #fff;
                width: 100%;
                border-radius: 4px;
                overflow: hidden;
                // border: 1px solid #ddd;
                border-bottom: 1px solid rgba(229, 230, 235, 1);

                .table-header {
                    display: flex;
                    // background-color: #f8f8f8;
                    font-weight: 600;

                    .table-cell {
                        flex: 1;
                        // padding: 10px;
                        // text-align: center;
                        font-size: 15px;
                        white-space: nowrap;
                        // border-right: 1px solid #eee;

                        &:last-child {
                            border-right: none;
                        }
                    }
                }

                .gray {
                    color: rgba(128, 128, 128, 1);
                }

                .table-row {
                    display: flex;
                    // border-bottom: 1px solid #eee;
                    align-items: stretch;

                    &:last-child {
                        border-bottom: none;
                    }

                    .table-cell {
                        padding: 2px 0;
                        // display: flex;
                        // align-items: center;
                        // justify-content: center;
                        flex: 1;
                        // padding: 10px;
                        // text-align: center;
                        font-size: 12px;
                        color: #000;
                        word-break: break-all; // 文字换行
                        // border-right: 1px solid #eee;

                        &:last-child {
                            border-right: none;
                        }
                    }
                }

                .text-left {
                    text-align: left;
                }

                .text-right {
                    text-align: right;
                }
            }

            .construction-period {
                border-bottom: none !important;

                h5 {
                    font-size: 16px;
                    font-weight: 600;
                    padding-bottom: 10px;

                    div {
                        display: inline-block;
                        font-size: 12px;
                        margin-left: 10px;
                        font-weight: 400;

                        span {
                            font-size: 12px;
                        }
                    }
                }
            }

            .construction-area {
                padding: 0 0 10px;
                border-bottom: 1px solid rgba(229, 230, 235, 1);

                .area-value {
                    color: #e55b2a;
                    font-weight: bold;
                    font-size: 16px;
                }

                h3 {
                    font-size: 16px;
                    font-weight: 600;
                }

                .construction-info {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-top: 10px;
                    font-size: 12px;

                }
            }

            .notice-bar {
                height: 30px;
                margin: 10px 0 0;
                padding-bottom: 22px;
                position: relative;
                bottom: -22px;
                border-radius: 14px 14px 0 0;
                line-height: 30px;
                color: #000000;
                font-size: 12px;
                background: linear-gradient(180deg, #F6F2B5 0%, #F9F3D8 100%);

                span {
                    padding-left: 15px;
                    color: #FF8D1A;
                    font-weight: bold;
                }
            }

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

    // 弹窗样式
    .area-popup {
        padding: 0;
        box-sizing: border-box;

        .popup-content {
            padding: 15px;
            box-sizing: border-box;

            .popup-title {
                font-size: 20px;
                font-weight: bold;
                margin-bottom: 5px;
            }

            .popup-c {
                display: flex;
                flex-direction: column;
                align-items: center;
            }

            .popup-desc {
                color: #000;
                margin-bottom: 5px;
            }

            .custom-field {
                width: 150px;
                margin: 0px auto;
                text-align: center;

                ::v-deep input {
                    caret-color: #e55b2a;
                    outline: none;
                    pointer-events: auto;
                    text-align: center;
                    font-size: 18px;
                    color: #e55b2a;
                    font-weight: bold;
                }
            }
        }
    }
}
</style>