<template>
    <div class="conatiner">
        <div class="address" v-if="this.typeFlag[productInfo.typeFlag] == '实体商品'">
            <div class="page-title">
                <span>收货人信息</span>
                <el-button type="text" class="btn-right" icon="el-icon-plus" @click="openAddressEdit(-1)">新增收货地址</el-button>
            </div>
            <div class="addressDetail">
                <div class="nothing" v-if="userAddress.length==0">
                    暂无数据
                </div>
                <template v-else>
                    <div class="address-item" v-if="isMore||userAddressID==item.id" @click="item.isChoose=!item.isChoose" :class="{isActive:item.isChoose}" v-for="(item,index) in userAddress">
                        <el-button size="medium" @click.stop='' class="realName" v-if="item.id==userAddressID">{{item.realName}}
                            <div class="choose">
                                <i class="el-icon-check"></i>
                            </div>
                        </el-button>
                        <el-button size="medium" @click.stop='userAddressID=item.id' class="realName" v-else>{{item.realName}}</el-button>
                        <span style="margin-left:27px;">{{item.realName}}</span>
                        <span style="margin-left:27px;">{{item.address.join(' ')}}</span>
                        <span>{{item.addressDetail}}</span>
                        <span>{{getPhone(item.telephone)}}</span>
                        <el-button class="defalt" type="info" size="mini" v-if="item.defaultFlag">默认地址</el-button>

                        <div style='float:right;margin:5px 23px 0 0;' v-if="item.isChoose">
                            <el-button type="text" size="mini" @click.stop="setDefaultNow(item.id)">设为默认地址</el-button>
                            <el-button type="text" size="mini" @click.stop="openAddressEdit(index)">编辑</el-button>
                            <el-button type="text" size="mini" @click.stop="del(item.id)">删除</el-button>
                        </div>
                    </div>
                    <template v-if="userAddress.length>1">
                        <el-button type="text" class="more" v-if="!isMore" @click="isMore=true">更多地址
                            <i class="el-icon-arrow-down  el-icon--right"></i>
                        </el-button>

                        <el-button type="text" class="more" v-else @click="isMore=false">收起地址
                            <i class="el-icon-arrow-up  el-icon--right"></i>
                        </el-button>
                    </template>
                </template>
            </div>
        </div>
        <div class="orderDetail">
            <div class="page-title">确认订单信息</div>
            <div class="order" v-if="productInfo.storeInfo">
                <div class="order-top">
                    <span style="width:293px">商品名称</span>
                    <span style="width:198px">单价</span>
                    <span style="width:198px">数量</span>
                    <span style="width:198px">优惠</span>
                    <span style="width:198px">小计</span>
                    <!-- <span style="width:165px">补充</span> -->
                </div>
                <div class="order-shop">
                    <span>
                        店铺：{{productInfo.storeInfo.storeName}}
                    </span>

                    <img src="../assetsPre/kefu.png" alt="">
                </div>

                <div class="order-Detail">
                    <div style="width:293px">
                        <div class="icon" :style="{backgroundImage:'url('+productInfo.image+')'}"></div>
                        <div class="content">
                            <div class="title"> {{productInfo.title}}</div>
                            <div class="taocan">{{menu}}</div>
                        </div>
                    </div>
                    <div style="width:198px;font-size:12px;color:rgba(253,149,1,1);">{{price}}</div>
                    <div style="width:198px">
                        <el-input-number class="buyNum" size="mini" v-model="num" :min="1"></el-input-number>
                    </div>
                    <div style="width:198px;font-size:14px;color:#333">{{gift}}</div>
                    <div style="width:198px;font-size:20px;color:#FC2703;">{{totalPrice}}</div>
                    <!-- <div style="width:165px">补充</div> -->
                </div>

                <div class="remark">
                    <div class="title">
                        <span>备注要求</span>
                        <span>单张图片要求上传后单独备注，其他要求如交付时间等可在此标记</span>
                    </div>
                    <div class="content">
                        <el-input type="textarea" resize='none' :autosize="{ minRows: 2}" placeholder="请输入内容" v-model="remark">
                        </el-input>

                    </div>
                </div>
            </div>

            <div class="bottom">
                <div class="price">
                    <span>实付款：</span>
                    <span>¥</span>
                    <span>{{totalPrice}}</span>
                </div>

                <div style="overflow:hidden">
                    <div class="address-order" v-if="userAddressID">
                        寄送至：{{useAddress.address.join(' ')}} {{useAddress.addressDetail}} 收货人: {{useAddress.realName}} {{getPhone(useAddress.telephone)}}
                    </div>

                </div>

                <el-button class='submit' type="primary" @click="onSave">提交订单</el-button>
            </div>
        </div>

        <el-dialog width="576px" title="新增收货人地址" :visible.sync="dialogVisible">
            <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="所在区域" required>
                    <el-cascader :options="cityData" :props='{value:"name",label:"name"}' v-model="ruleForm.address">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" required>
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="ruleForm.addressDetail">
                    </el-input>
                </el-form-item>
                <el-form-item label="邮政编码">
                    <el-input v-model="ruleForm.postcode"></el-input>
                </el-form-item>
                <el-form-item label="收货人姓名" required>
                    <el-input v-model="ruleForm.realName"></el-input>
                </el-form-item>
                <el-form-item label="收货人电话" required>
                    <el-input v-model="ruleForm.telephone"></el-input>
                </el-form-item>
                <el-form-item label="设为默认">
                    <el-switch v-model="ruleForm.defaultFlag"></el-switch>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()">保存</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
import miniHead from '../components/MiniHead'
import menuFoot from '../pagesPre/MenuFoot'
import { mapState } from 'vuex'
import cityData from '../city'
export default {
    name: 'submit',
    data() {
        return {
            cityData,
            tableData3: [],
            productInfo: {},
            num: 1,
            remark: '',
            userAddress: [],
            dialogVisible: false,
            ruleForm: {
                address: [],
                addressDetail: '',
                postcode: '',
                realName: '',
                telephone: "",
                defaultFlag: true
            },
            isMore: false,
            userAddressID: 0
        }
    },
    mounted() {
        this.$http.get({
            url: '/productInfo/getOne',
            data: {
                id: this.$route.query.productId
            }
        }).then(res => {
            if (res.success) {
                this.productInfo = res.data

                if (this.typeFlag[res.data.typeFlag] == '实体商品') {
                    this.getUserAddress()
                }
            }
        }).catch(e => {
            console.log(e)
        })
        this.num = this.$route.query.num



    },
    computed: {
        ...mapState(['userInfo', 'typeFlag']),
        price() {
            var money = this.productInfo.price;
            if (this.productInfo.productPriceList.length > 0) {
                this.productInfo.productPriceList.forEach(item => {
                    if (item.maxCounts && item.minCounts && this.num <= item.maxCounts && this.num >= item.minCounts) {
                        money = item.price
                    } else if (!item.maxCounts && this.num >= item.minCounts) {
                        money = item.price
                    } else if (!item.minCounts && this.num <= item.maxCounts) {
                        money = item.price
                    }
                })
            }
            else {
                money = this.productInfo.price
            }

            return money
        },
        totalPrice() {
            var money = this.price * this.num;

            return money
        },
        gift() {
            var str = ''
            if (this.productInfo.productPriceList) {
                this.productInfo.productPriceList.forEach(item => {
                    if (item.maxCounts && item.minCounts && this.num <= item.maxCounts && this.num >= item.minCounts) {
                        str = item.minCounts + '到' + item.maxCounts + '张优惠'
                    } else if (!item.maxCounts && this.num >= item.minCounts) {
                        str = item.minCounts + '张以上优惠'
                    } else if (!item.minCounts && this.num <= item.maxCounts) {
                        str = item.maxCounts + '张以下优惠'
                    }
                })
            }
            return str
        },
        menu() {
            var str = ''
            if (this.productInfo.productPriceList) {
                this.productInfo.productPriceList.forEach(item => {
                    if (item.maxCounts && item.minCounts && this.num <= item.maxCounts && this.num >= item.minCounts) {
                        str = item.name
                    } else if (!item.maxCounts && this.num >= item.minCounts) {
                        str = item.name
                    } else if (!item.minCounts && this.num <= item.maxCounts) {
                        str = item.name
                    }
                })
            }
            return str
        },
        useAddress() {
            var jsonp = {
                address: [''],
                addressDetail: '',
                postcode: '',
                realName: '',
                telephone: "",
                defaultFlag: true
            }
            if (this.userAddressID) {
                this.userAddress.forEach(item => {
                    if (item.id == this.userAddressID) {
                        jsonp = item
                    }
                })
            }

            return jsonp
        },
        specification() {
            var id = ''
            if (this.productInfo.productPriceList) {
                this.productInfo.productPriceList.forEach(item => {
                    if (item.maxCounts && item.minCounts && this.num <= item.maxCounts && this.num >= item.minCounts) {
                        id = item.id
                    } else if (!item.maxCounts && this.num >= item.minCounts) {
                        id = item.id
                    } else if (!item.minCounts && this.num <= item.maxCounts) {
                        id = item.id
                    }
                })
            }
            return id
        }
    },
    methods: {
        cleanChoose() {
            this.userAddress.forEach(item => {
                item.isChoose = false
            })
        },
        onSave() {
            if (this.typeFlag[this.productInfo.typeFlag] == '实体商品' && !this.userAddressID) {
                this.$message({
                    message: '请选择收货地址',
                    type: 'warning'
                });

                return
            }

            var inventory = this.productInfo.inventory || 0

            if (this.num > inventory) {
                this.$message({
                    message: '库存不足不能购买',
                    type: 'warning'
                });
                return
            }

            this.$confirm('确定要提交订单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.submit()
            }).catch(() => {

            });
        },
        submit() {


            var data = {
                productId: this.$route.query.productId,
                storeId: this.$route.query.storeId,
                userId: this.userInfo.id,
                quantity: this.num,
                productType: this.productInfo.typeFlag,
                unitPrice: this.price,
                productName: this.productInfo.title,
                specification: this.menu,
                remark: this.remark
            }
            if (this.userAddressID) {
                data.userAddressID = this.userAddressID
            }
            this.$http.post({
                url: '/userOrder/save',
                data: data
            }).then(res => {
                if (res.success) {

                    this.$confirm('<img src="' + require('../assetsPre/success.png') + '" style="width:48px;height:47px;vertical-align: middle;"><span style="font-size:24px;font-family:MicrosoftYaHei;color:rgba(51,51,51,1);margin-left:12px;line-height:17px;vertical-align: middle;">提交订单成功</span>', '', {
                        confirmButtonText: '去支付',
                        cancelButtonText: '返回订单管理',
                        dangerouslyUseHTMLString: true,
                        center: true,
                        cancelButtonClass: 'btn-cancel',
                        confirmButtonClass: 'btn-confirm',
                        closeOnClickModal: false,
                    }).then(() => {
                        this.$router.replace({
                            name: 'payOrder',
                            query: {
                                orderId: res.data
                            }
                        })

                    }).catch(() => {
                        this.$router.replace({
                            name: 'userOrder',
                            query: {
                                orderId: res.data
                            }
                        })

                    });
                }
            }).catch(e => {
                console.log(e)
            })
        },
        getUserAddress() {
            this.$http.get({
                url: '/userAddress/all',
                data: {
                    userId: this.userInfo.id
                }
            }).then(res => {
                if (res.success) {
                    res.data.forEach(item => {
                        item.defaultFlag = item.defaultFlag == 'Y'
                        item.address = item.address.split(',')
                        item.isChoose = false
                    })
                    this.userAddress = res.data
                    if (res.data.length > 0) {
                        this.userAddressID = res.data[0].id
                    }
                }
            }).catch(e => {
                console.log(e)
            })
        },
        submitForm() {
            // ruleForm: {
            //         city: [],
            //         address: '',
            //         code: '',
            //         name: '',
            //         phone: "",
            //         delivery: true
            //     }
            if (this.ruleForm.address.length == 0) {
                this.$message({
                    message: '请选择所在区域',
                    type: 'warning'
                });

                return
            }


            if (!this.ruleForm.addressDetail) {
                this.$message({
                    message: '请填写详细地址',
                    type: 'warning'
                });

                return
            }

            if (!this.ruleForm.realName) {
                this.$message({
                    message: '请填写收货人姓名',
                    type: 'warning'
                });

                return
            }
            if (!this.checkPhone(this.ruleForm.telephone)) {
                this.$message({
                    message: '请输入正确电话格式',
                    type: 'warning'
                });

                return
            }

            var data = JSON.parse(JSON.stringify(this.ruleForm))

            if (!data.userId) {
                data.userId = this.userInfo.id
            }

            data.address = data.address.join(',')
            data.defaultFlag = data.defaultFlag ? 'Y' : 'N'


            this.$http.post({
                url: data.id ? '/userAddress/update' : '/userAddress/save',
                data: data
            }).then(res => {
                if (res.success) {
                    var id = ''
                    if (data.id) {
                        id = data.id
                    }
                    else {
                        id = res.data
                    }

                    console.log(id)

                    if (data.defaultFlag == 'Y') {
                        this.setDefault(id).then(() => {
                            this.$message({
                                message: '收货地址保存成功',
                                type: 'success'
                            });
                            this.dialogVisible = false

                            this.getUserAddress()
                            this.cleanChoose()
                        })
                    }
                    else {
                        this.$message({
                            message: '收货地址保存成功',
                            type: 'success'
                        });
                        this.dialogVisible = false

                        this.getUserAddress()
                        this.cleanChoose()
                    }


                }
            })



        },
        setDefaultNow(id) {
            this.setDefault(id).then(() => {
                this.$message({
                    message: '设置默认地址成功',
                    type: 'success'
                });
                this.getUserAddress()
            })
        },
        setDefault(id) {

            console.log(id)

            return new Promise((resolve, reject) => {
                this.$http.post({
                    url: '/userAddress/setDefault',
                    data: {
                        userId: this.userInfo.id,
                        addressId: id
                    }
                }).then(res => {
                    if (res.success) {

                        resolve()

                    }
                })
            })

        },
        del(id) {
            this.$http.post({
                url: '/userAddress/del',
                data: {
                    id: id
                }
            }).then(res => {
                if (res.success) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getUserAddress()


                }
            })
        },
        openAddressEdit(index) {
            if (index == -1) {
                this.ruleForm = {
                    address: [],
                    addressDetail: '',
                    postcode: '',
                    realName: '',
                    telephone: "",
                    defaultFlag: true
                }
            }
            else {
                this.ruleForm = JSON.parse(JSON.stringify(this.userAddress[index]))
            }

            this.dialogVisible = true
        },

    },
    components: {
        miniHead, menuFoot
    }
}
</script>

<style lang="less" scoped>
.conatiner {
    .address {
        background: rgba(255, 255, 255, 1);
        border-radius: 2px;
        border: 1px solid rgba(234, 234, 234, 1);
        margin-bottom: 20px;
        padding: 0 20px;

        .addressDetail {
            transition: height ease-in-out 0.3s;
            .nothing {
                font-size: 12px;
                color: #999;
                line-height: 40px;
                text-align: center;
            }

            .address-item {
                margin-top: 17px;
                .realName {
                    width: 145px;
                    border: 1px solid rgba(234, 234, 234, 1);
                    position: relative;
                    overflow: hidden;
                    .choose {
                        position: absolute;
                        width: 40px;
                        height: 40px;
                        background: rgba(11, 158, 192, 1);
                        color: #fff;
                        right: -20px;
                        top: -20px;
                        transform: rotate(45deg);
                        text-align: center;
                        i {
                            position: absolute;
                            bottom: 0;
                            left: 12px;
                            transform: rotate(-45deg);
                        }
                    }
                }

                span {
                    font-size: 12px;
                    font-family: MicrosoftYaHei;
                    color: rgba(51, 51, 51, 1);
                    line-height: 16px;
                    vertical-align: middle;
                }

                .defalt {
                    color: #333;
                    margin-left: 11px;
                }

                &.isActive {
                    background: rgba(238, 236, 233, 1);
                }
            }

            .more {
                font-size: 12px;
                font-family: MicrosoftYaHei;
                color: rgba(51, 51, 51, 1);
                line-height: 16px;
            }
            min-height: 45px;
        }
    }
    .orderDetail {
        background-color: #fff;
        border-radius: 4px;
        border: 1px solid rgba(234, 234, 234, 1);
        padding-left: 20px;
    }

    .page-title {
        font-size: 14px;
        font-family: MicrosoftYaHei;
        color: rgba(51, 51, 51, 1);
        line-height: 48px;
        // padding: 22px 0 14px;
        border-bottom: 1px solid rgba(216, 216, 216, 1);
        .btn-right {
            float: right;
            margin-top: 5px;
        }
    }

    .order {
        margin: 11px 41px 0 5px;
        border: 1px solid rgba(234, 234, 234, 1);
        .order-top {
            span {
                display: inline-block;
                text-align: center;
                line-height: 40px;
                font-size: 12px;
                font-family: MicrosoftYaHei;
                color: rgba(108, 108, 108, 1);
            }
        }

        .order-shop {
            padding-left: 21px;
            border-top: 1px solid rgba(234, 234, 234, 1);
            line-height: 40px;
            span {
                font-size: 14px;
                font-family: MicrosoftYaHei;
                color: rgba(108, 108, 108, 1);
                line-height: 19px;
                vertical-align: middle;
            }

            img {
                width: 30px;
                height: 26px;
                margin-left: 5px;
                vertical-align: middle;
            }
        }

        .order-Detail {
            padding: 16px 0 14px;
            div {
                display: inline-block;
                text-align: center;
                vertical-align: middle;

                .icon {
                    width: 80px;
                    height: 60px;
                    border-radius: 4px;
                    background-repeat: no-repeat;
                    background-position: center center;
                    background-size: cover;
                }

                .content {
                    margin-left: 15px;
                    text-align: left;
                    width: 150px;
                    vertical-align: top;
                    .title {
                        font-size: 14px;
                        font-family: MicrosoftYaHei;
                        color: rgba(51, 51, 51, 1);
                        line-height: 19px;
                        display: block;
                        text-align: left;
                        width: 150px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    .taocan {
                        font-size: 12px;
                        font-family: MicrosoftYaHei;
                        color: rgba(11, 158, 192, 1);
                        line-height: 16px;
                        display: block;
                        text-align: left;
                        margin-top: 11px;
                    }
                }
            }
        }

        .remark {
            padding: 13px 300px 20px 22px;
            .title {
                span {
                    &:first-child {
                        font-size: 14px;
                        font-family: MicrosoftYaHei;
                        color: rgba(253, 149, 1, 1);
                        line-height: 16px;
                    }

                    &:last-child {
                        font-size: 12px;
                        font-family: MicrosoftYaHei;
                        color: #666;
                        line-height: 16px;
                        margin-left: 10px;
                    }
                }
            }

            .content {
                margin-top: 5px;
            }
        }
    }

    .bottom {
        padding-right: 40px;
        overflow: hidden;
        padding-bottom: 67px;
        .price {
            line-height: 40px;
            text-align: right;
            margin-top: 23px;
            span {
                display: inline-block;
                vertical-align: bottom;

                &:first-child {
                    color: #333;
                    font-size: 14px;
                    line-height: 30px;
                }

                &:nth-child(2) {
                    color: #999;
                    font-size: 30px;
                }

                &:nth-child(3) {
                    color: #fc2703;
                    font-size: 30px;
                }
            }
        }

        .address-order {
            font-size: 12px;
            font-family: MicrosoftYaHei;
            color: rgba(102, 102, 102, 1);
            line-height: 16px;
            height: 31px;
            background: rgba(245, 245, 245, 1);
            padding: 0 10px;
            line-height: 31px;
            // display: inline-block;
            width: auto;
            float: right;
            margin-top: 4px;
        }

        .submit {
            width: 176px;
            height: 40px;
            border-radius: 2px;
            float: right;
            margin-top: 18px;
        }
    }
}
</style>
