<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 { userProductStorageApi, userProductStorageSupplyApi } from "@/api/store"
import { apiProvince, apiCity, apiArea, apiStreet, apiVillage, apiBrigade } from '@/api/public'
import { userShipApi, userShipUpdateApi, userLabelListApi, userLabelUpdateApi } from "@/api/user"
import authCode from "@/components/authCode.vue";

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 = (e=null) => {
    getUserInfo();
    // mitt.emit('re-load-user-list', e ? true : false);
}

const updateShip = ref(false);
const userShip = ref([]);
const getUserShip = () => {
    userShipApi().then(res => {
        userShip.value = res.data.lists;
    })
}
getUserShip()
const updateUserShip = () => {
    userShipUpdateApi({
        id: formData.value.id,
        user_ship: formData.value.user_ship
    }).then(res => {
        ElMessage.success('修改成功');
        formData.value.user_ship_name = userShip.value.find(item => item.id == formData.value.user_ship)?.title;
        updateShip.value = false;
    })
}
const cancelUserShip = () => {
    updateShip.value = false;
}

const updateLable = ref(false);
const userLable = ref([]);
const getLableList = () => {
    userLabelListApi().then(res => {
        userLable.value = res.data.lists;
    })
}
getLableList()
const updateUserLable = () => {
    userLabelUpdateApi({
        id: formData.value.id,
        label_id: formData.value.label_id
    }).then(res => {
        ElMessage.success('修改成功');
        formData.value.label_name = userLable.value.find(item => item.label_id == formData.value.label_id)?.label_name;
        updateLable.value = false;
    })
}
const cancelLable = () => {
    updateLable.value = false;
}


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);

const activeStore = ref(0);
const activeStoreList = ref(["基本信息", "用户资产"]);

const isOut = ref(false); // 是否为出库状态
const productList = ref([]); // 商品列表
const whereProduct = ref({
    page_no: 1,
    page_size: 10,
    loading: false,
    loadend: false
})
let info = []; // 出库列表
const initProduct = (re = false) => {
    if (re) {
        productList.value = [];
        whereProduct.value.page_no = 1;
        whereProduct.value.loadend = false;
    }
    if (whereProduct.value.loadend || whereProduct.value.loading) return;
    whereProduct.value.loading = true;
    userProductStorageApi({
        uid: formData.value.id,
        page_no: whereProduct.value.page_no,
        page_size: whereProduct.value.page_size
    }).then(res => {
        productList.value = [...productList.value, ...res.data.lists];
        whereProduct.value.loading = false;
        whereProduct.value.page_no++;
        if (res.data.lists.length < whereProduct.value.page_size) {
            whereProduct.value.loadend = true;
        }
    })
}

const outForm = ref({
    mobile: '',
    code: ''
})
const dialogFormVisible = ref(false);
// 预出库
const onOutAll = () => {
    outForm.value.mobile = formData.value.phone;
    outForm.value.code = '';
    info = productList.value.filter(item => item.n_num).map(item => {
        return {
            product_id: item.product_id,
            nums: item.n_num
        }
    })
    if (info.length == 0) return ElMessage.error("请选择商品");
    dialogFormVisible.value = true;
    // onOutPut();
}
// 发送短信验证码
const onSendCode = ()=>{
    console.log('发送短信验证码');
    ElMessage.success("验证码已发送");
}

// 出库
const onOutPut = () => {
    if(outForm.value.code == '') return ElMessage.error("请输入验证码")
    userProductStorageSupplyApi({
        uid: formData.value.id,
        info: info
    }).then(res => {
        isOut.value = false;
        ElMessage.success("出库成功");
        dialogFormVisible.value = false;
        initProduct(true);
    })
}

const getUserInfo = ()=>{
    userDetailApi({
        id: formData.value.id
    }).then(({ data }) => {
        data.phone = data.mobile + '';
        delete data.mobile;
        formData.value = Object.assign(formData.value, data);
    })
}

onMounted(() => {
    mitt.on("set-user-detail", (res) => {
        formData.value = res;
        isOut.value = false;
        userDetailApi({
            id: formData.value.id
        }).then(({ data }) => {
            data.phone = data.mobile + '';
            delete data.mobile;
            formData.value = Object.assign(res, data);
            console.log(formData.value);
        })
        getAddress();
        initProduct(true);
    });
});

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

<template>
    <div class="my-order">
        <div class="header-nav">
            <div v-for="(item, index) in activeStoreList" :key="index" class="nav-item" :class="{
                'nav-item-active': activeStore == index,
                'nav-item-radius1': activeStore == index + 1,
                'nav-item-radius2': activeStore == index - 1,
            }" @click="activeStore = index">
                {{ item }}
            </div>
            <div class="nav-item" :class="{
                'nav-item-radius2': activeStore == activeStoreList.length - 1,
            }" style="flex: 1"></div>
        </div>
        <div class="detail" v-if="formData.id && activeStore == 0">
            <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.return_money?.toFixed(2) }}</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 red">¥{{ formData.get_frozen?.toFixed(2) }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">冻结礼品券:</div>
                        <div class="info-item-info red">¥{{ formData.amount_frozen?.toFixed(2) }}</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.nickname }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-title">用户电话:</div>
                        <div class="info-item-info">{{ formData.phone }}</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.real_name }}</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" size="large" v-if="formData.user_ship != 1">{{
                                    formData.user_ship_name
                                }}</el-tag>
                                <el-tag type="success" size="large" v-else>{{ formData.user_ship_name }}</el-tag>
                                <el-button type="primary" v-if="formData.user_ship != 1" style="margin-left: 1rem;"
                                    @click="updateShip = true">修改</el-button>
                            </template>
                            <template v-else>
                                <el-select v-model="formData.user_ship" placeholder="请选择用户类型" style="width: 10rem;">
                                    <el-option v-for="item in userShip" :key="item.id" :label="item.title"
                                        :value="item.id" :disabled="item.id==1||item.id==2||item.id==3" />
                                </el-select>
                                <el-button type="primary" style="margin-left: 1rem;"
                                    @click="updateUserShip">确认</el-button>
                                <el-button style="margin-left: 1rem;" @click="cancelUserShip">取消</el-button>
                            </template>
                        </div>
                    </div>
                    <div class="info-item" v-if="formData.user_ship == 1"
                        style="width: 100%;flex-shrink: 0;align-items: center;">
                        <div class="info-item-title">用户标签:</div>
                        <div class="info-item-info">
                            <template v-if="updateLable == false">
                                <el-tag type="primary" size="large" v-if="formData.label_name">{{ formData.label_name
                                    }}</el-tag>
                                <el-button type="primary" v-if="formData.label_name" style="margin-left: 1rem;"
                                    @click="updateLable = true">修改</el-button>
                                <el-button type="primary" v-else style="margin-left: 1rem;"
                                    @click="formData.label_id = ''; updateLable = true;">添加</el-button>
                            </template>
                            <template v-else>
                                <el-select v-model="formData.label_id" placeholder="请选择用户类型" style="width: 10rem;">
                                    <el-option v-for="item in userLable" :key="item.label_id" :label="item.label_name"
                                        :value="item.label_id" />
                                </el-select>
                                <el-button type="primary" style="margin-left: 1rem;"
                                    @click="updateUserLable">确认</el-button>
                                <el-button style="margin-left: 1rem;" @click="cancelLable">取消</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 class="detail" v-if="formData.id && activeStore == 1" v-loading="whereProduct.loading">
            <div class="table" v-infinite-scroll="initProduct" :infinite-scroll-distance="300"
                :infinite-scroll-delay="300" style="overflow: auto" :infinite-scroll-immediate="false">
                <el-table :data="productList">
                    <el-table-column label="商品信息">
                        <template #default="{ row }">
                            <div style="display: flex; align-items: center">
                                <el-image style="height: 3rem; width: 3rem;flex-shrink: 0;" :src="row.image"></el-image>
                                <span style="margin-left: 0.5rem">{{ row.store_name }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="单价" :width="isOut?130:200" />
                    <el-table-column prop="nums" label="存量" :width="isOut?100:200" />
                    <el-table-column prop="nums" v-if="isOut" label="出库量" width="250">
                        <template #default="{ row }">
                            <div style="display: flex; align-items: center" v-if="row.nums">
                                <el-input-number v-model="row.n_num" step-strictly :min="0" :max="row.nums" />
                                <el-button type="primary" style="margin-left: 1rem;"
                                    @click="row.n_num = row.nums">全部</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="pay_price" label="总价" width="150" /> -->
                </el-table>
            </div>
            <div class="footer">
                <div v-if="!isOut">
                    <el-button type="warning" size="large" @click="isOut = true"
                        :disabled="productList.length == 0">商品出库</el-button>
                    <!-- <el-button type="primary" size="large" @click="onOutAll">全部出库</el-button> -->
                </div>
                <div v-else>
                    <el-button type="primary" size="large" @click="onOutAll">确认出库</el-button>
                    <el-button size="large" @click="isOut = false">取消</el-button>
                </div>
            </div>
        </div>
        <div v-else>
            <el-empty></el-empty>
        </div>
        <payUser ref="payRef" @paySuccess="paySuccess"></payUser>
        <el-dialog v-model="dialogFormVisible" title="出库验证" width="500">
            <el-form :model="outForm">
                <el-form-item label="手机号:">
                    <el-input v-model="outForm.mobile" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="验证码:">
                    <el-input v-model="outForm.code" autocomplete="off" placeholder="请输入验证码" style="flex: 1;" />
                    <authCode style="margin-left: 1rem;" @sendCode="onSendCode" :key="outForm.mobile"></authCode>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onOutPut">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

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

    .header-nav {
        display: flex;
        background: linear-gradient(to bottom,
                #f5f5f5 50%,
                #fff 50%);

        /* 创建渐变背景 */
        .nav-item {
            height: 4rem;
            width: 8rem;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.2rem;
            background-color: #f5f5f5;
            border-radius: 1rem 1rem 0 0;
        }

        .nav-item-active {
            background-color: #fff;
            position: relative;
            transition: 300ms;
        }

        .nav-item-radius1 {
            border-radius: 0 0 1rem 0;
        }

        .nav-item-radius2 {
            border-radius: 0 0 0 1rem;
        }
    }

    .detail {
        height: calc(100% - 4rem);
        box-sizing: border-box;
        position: relative;

        .table {
            padding: 1rem;
            padding-bottom: 7rem;
            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;
            z-index: 1000;
            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>
