<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-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-forms-item label="计划日期" name="date">
                        <uni-datetime-picker type="date" return-type="timestamp" v-model="FormData.date" />
                    </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="有安装了ETC设备的，请务必关闭或移除ETC，避免扣费" />
        <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: {},
                FormData: {
                    start_province: '', //默认 460000
                    start_city: '',
                    aim_province: '', //默认 230000
                    aim_city: '',
                    date: Date(+7).now, //计划发运日期
                    car_value: 20, //单位：万。默认含20万运输险
                    car_title: '',
                    carno: '', //车牌/架号
                    isTempCarno: 0,
                    username: '',
                    mobile: '',
                    remark: ''
                },
                lsIndex: 'OrderCreateDraft',
                //悬浮按钮
                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: "安徽"
                    }
                ],
                //车辆省份标识
                carPs: carP.list,
                letters: letter.list,
                //是否临牌
                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: '运达城市不能为空'
                        }]
                    },
                },
            }
        },
        onLoad(o) {
            // console.log(province.listByTitle['海南省']); //显示海南代码
            var user = ctms.user.getInfo();
            this.FormData.phone = user.mobile;
        },
        onReady() {
            // 设置自定义表单校验规则，必须在节点渲染完毕后执行
            this.$refs.customForm.setRules(this.formRules)
        },
        onShow: function() {
            var lsIndex = this.lsIndex;
            var res = uni.getStorageSync(lsIndex);
            if (res) {
                this.FormData = res;
            }
            this.provinces = province.listDatacom;
            this.userinfo = getApp().globalData;
            utils.debug(this.userinfo);
        },
        onHide() {
            this.draft(); //界面隐藏时自动保存草稿
        },
        methods: {
            //表单校验
            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 = this.FormData;
                }
                ctms.order.book(FormData).then(
                    function(res) {
                        if (res) {
                            var oid = res.data.id;
                            uni.showModal({
                                title: '提交成功',
                                content: '是否前往查看详情',
                                success: function(res) {
                                    //清空本次缓存，避免用户重复提交
                                    uni.removeStorageSync(_that.lsIndex);
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '../detail/detail?oid=' + oid
                                        });
                                    } else if (res.cancel) {
                                        //将缓存存入历史草稿模板
                                        uni.setStorageSync(_that.lsIndex + '-0',
                                            FormData);
                                        //重新载入页面
                                        uni.redirectTo({
                                            url: 'create'
                                        });
                                    }
                                }
                            })
                        } else {
                            uni.showToast({
                                title: "操作失败",
                                icon: "error"
                            });
                        }
                    }
                );
                uni.hideLoading();
            },
            //存储与取用草稿
            /*TD：草稿逻辑
            当前页面正在录入的内容，视为默认草稿数据，即时更新、主动保存；
            索引-1~5：追加应用模板草稿或设置当前草稿为对应模板；后期考虑加入固定模板
            */
            draft(e) {
                //e是索引后缀
                var lsIndex = this.lsIndex;
                if (e) {
                    lsIndex = lsIndex + e;
                }
                uni.setStorageSync(lsIndex, this.FormData);
                uni.showToast({
                    title: '草稿已保存'
                })
            },
            useDraft(e) {
                var _that = this;
                //e为缓存索引
                uni.showModal({
                    title: '覆盖提醒',
                    content: '即将应用该草稿中的临时数据',
                    success: function(res) {
                        if (res.confirm) {
                            var lsIndex = _that.lsIndex + e;
                            _that.FormData = uni.getStorageSync(lsIndex);
                        } 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;
                var lsIndex = this.lsIndex;
                if (!e.item.diyfn) {
                    //未设置这个difyfn字段的，是“保存草稿”按钮
                    return this.draft();
                }
                lsIndex = lsIndex + e.item.diyfn;
                var res = uni.getStorageSync(lsIndex);
                // console.log(e.item.diyfn);
                // console.log('error',lsIndex);
                // console.log(res);
                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;
                                return _that.draft(e.item.diyfn);
                            } else if (res.cancel) {
                                uni.showToast({
                                    icon: 'error',
                                    title: '操作已取消'
                                });
                                return false;
                            }
                        }
                    });
                } else {

                }
                //缓存存在
                return this.useDraft(e.item.diyfn);
            }
        }
    }
</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>