<template>
    <view class="content">
        <uni-notice-bar show-icon scrollable text="平台上新季,全路线大力优惠,欢迎来询！！！。" />

        <view class="order-form">
            <!-- 自定义表单校验 -->
            <uni-forms ref="customForm" :rules="formRules" :modelValue="FormData">
                <uni-section title="您要发运的车辆信息" type="line">
                    <uni-forms-item label="品牌车型" name="car_title">
                        <uni-easyinput type="text" v-model="FormData.car_title" placeholder="填写品牌车型" />
                    </uni-forms-item>
                    <uni-forms-item label="车牌号" name="car_no">
                        <uni-easyinput type="text" v-model="FormData.car_no" placeholder="无车牌时可填写车架号后六位" />
                    </uni-forms-item>
                    <text class="uniui-h6 help-block">无车牌时可填写车架号(至少后六位)</text>
                    <uni-forms-item label="是否临牌" name="isTempCarno">
                        <uni-data-checkbox v-model="FormData.isTempCarno" :multiple="false" :localdata="isTempCarno" />
                    </uni-forms-item>
                    <uni-forms-item label="车辆保价(万元)" required name="car_value">
                        <uni-easyinput type="number" v-model="FormData.car_value" placeholder="单位：万元;默认20" />
                    </uni-forms-item>
                    <uni-forms-item label="计划日期" name="plan_date">
                        <uni-datetime-picker type="date" return-type="timestamp" v-model="FormData.plan_date" />
                    </uni-forms-item>
                </uni-section>

                <uni-section title="从哪里出发 - 运到哪儿去" type="line">
                    <uni-forms-item label="出发省份" required name="start_province">
                        <uni-data-picker placeholder="请选择省份" popup-title="请选择出发省份" :localdata="provinces"
                            v-model="FormData.start_province">
                        </uni-data-picker>
                    </uni-forms-item>
                    <uni-forms-item label="始发城市" required name="start_city">
                        <uni-easyinput v-model="FormData.start_city" placeholder="请填写出发城市名称" />
                    </uni-forms-item>

                    <uni-forms-item label="目标省份" required name="aim_province">
                        <uni-data-picker placeholder="请选择省份" popup-title="请选择运达省份" :localdata="provinces"
                            v-model="FormData.aim_province">
                        </uni-data-picker>
                    </uni-forms-item>
                    <uni-forms-item label="目标城市" required name="aim_city">
                        <uni-easyinput v-model="FormData.aim_city" placeholder="请填写目标运达城市名称" />
                    </uni-forms-item>
                </uni-section>

                <uni-section title="联系信息" type="line">
                    <uni-forms-item label="您的姓名" name="from_name">
                        <uni-easyinput v-model="FormData.from_name" placeholder="请输入姓名" />
                    </uni-forms-item>
                    <uni-forms-item label="手机号" required name="from_mobile">
                        <uni-easyinput v-model="FormData.from_mobile" placeholder="请输入发车人电话" />
                    </uni-forms-item>
                </uni-section>

                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput type="textarea" v-model="FormData.remark" placeholder="对运单做一些备注，比如 从哪里提车的；根据实际情况" />
                </uni-forms-item>

            </uni-forms>

            <view class="button-group">
                <button type="primary" size="mini" @click="formCheck('customForm')">确认提交</button>
                <button type="default" size="mini" @click="draft">我再想想</button>
            </view>

            <uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
                :direction="direction" @trigger="trigger" @fabClick="fabClick" />
        </view>

        <uni-notice-bar
            text="温馨提示: 请不要随车放置  贵重小件物品(如 眼镜\无线充电器\数据线\U盘\手表\Zipporr火机等)、精密仪器设备(如 电脑等)、易燃易爆物品，车内不得放置违规违禁物品(如 燃料油\火机\酒精\散装酒等)，否则司机有权拒载、平台有权拒单。" />
        <uni-notice-bar text="炎热天气，不要随车装运水果，一定会闷坏的。" />
        <text class="uniui-h6 help-block"></text>
    </view>

</template>

<script>
    import province from '@/common/province.js';
    import letter from '@/common/letter.js';
    import carP from '@/common/car-p.js';
    import config from "@/config/ctms.config.js";
    import store from '@/store/index.js';
    import utils from "@/utils/common.js";
    import ctms from '@/apis/ctms/index.js';
    export default {
        data() {
            return {
                userinfo: {},
                oid: 0, //源订单
                order: {},
                NotNew: 0, //是否不新增 0 否(更新订单) 1 是(增加订单)
                FormData: {
                    start_province: '', //默认 460000
                    start_city: '',
                    aim_province: '', //默认 230000
                    aim_city: '',
                    date: '', //计划发运日期
                    plan_date: '2017-04-03', //计划发运日期
                    car_value: 20, //单位：万。默认含20万运输险
                    car_title: '',
                    carno: '', //车牌/架号
                    isTempCarno: 0,
                    from_name: '',
                    from_mobile: '',
                    remark: ''
                },

                //悬浮按钮
                horizontal: 'right',
                vertical: 'bottom',
                direction: 'vertical', //horizontal水平展开；vertical垂直展开
                pattern: {
                    color: '#7A7E83',
                    backgroundColor: '#fff',
                    selectedColor: '#007AFF',
                    buttonColor: '#fd8008',
                    iconColor: '#fff'
                },
                content: [{
                        iconPath: '/static/fab/c5.png',
                        selectedIconPath: '/static/fab/c5.png',
                        text: '草稿-5',
                        active: false,
                        diyfn: '5' //自定义添加的一个字段
                    },
                    {
                        iconPath: '/static/fab/c4.png',
                        selectedIconPath: '/static/fab/c4.png',
                        text: '草稿-4',
                        active: false,
                        diyfn: '4' //自定义添加的一个字段
                    },
                    {
                        iconPath: '/static/fab/c3.png',
                        selectedIconPath: '/static/fab/c3.png',
                        text: '草稿-3',
                        active: false,
                        diyfn: '3' //自定义添加的一个字段
                    },

                    {
                        iconPath: '/static/fab/c2.png',
                        selectedIconPath: '/static/fab/c2.png',
                        text: '草稿-2',
                        active: false,
                        diyfn: '2' //自定义添加的一个字段
                    },

                    {
                        iconPath: '/static/fab/c1.png',
                        selectedIconPath: '/static/fab/c1.png',
                        text: '草稿-1',
                        active: false,
                        diyfn: '1' //自定义添加的一个字段
                    },

                    {
                        iconPath: '/static/fab/draft.png',
                        selectedIconPath: '/static/fab/draft-active.png',
                        text: '保存草稿',
                        active: false,
                        diyfn: false
                    },
                ],

                // 单选性别数据源
                sexs: [{
                    text: '男',
                    value: 0
                }, {
                    text: '女',
                    value: 1
                }, {
                    text: '保密',
                    value: 2
                }],

                //默认省份数据
                provinces: [{
                        value: '460000',
                        text: "海南省"
                    },
                    {
                        value: '340000',
                        text: "安徽"
                    }
                ],

                //是否临牌
                isTempCarno: [{
                    text: '否',
                    value: 0
                }, {
                    text: '是',
                    value: 1
                }],

                // 自定义表单校验规则
                formRules: {
                    start_province: {
                        rules: [{
                            required: true,
                            errorMessage: '出发省份不能为空'
                        }]
                    },
                    aim_province: {
                        rules: [{
                            required: true,
                            errorMessage: '运达省份不能为空'
                        }]
                    },
                    start_city: {
                        rules: [{
                            required: true,
                            errorMessage: '出发城市不能为空'
                        }]
                    },
                    aim_city: {
                        rules: [{
                            required: true,
                            errorMessage: '运达城市不能为空'
                        }]
                    },
                    mobile: {
                        rules: [{
                            required: true,
                            errorMessage: '请填写手机号'
                        }]
                    },
                },
            }
        },
        onLoad(o) {
            // console.log(province.listByTitle['海南省']); //显示海南代码
            // console.log(o);
            if (o.oid) {
                this.oid = o.oid;
            }
            if (o.NotNew) {
                this.NotNew = true;
                uni.setNavigationBarTitle({
                    title: '更新咨询'
                })
            }
            var user = ctms.user.getInfo();
            this.userinfo = {
                ...this.userinfo,
                ...user
            }
            this.FormData.from_mobile = user.mobile;
            this.FormData.from_name = user.username;

            this.provinces = province.listDatacom;

            this.setDate();
        },
        onReady() {
            // 设置自定义表单校验规则，必须在节点渲染完毕后执行
            this.$refs.customForm.setRules(this.formRules)
            //取订单详情，如果有的话
            if (this.oid) {
                if (!this.getOderDetail(true)) this.getOderDetail(false);
            }
        },
        onShow: function() {

        },
        onHide() {
            this.draft(null); //界面隐藏时自动保存草稿
        },
        methods: {
            //设置日期
            setDate: function() {
                var _that = this;

                var timestamp = this.order.date ? this.order.date * 1000 : Date.now() + 7 * 24 * 3600 * 1000;
                var time = new Date(timestamp);
                var date = time.getFullYear() + '-' + (time.getMonth() + 1) + '-' + time.getDate();
                _that.FormData.plan_date = date;
            },

            // 获取订单详情
            getOderDetail: function(cache = null) {
                /* cache 是否读取缓存 */
                var _that = this;
                return ctms.orderpre.detail(this.oid, cache).then((res) => {
                    if (res) {
                        if (!_that.NotNew) {
                            delete res['id']; //是新建而不是更新，删除ID
                        }
                        _that.order = res;
                        _that.FormData = {
                            ..._that.FormData,
                            ..._that.order
                        };
                        _that.setDate()
                        return true;
                    } else {
                        return false;
                    }
                });
            },
            //表单校验
            formCheck(ref) {
                this.$refs[ref].validate().then(res => {
                    // utils.debug(res);
                    this.formSubmit();
                }).catch(err => {
                    utils.debug(err);
                    uni.showToast({
                        icon: 'error',
                        title: err['0'].errorMessage
                    })
                })
            },

            formSubmit: function(e) {
                uni.showLoading({
                    title: '网络请求中'
                })
                var FormData,
                    _that = this;
                if (e) {
                    //直接使用表单内建的提交机制
                    // uitls.debug('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
                    FormData = e.detail.value;
                } else {
                    FormData = _that.FormData;
                }

                ctms.orderpre.create(FormData).then(
                    function(res) {
                        if (res) {
                            var oid = res.data.id;
                            ctms.orderpre.delDetail(oid)
                            uni.showModal({
                                title: '提交成功',
                                content: '是否前往查看详情',
                                success: function(res) {
                                    //清空本次缓存，避免用户重复提交
                                    ctms.orderpre.delDraft()
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '../detail/detail?oid=' + oid
                                        });
                                    } else if (res.cancel) {
                                        //重新载入页面
                                        uni.redirectTo({
                                            url: 'create'
                                        });
                                    }
                                }
                            })
                        } else {
                            uni.showToast({
                                title: "操作失败",
                                icon: "error"
                            });
                        }
                    }
                );
                uni.hideLoading();
            },
            //存储与取用草稿
            /*TD：草稿逻辑
            当前页面正在录入的内容，视为默认草稿数据，即时更新、主动保存；
            索引-1~5：追加应用模板草稿或设置当前草稿为对应模板；后期考虑加入固定模板
            */
            draft(e) {
                //e是索引后缀
                ctms.orderpre.draft(this.FormData, e)
                if (e !== null) {
                    uni.showToast({
                        title: '草稿已保存'
                    })
                }
            },
            useDraft(e, data = null) {
                var _that = this;
                //e为缓存索引
                uni.showModal({
                    title: '覆盖提醒',
                    content: '即将应用该草稿中的临时数据',
                    success: function(res) {
                        if (res.confirm) {
                            if (data) {
                                _that.FormData = data;
                            } else {
                                _that.FormData = ctms.orderpre.getDraft(e)
                            }

                        } else if (res.cancel) {

                        }
                    }
                })
            },

            //浮窗按钮相关操作
            fabClick(e) {
                // utils.debug('点击了悬浮按钮')
            },
            trigger(e) {
                //检查是否存在模板，有则提示应用，无则创建保存
                var eindex = e.index;
                this.content[e.index].active = !e.item.active;
                var hasDraft = false;
                if (!e.item.diyfn) {
                    //未设置这个difyfn字段的，是“保存草稿”按钮
                    return this.draft();
                }
                var index = e.item.diyfn;
                var res = ctms.orderpre.getDraft(index)

                var _that = this;
                if (!res) {
                    //该按钮对应的缓存不存在，追加模板
                    return uni.showModal({
                        title: '提示',
                        content: `${e.item.text}对应的草稿不存在，创建吗？`,
                        success: function(res) {
                            if (res.confirm) {
                                _that.content[e.index].active = true;
                                _that.draft(e.item.diyfn);
                            } else if (res.cancel) {
                                uni.showToast({
                                    icon: 'error',
                                    title: '操作已取消'
                                });
                            }
                        }
                    });
                }
                //缓存存在
                return this.useDraft(e.item.diyfn, res);
            }
        }
    }
</script>

<style>
    .container {
        /* #ifndef APP-NVUE */
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        /* #endif */
    }

    .order-form {
        padding: 15px;
        background-color: #fff;
    }

    .segmented-control {
        margin-bottom: 15px;
    }

    .button-group {
        margin-top: 15px;
        display: flex;
        justify-content: space-around;
    }

    .form-item {
        display: flex;
        align-items: center;
    }

    .button {
        display: flex;
        align-items: center;
        height: 35px;
        margin-left: 10px;
    }

    /*级联选择器*/
    .data-pickerview {
        height: 400px;
        border: 1px #e5e5e5 solid;
    }

    .popper__arrow {
        top: -6px;
        left: 50%;
        margin-right: 3px;
        border-top-width: 0;
        border-bottom-color: #EBEEF5;
    }

    .popper__arrow {
        top: -6px;
        left: 50%;
        margin-right: 3px;
        border-top-width: 0;
        border-bottom-color: #EBEEF5;
    }

    /*自定义样式*/
    .help-block {
        display: block;
        width: 100%;
        color: #666666;
        font-size: 0.8rem;
        line-height: 1rem;
        text-align: justify;
        text-align-last: justify;
    }

    .uni-section {
        margin-top: 0;
    }
</style>