<template>
    <div>
        <nav-bar path="index"/>
        <div class='card'>
            <h3><strong>礼物匹配</strong></h3>
            <p>希望对方的性别是</p>
            <van-radio-group v-model="gender">
                <van-radio name="1" checked-color="#fd6740" style="float: left; margin-right: 20px">男</van-radio>
                <van-radio name="2" checked-color="#fd6740">女</van-radio>
            </van-radio-group>
            <p>礼物名称</p>
            <van-field
                    placeholder="给你的礼物起个名字吧"
                    v-model="presentName"
                    :error="pnError"
                    @click="pnError=false"
                    required
                    maxlength="10"
            />
            <p>我的礼物丨走心介绍</p>
            <van-cell-group>
                <van-field
                        type="textarea"
                        placeholder="请在此输入你的礼物介绍和礼物故事"
                        rows="5"
                        autosize
                        v-model="desc"
                        :error="descError"
                        @click="descError=false"
                        required
                        maxlength="300"
                />
            </van-cell-group>

            <p>礼物标签</p>
            <van-radio-group v-model="tag">
                <div
                        v-for="i in [0, 1 , 2, 3]"
                        :key="i"
                        style="height: 40px"
                >
                    <div
                            v-for="j in [0, 1, 2, 3]"
                            :key="j"
                            style="float: left; width: 25%"
                    >
                        <van-radio
                                v-if="i * 4 + j < tags.length"
                                :name="i * 4 + j"
                                checked-color="#fd6740"
                        >{{tags[i * 4 + j]}}
                        </van-radio>
                    </div>
                </div>
            </van-radio-group>

        </div>
        <div class="card" style="margin-bottom: 10px">
            <p>上传礼物照片</p>
            <div style="margin-bottom: 10px">
                <add-photo :photoURL="imgUrl" @onRead="onRead"/>
            </div>
        </div>

        <van-button
                type="primary"
                class="submit_button"
                @click="publishPresent"
                :loading="loading"
        >下一步
        </van-button>
    </div>
</template>

<script>
    import {
        Uploader, Icon,
        CellGroup, Field,
        RadioGroup, Radio,
        CheckboxGroup, Checkbox,
        Picker,
        Button,
        Toast
    } from 'vant';
    import {BasicFunction} from "../connector/basic-service";
    import AddPhoto from "../components/addPhoto";
    import NavBar from "../components/navBar";
    export default {
        name: "PresentRegister",
        components: {
            AddPhoto,
            NavBar,
            [Uploader.name]: Uploader, [Icon.name]: Icon,
            [CellGroup.name]: CellGroup, [Field.name]: Field,
            [RadioGroup.name]: RadioGroup, [Radio.name]: Radio,
            [CheckboxGroup.name]: CheckboxGroup, [Checkbox.name]: Checkbox,
            [Picker.name]: Picker,
            [Button.name]: Button
        },
        data() {
            return {
                gender: '1',
                presentId: '',
                presentName: '',
                pnError: false,
                desc: '',
                descError: false,
                tags: [
                    "情怀","复古", "有趣", "学霸",  "实用",
                    "童年", "吃货", "佛系", "土味", "活力",
                    "洋气", "精致",  "轻奢",  "其它",
                ],
                tag: 0,
                photo: null,
                loading: false
            }
        },
        methods: {
            publishPresent() {
                this.loading = true;
                // 检验输入
                if (this.presentName.length === 0) {
                    this.pnError = true;
                    this.loading = false;
                    return;
                } else if (this.desc.length <= 15) {
                    this.descError = true;
                    Toast.fail('请输入至少15个字的礼物介绍');
                    this.loading = false;
                    return;
                } else if (this.photo === null) {
                    Toast.fail('请上传礼物照片');
                    this.loading = false;
                    return;
                }
                // 上传礼物信息
                let userId = localStorage.getItem("frontend-userid");
                let tag = this.tag;
                let gender = this.gender;

                console.log('------- photo -------');
                console.log(this.photo);

                let that = this;
                // 如果没有改变图片，直接上传
                if (this.imgUrl && this.imgUrl === this.photo) {
                    let imgURL = this.imgUrl;
                    imgURL = '/' + imgURL.split('/')[3] + '/' + imgURL.split('/')[4] + '/' + imgURL.split('/')[5];
                    let present = [{
                        goodid: this.presentId,
                        name: this.presentName,
                        goodsNo: "0", modelId: "0",
                        ownerId: userId.toString(),
                        goodFirstKind: gender,
                        goodSecondKind: tag.toString(),
                        sellPrice: "0.0", marketPrice: "0.0", costPrice: "0.0",
                        upTime: getNowFormatDate(), downTime: getNowFormatDate(), createTime: getNowFormatDate(),
                        storeNums: "0",
                        img: imgURL,
                        isDel: "0", content: "none", keywords: "none",
                        description: that.desc,
                        searchWords: "", weight: "0.0", point: "0", unit: "0", brandId: "0",
                        visit: "0", favorite: "0", sort: "0", listImg: "xx.jpg",
                        smallImg: "xx.jpg", specArray: "{}", exp: "0"
                    }];
                    console.log(present);
                    let url = "updateBatch";
                    if (that.presentId === '') url = "saveBatch";
                    BasicFunction.get_data("smartGoods/" + url, function (response) {
                        console.log("------ Data Rcvd in PresentReg --------");
                        console.log(response);
                        if (response.ret === "10000") {
                            that.$router.push('share');
                        } else {
                            Toast.fail("上传失败，请检查网络");
                            that.loading = false;
                        }
                    }, present);
                }
                else {
                    let formData = new FormData();
                    formData.append('file', this.photo);
                    let imgURL = '';
                    // 先上传图片
                    BasicFunction.get_data("fileserver/upload?sign=abcdefg", function (res) {
                        console.log('----- upload photo result -----');
                        console.log(res);
                        if (res.ret === '10000') {
                            imgURL = res.model;
                            console.log('img:' + imgURL);
                            let present = [{
                                goodid: that.presentId,
                                name: that.presentName,
                                goodsNo: "0",
                                modelId: "0",
                                ownerId: userId.toString(),
                                goodFirstKind: gender,
                                goodSecondKind: tag.toString(),
                                sellPrice: "0.0",
                                marketPrice: "0.0",
                                costPrice: "0.0",
                                upTime: getNowFormatDate(),
                                downTime: getNowFormatDate(),
                                createTime: getNowFormatDate(),
                                storeNums: "0",
                                img: imgURL,
                                isDel: "0",
                                content: "none",
                                keywords: "none",
                                description: that.desc,
                                searchWords: "",
                                weight: "0.0",
                                point: "0",
                                unit: "0",
                                brandId: "0",
                                visit: "0",
                                favorite: "0",
                                sort: "0",
                                listImg: "xx.jpg",
                                smallImg: "xx.jpg",
                                specArray: "{}",
                                exp: "0"
                            }];
                            console.log(present);
                            let url = "updateBatch";
                            if (that.presentId === '') url = "saveBatch";
                            BasicFunction.get_data("smartGoods/" + url, function (response) {
                                console.log("------ Data Rcvd in PresentReg --------");
                                console.log(response);
                                if (response.ret === "10000") {
                                    that.$router.push('share');
                                } else {
                                    Toast.fail("上传失败，请检查网络");
                                    that.loading = false;
                                }
                            }, present);
                        } else {
                            Toast.fail('上传图片失败，请检查网络');
                            that.loading = false;
                        }
                    }, formData);
                }
            },
            onRead: function (e) {
                this.photo = e;
            }
        },
        created: function () {
            if (!localStorage.getItem('frontend-userid')) {
                this.$router.push('login');
                return;
            }
            if(this.$route.query.present) {
                let present = this.$route.query.present;
                console.log('----- Present Info -----');
                console.log(present);
                this.presentId = present.id;
                this.gender = present.gender.toString();
                this.presentName = present.name;
                this.desc = present.desc_long;
                this.tag = present.tags;
                this.imgUrl = present.imgUrl;
                this.photo = present.imgUrl;
            }
        }
    }

    function getNowFormatDate() {
        let date = new Date();
        let seperator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        let hour = date.getHours();
        let minutes = date.getMinutes();
        let seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hour >= 0 && hour <= 9) {
            hour = "0" + hour;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        let currentdate = year + seperator + month + seperator + strDate;
        currentdate = currentdate + ' ' + hour + ':' + minutes + ':' + seconds;
        return currentdate;
    }
</script>

<style scoped>
    p, h3 {
        color: #fd6740;
    }
    h3 {
        padding: 5px;
        border-bottom: solid 1px #e4e4e4;
    }
    .card {
        background-color: white;
        margin: 20px 20px;
        border: solid 1px #e4e4e4;
        padding: 15px;
        text-align: left;
    }
    .submit_button {
        margin-bottom: 10px;
        margin-left: auto;
        margin-right: auto;
        background-color: #fd6740;
        border-color: #fd6740;
        width: 85%;
    }
</style>