<template>
    <div>
        <nav-bar path="index" title="礼品卡"/>
        <!--对方的礼物信息-->
        <!--<p>{{myPresent.name}}-{{receivedPresent.name}}</p>-->
        <gift-card
                v-if="myPresent.status === 2 || myPresent.status === 3"
                :present-img="receivedPresent.img"
                :present-name="receivedPresent.name"
                :present-desc="receivedPresent.desc"
                :owner="1"
                :placeId="receivedPresent.placeId"
                :gender="receivedPresent.gender"
                :status="-1"
                :wechat="receivedPresent.wechat"
        />
        <!--我写的感谢信-->
        <div class="letter" v-if="RcommentDo.content.length !== 0">
            <p style="font-size: 110%"><strong>我送出的感谢信</strong></p>
            <van-rate
                    icon="like"
                    void-icon="like-o"
                    readonly
                    v-model="RcommentDo.rate"
                    color="red"
            />
            <p>{{RcommentDo.content}}</p>
        </div>
        <!--我的礼物信息-->
        <gift-card
                :present-img="myPresent.img"
                :present-name="myPresent.name"
                :present-desc="myPresent.desc"
                :owner="0"
                :placeId="myPresent.placeId"
                :gender="myPresent.gender"
                :status="myPresent.status"
                :wechat="myPresent.wechat"
        />
        <div class="letter" v-if="commentDo.content.length !== 0">
            <p style="font-size: 110%"><strong>我收到的感谢信</strong></p>
            <van-rate
                    icon="like"
                    void-icon="like-o"
                    readonly
                    v-model="commentDo.rate"
                    color="red"
            />
            <p>{{commentDo.content}}</p>
        </div>
        <div class="letter" v-if="myPresent.status === 4">
            <p><strong>审核未通过，请前往首页重新发布礼物！</strong></p>
            <p v-if="reason.length !== 0">原因：{{reason}}</p>
        </div>
        <div style="height: 100px; width: 100%"></div>
        <img src="http://szugift.oss-cn-shenzhen.aliyuncs.com/present_card_bottom.png"
             style="position: fixed; bottom: 100px; max-width: 100%; z-index: -1"
        />
        <div
                v-if="myPresent.status === 2"
                style="position: fixed; bottom: 0; width: 100%; background-color: #fff6e3"
        >
            <van-button
                    type="primary" size="large"
                    style="background-color: #fd6740; border-color: #fd6740; width: 85%;"
                    @click="toWriteComment"
            >确认交换成功</van-button>
            <p>交换成功可以开始接收对方发来的感谢信哦</p>
        </div>
        <div
                v-if="myPresent.status === 0 || myPresent.status === 1 || myPresent.status === 4"
                style="position: fixed; bottom: 0; width: 100%"
        >
            <van-button
                    type="default" size="large"
                    style="width: 85%;"
                    @click="editPresent"
                    v-if="myPresent.status !== 4"
            >修改礼物</van-button>
            <van-button
                    type="warning" size="large"
                    style="width: 85%; margin: 10px 0 10px"
                    @click="deletePresent"
            >删除礼物</van-button>
        </div>
    </div>
</template>

<script>
    import GiftCard from "../components/giftCard";
    import {Button, Dialog, Toast, Rate} from 'vant'
    import NavBar from "../components/navBar";
    import {BasicFunction} from "../connector/basic-service";

    export default {
        name: "giftDetail",
        components: {
            NavBar,
            GiftCard,
            [Button.name]: Button,
            [Rate.name]: Rate
        },
        data() {
            return {
                myPresent: {},
                reason: '',
                receivedPresent: {},
                giftDo: {},
                identityDo: {},
                commentDo: {
                    content: '',
                    rate: 5
                },
                RgiftDo: {},
                RidentityDo: {},
                RcommentDo: {
                    content: '',
                    rate: 5
                },
                orderId: -1
            }
        },
        methods:{
            editPresent: function() {
                Toast.loading({
                    mask: true,
                    message: '加载中...',
                    duration: 500
                });
                let p = this.myPresent;
                this.$router.push({path: 'presentRegister', query: {presentId: p.id}});
            },
            deletePresent: function() {
                Dialog.confirm({
                    message: '确认删除礼物吗？'
                }).then(() => {
                    // 删除礼物：将isDel设为1
                    Toast.loading({
                        mask: true,
                        message: '加载中...',
                        duration: 1000
                    });
                    let that = this;
                    BasicFunction.get_data("smartGoods/list?goodid=" + this.myPresent.id, function (response) {
                        // console.log("------ Data Rcvd in detail --------");
                        // console.log(response);
                        try {
                            let list = response.model.list;
                            if (response.ret === "10000") {
                                list[0].isDel = 1;
                                // console.log(list);
                                BasicFunction.get_data("smartGoods/updateBatch", function (response) {
                                    // console.log(response);
                                    if (response.ret === '10000') {
                                        Toast.success('删除成功');
                                        that.$router.push('index');
                                    } else {
                                        Toast.fail('删除失败，请检查网络');
                                    }
                                }, list)
                            } else Toast.fail('获取资源失败');
                        } catch (e) {
                            console.warn(e);
                            Toast.fail('获取资源失败');
                        }
                    }, {});
                }).catch(() => {
                    // on cancel
                });
            },
            toWriteComment: function () {
                let myId = this.myPresent.id;
                let goodid = this.receivedPresent.id;
                let orderId = this.orderId;
                this.$router.push({
                    path: 'assess',
                    query: {myId: myId, goodId: goodid, orderId: orderId}
                });
            },
            loadGift(){
                let presentId = this.$route.query.presentId;
                if(presentId == null || presentId == undefined){
                    presentId = BasicFunction.utils_get_param("presentId");
                }
                if(presentId == undefined || presentId == null){
                    Toast.fail('请重新进入礼物页哦');
                    this.$router.push('index');
                }

                let that = this;
                BasicFunction.get_data('smartGoods/list?goodid=' + presentId, function (res) {
                    if (res.ret === '10000') {
                        if(res.model === undefined || res.model == null || res.model.list == undefined || res.model.list.length <= 0){
                            Toast.fail('礼物查看遇到问题，请稍等一下再试吧');
                            that.$router.push('index');
                            return;
                        }
                        that.giftDo = res.model.list[0];
                        that.onloadGift(that.giftDo);
                    }
                }, {});
            },
            initGifts() {
                if (this.RgiftDo.goodid !== undefined) {
                    let rpresent = {};
                    let ridentity = this.RidentityDo;
                    rpresent.id = this.RgiftDo.goodid;
                    rpresent.name = this.RgiftDo.name;
                    rpresent.desc = this.RgiftDo.description;
                    rpresent.gender = ridentity.userSex;
                    rpresent.placeId = ridentity.dormDistrict;
                    rpresent.wechat = ridentity.userWxAccount;
                    rpresent.img = "http://szugift.oss-cn-shenzhen.aliyuncs.com/mysterious%20gift.jpg";
                    this.receivedPresent = rpresent;
                }
                let present = {};
                let identity = {};
                identity = this.identityDo;
                present.id = this.giftDo.goodid;
                present.name = this.giftDo.name;
                present.desc = this.giftDo.description;
                present.status = this.giftDo.sort;
                present.gender = this.giftDo.goodFirstKind;
                present.placeId = identity.dormDistrict;
                present.wechat = identity.userWxAccount;
                present.img = "http://gift.fogice.com" + this.giftDo.img;
                this.myPresent = present;
            },
            onloadGift(){
                let that = this;
                let status = this.giftDo.sort;
                let id = this.giftDo.goodid;
                // console.log(that.myPresent);
                if (status >= 2) {
                    if (status === 4) that.onloadReview(id);
                    let userid = localStorage.getItem('frontend-userid');
                    BasicFunction.get_data('smartOrder/list?userId=' + userid, function (orderRes) {
                        try {
                            console.log('----- order res -----');
                            console.log(orderRes);
                            if (orderRes.ret === '10000' && orderRes.model.list !== undefined && orderRes.model.list.length !== 0) {
                                let order = orderRes.model.list[0];
                                let receiverId = parseInt(order.note);
                                that.orderId = order.id;
                                BasicFunction.get_data('smartGoods/list?goodid=' + receiverId, function (receiverRes) {
                                    console.log('----- received gift -----');
                                    try {
                                        console.log(receiverRes);
                                        if (receiverRes.ret === '10000') {
                                            if (receiverRes.model === undefined || receiverRes.model == null || receiverRes.model.list == undefined || receiverRes.model.list.length <= 0) {
                                                Toast.fail('礼物查看遇到问题，请稍等一下再试吧');
                                                that.$router.push('index');
                                                return;
                                            }
                                            that.RgiftDo = receiverRes.model.list[0];
                                            that.onloadReceiveGift(id, status);
                                        }
                                    } catch (e) {
                                        console.warn(e);
                                        Toast.fail('获取数据失败，请重试');
                                    }
                                }, {});
                            }
                        } catch (e) {
                            console.warn(e);
                            Toast.fail('数据异常！请重试');
                        }
                    }, {})
                } else this.initGifts();
            },
            onloadReceiveGift(myid, status) {
                let receiverId = this.RgiftDo.ownerId;
                let goodid = this.RgiftDo.goodid;
                let that = this;
                BasicFunction.get_data('smartIdentity/list?userId=' + receiverId, function (recvRes) {
                    try {
                        console.log("----- receiver's identity");
                        console.log(recvRes);
                        if (recvRes.ret === '10000' && recvRes.model !== undefined && recvRes.model.list.length !== 0) {
                            that.RidentityDo = recvRes.model.list[0];
                            if (status === 3) that.onloadFeedback(myid, goodid);
                            else that.initGifts();
                        } else {
                            Toast.fail('获取数据失败，请重试');
                        }
                    } catch (e) {
                        console.log(e);
                        Toast.fail('获取数据失败，请重试');
                    }
                }, {});
            },
            onloadFeedback(myid, rgoodId) {
                let that = this;
                BasicFunction.get_data('smartOrderFeedback/list?goodId=' + myid, function (res) {
                    console.log('----- received feedback -----');
                    console.log(res);
                    try {
                        if (res.ret === '10000') {
                            let comment = {
                                content: '暂未收到'
                            };
                            if (res.model.list !== undefined && res.model.list.length !== 0) {
                                comment = res.model.list[0];
                                that.commentDo.rate = comment.ratingMajor;
                            }
                            that.commentDo.content = comment.content;
                            // 对方的评价
                            BasicFunction.get_data('smartOrderFeedback/list?goodId=' + rgoodId, function (recvRes) {
                                console.log('----- sent feedback -----');
                                console.log(res);
                                try {
                                    if (recvRes.ret === '10000') {
                                        let comment = {
                                            content: '感谢信未发送或发送失败'
                                        };
                                        if (recvRes.model.list !== undefined && recvRes.model.list.length !== 0) {
                                            comment = recvRes.model.list[0];
                                            that.RcommentDo.rate = comment.ratingMajor;
                                        }
                                        that.RcommentDo.content = comment.content;
                                        that.initGifts();
                                    } else {
                                        Toast.fail('获取信息失败');
                                        that.initGifts();
                                    }
                                } catch (e) {
                                    console.warn(e);
                                    Toast.fail('获取信息失败');
                                    that.initGifts();
                                }
                            }, {});
                        } else {
                            Toast.fail('获取信息失败');
                            that.initGifts();
                        }
                    } catch (e) {
                        console.warn(e);
                        Toast.fail('获取信息失败');
                        that.initGifts();
                    }
                }, {});
            },
            onloadReview(goodid) {
                let that = this;
                BasicFunction.get_data('smartGoodReview/list?goodId=' + goodid, function (res) {
                    if (res.ret === '10000' && res.model.list !== undefined) {
                        if (res.model.list.length !== 0) {
                            let i = sortReason(res.model.list);
                            that.reason = res.model.list[i].displayNote;
                        }
                    } else Toast.fail('获取信息失败');
                }, {});
            }
        },
        created: function () {
            if (!localStorage.getItem('frontend-userid')) {
                this.$router.push('login');
                return;
            }
            // let presentId = this.$route.query.presentId;
            // console.log(this.$route.query.present);
            let userid = localStorage.getItem('frontend-userid');
            let that = this;
            BasicFunction.get_data('smartIdentity/list?userId=' + userid, function (res) {
                // console.log(res);
                try {
                    if (res.ret === '10000' && !(res.model === undefined || res.model == null || res.model.list == undefined || res.model.list.length <= 0)){
                        that.identityDo = res.model.list[0];
                        that.loadGift();
                    } else Toast.fail('获取信息失败');
                } catch (e) {
                    console.warn(e);
                    Toast.fail('获取信息失败');
                }
            }, {});
        }
    }

    // 找最后建立的那条审核单
    function sortReason(list) {
        // console.log('-----review list-----');
        // console.log(list);
        let last = 0;
        let lastTime = new Date((list[0].reviewTime).replace(/-/g, "/"));
        for (let i = 1; i < list.length; i++) {
            let time = new Date((list[i].reviewTime).replace(/-/g, "/"));
            if (lastTime < time) {
                lastTime = time;
                last = i;
            }
        }
        return last;
    }
</script>

<style scoped>
    .letter {
        background-color: white;
        margin: 20px 20px;
        border: solid 1px #e4e4e4;
        padding: 0 15px;
        text-align: left;
    }
</style>