<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { useUserStore } from "@/store/user.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import mitt from "@/utils/mitt.js";
import payUser from "@/components/payUser.vue";
import { userAddressDetailApi, userAddressEditApi, userDetailApi } from "@/api/user"
import { apiProvince, apiCity, apiArea, apiStreet, apiVillage, apiBrigade } from '@/api/public'

const userStore = useUserStore();
const router = useRouter();

const formData = ref({
    id: "",
});

const payInfo = ref({
    price: '',
    type: 1,
})

const payRef = ref(null);
const toPay = () => {
    if (payInfo.value.type == 1) payInfo.value.price = '1000';
    else if (payInfo.value.type == 2) payInfo.value.price = '2000';
    else if (payInfo.value.type == 3) payInfo.value.price = '5000';
    // if (Number(payInfo.value.price) < 1000 && formData.value.user_ship != 1) return ElMessage.error('至少购买1000元礼包');
    if (payInfo.value.type == 0) payInfo.value.price = Number(payInfo.value.price).toFixed(2);
    console.log('支付', payInfo.value);
    payRef.value.setForm({
        data: {
            uid: formData.value.id,
            price: payInfo.value.price,
        }
    });
    payRef.value.drawer = true;
}
const paySuccess = () => {
    console.log('支付成功');
    mitt.emit('re-load-user-list');
}

const addressInfo = ref({
    id: '',
    province: '',
    city: '',
    area: '',
    street: '',
    brigade: ''
})
const selectedValues = ref([])
const selectedEd = ref([])
const getAddress = () => {
    userAddressDetailApi({
        uid: formData.value.id
    }).then(res => {
        if (res.data.village) {
            selectedValues.value = [res.data.city, res.data.area, res.data.street, res.data.village, +res.data.brigade];
            selectedEd.value = JSON.parse(JSON.stringify(selectedValues.value));
            addressInfo.value = Object.assign(addressInfo.value, res.data);
        }
    })
}


const options = ref([]);
// 异步加载数据的方法
const loadOptions = async (node, resolve) => {
    const level = node.level;
    let response;
    if (level !== 0 && !node.data.code) return resolve([]);
    // if (level === 0) {
    //     response = await apiProvince();
    //     response = response.data.map((item) => {
    //         return {
    //             code: item.province_code,
    //             name: item.province_name
    //         }
    //     })
    // } else 
    if (level === 0) {
        response = await apiCity({
            province_code: 510000 // 四川省
        });
        response = response.data.map((item) => {
            return {
                code: item.city_code,
                name: item.city_name
            }
        })
    } else if (level === 1) {
        response = await apiArea({
            city_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.area_code,
                name: item.area_name
            }
        })
    }
    else if (level === 2) {
        response = await apiStreet({
            area_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.street_code,
                name: item.street_name,
            }
        })
    }
    else if (level === 3) {
        response = await apiVillage({
            street_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.village_code,
                name: item.village_name,
            }
        })
    }
    else if (level === 4) {
        response = await apiBrigade({
            village_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.id,
                name: item.brigade_name,
                leaf: true
            }
        })
    }

    resolve(response);
};
const props = {
    value: 'code',
    label: 'name',
    children: 'children',
    multiple: false,
    lazy: true,
    lazyLoad: loadOptions
};

const updateAddress = async () => {
    addressInfo.value.city = selectedValues.value[0]
    addressInfo.value.area = selectedValues.value[1]
    addressInfo.value.street = selectedValues.value[2]
    addressInfo.value.village = selectedValues.value[3]
    addressInfo.value.brigade = selectedValues.value[4]
    if (!addressInfo.value.phone) addressInfo.value.phone = formData.value.account;
    if (!addressInfo.value.real_name) addressInfo.value.real_name = formData.value.real_name || formData.value.nickname;
    userAddressEditApi({
        ...addressInfo.value,
        uid: formData.value.id
    }).then(res => {
        ElMessage.success('编辑成功')
        isDisabled.value = true;
    })
}

const cancelUpdate = () => {
    selectedValues.value = JSON.parse(JSON.stringify(selectedEd.value))
    isDisabled.value = true;
}

const isDisabled = ref(true);

onMounted(() => {
    mitt.on("set-user-detail", (res) => {
        formData.value = res;
        userDetailApi({
            id: res.id
        }).then(({ data }) => {
            formData.value = Object.assign(res, data);
            console.log(formData.value);
        })
        getAddress();
    });
});

onUnmounted(() => {
    mitt.off("set-user-detail");
});
</script>

<template>
    <div class="my-order">
        <div class="detail" v-if="formData.id">
            <div class="table">
                <div class="table-title">用户信息</div>
                <div class="table-info">
                    <div class="info-item">
                        <div class="info-item-title">用户余额:</div>
                        <div class="info-item-info red">¥{{ formData.now_money }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">采购款:</div>
                        <div class="info-item-info red">¥{{ formData.purchase_funds }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">待返还金额:</div>
                        <div class="info-item-info red">¥{{ formData.number }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">头像:</div>
                        <div class="info-item-info">
                            <el-avatar style="width: 4rem;height: 4rem;" :src="formData.avatar" />
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">用户昵称:</div>
                        <div class="info-item-info">{{ formData.nickname }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">ID:</div>
                        <div class="info-item-info">{{ formData.id }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">用户电话:</div>
                        <div class="info-item-info">{{ formData.mobile }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">用户账号:</div>
                        <div class="info-item-info">{{ formData.account }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">创建时间:</div>
                        <div class="info-item-info">{{ formData.create_time }}</div>
                    </div>
                    <div class="info-item" style="width: 100%;flex-shrink: 0;align-items: center;">
                        <div class="info-item-title">用户类型:</div>
                        <div class="info-item-info">
                            <template v-if="updateShip == false">
                                <el-tag type="primary" v-if="formData.user_ship == 0">{{ formData.user_ship_name
                                    }}</el-tag>
                                <el-tag type="success" v-else>{{ formData.user_ship_name }}</el-tag>
                                <el-button v-if="isDisabled" type="primary" style="margin-left: 1rem;" size="small"
                                    @click="isDisabled = false">修改</el-button>
                            </template>
                            <template v-else>
                                <el-select v-model="formDataInfo.user_ship" placeholder="请选择会员类型" style="width: 100%;">
                                    <el-option v-for="item in userShip" :key="item.id" :label="item.title"
                                        :value="item.id" :disabled="item.id == 1" />
                                </el-select>
                                <el-button v-if="!isDisabled" type="primary" style="margin-left: 1rem;"
                                    @click="updateAddress">确认</el-button>
                                <el-button v-if="!isDisabled" style="margin-left: 1rem;"
                                    @click="cancelUpdate">取消</el-button>
                            </template>
                        </div>
                    </div>
                    <div class="info-item" style="width: 100%;flex-shrink: 0;align-items: center;">
                        <div class="info-item-title">用户地址:</div>
                        <el-cascader :key="formData.id" style="flex: 1;" v-model="selectedValues" :options="options"
                            :props="props" :load="loadOptions" class="w-full" :disabled="isDisabled" />
                        <el-button v-if="isDisabled" type="primary" style="margin-left: 1rem;"
                            @click="isDisabled = false">修改</el-button>
                        <el-button v-if="!isDisabled" type="primary" style="margin-left: 1rem;"
                            @click="updateAddress">确认</el-button>
                        <el-button v-if="!isDisabled" style="margin-left: 1rem;" @click="cancelUpdate">取消</el-button>
                    </div>
                </div>
                <div class="table-title">供销经营礼包<span class="tips">首次购买1000元以上成为行业会员</span></div>
                <div class="table-info">
                    <div class="pay-btn">
                        <div class="pay-item" :class="{ 'pay-item-active': payInfo.type == 1 }"
                            @click="payInfo.type = 1">
                            <div>¥1000.00</div>
                        </div>
                        <div class="pay-item" :class="{ 'pay-item-active': payInfo.type == 2 }"
                            @click="payInfo.type = 2">
                            <div>¥2000.00</div>
                        </div>
                        <div class="pay-item" :class="{ 'pay-item-active': payInfo.type == 3 }"
                            @click="payInfo.type = 3">
                            <div>¥5000.00</div>
                        </div>
                        <div class="pay-item" :class="{ 'pay-item-active': payInfo.type == 0 }"
                            @click="payInfo.type = 0">
                            <input type="number" class="input" v-model="payInfo.price" placeholder="自定义金额">
                        </div>
                    </div>
                    <el-button type="primary" size="large" class="pay" @click="toPay">立即支付</el-button>
                </div>
            </div>
        </div>
        <div v-else>
            <el-empty></el-empty>
        </div>
        <payUser ref="payRef" @paySuccess="paySuccess"></payUser>
    </div>
</template>

<style scoped lang="scss">
.my-order {
    border-radius: 1.2rem;
    height: 100%;
    flex: 1;
    background-color: #fff;
    position: relative;
    overflow: hidden;

    .detail {
        height: 100%;
        box-sizing: border-box;
        position: relative;

        .table {
            padding: 1rem;
            padding-bottom: 6rem;
            box-sizing: border-box;
            overflow-y: auto;
            height: 100%;

            .table-title {
                font-weight: bold;

                .tips {
                    font-weight: 400;
                    color: #999;
                    font-size: 0.8rem;
                    margin-left: 1rem;
                }
            }

            .table-info {
                display: flex;
                flex-wrap: wrap;
                color: #777;
                font-size: 0.9rem;
                padding-bottom: 1rem;
                margin-bottom: 1rem;
                border-bottom: 1px solid #eee;

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

                .info-item {
                    width: 33%;
                    display: flex;
                    padding-top: 1rem;

                    .red {
                        color: #ff4a00;
                    }

                    .info-item-title {
                        flex-shrink: 0;
                        padding-right: 1rem;
                    }
                }

                .pay-btn {
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    margin-bottom: 1rem;

                    .pay-item {
                        flex: 1;
                        min-width: 10rem;
                        margin: 1rem 0.5rem 0 0.5rem;
                        height: 5rem;
                        background-color: rgba($color: #67c23a, $alpha: 0.1);
                        color: #67c23a;
                        border-radius: 1rem;
                        border: 2px solid #67c23a;
                        cursor: pointer;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        font-size: 1.5rem;
                        font-size: 1.5rem;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                        .input {
                            font-size: 1.5rem;
                            width: 100%;
                            height: 100%;
                            text-align: center;
                            color: #67c23a;
                        }

                        &-active {
                            background-color: #67c23a;
                            color: #fff;

                            .input {
                                color: #fff;
                            }
                        }
                    }

                }

                .pay {
                    width: 100%;
                    border-radius: 3rem;
                    margin: 0.5rem;
                }
            }
        }

        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 6rem;
            box-sizing: border-box;
            background-color: #fff;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            padding: 0 2rem;
            border-top: 1px solid #eee;
        }
    }

    input[type="number"] {
        /* 移除边框 */
        border: none;
        /* 移除内边距 */
        padding: 0;
        /* 移除默认背景颜色 */
        background-color: transparent;
        /* 移除聚焦时的轮廓 */
        outline: none;
        /* 重置文本填充色，防止某些浏览器对自动填充的文本颜色有特殊样式 */
        -webkit-text-fill-color: inherit;
        /* 适用于Webkit内核浏览器 */
        -webkit-appearance: none;
        /* 针对Webkit内核，移除一些特殊样式 */
        /* 防止输入框在聚焦时出现阴影或特殊样式 */
        box-shadow: none;
    }
}
</style>
