 <template>
    <app-layout>
        <view class="app-view">
            <!-- 自动识别功能 -->
 <!--           <view class="automatic dir-left-nowrap cross-center main-between">
                <input type="text" v-model="automatic" placeholder-class="place-automatic"
                       placeholder="复制收货信息（姓名前后请输入空格）" @confirm="getAddress">
                <button @click="getAddress">自动识别</button>
            </view> -->

            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">参训人:</text>
                <input class="address-input" type="text" v-model="form.name" />
            </view>
            <view class="app-line app-border main-betweens cross-center">
                <text class="app-text box-grow-0">性别:</text>
			<!-- 	<app-diy-form
				        :list="form.sex"
				        @input="handleGoodsFormInput"
				        @validate="handleGoodsFormValidate"
				        :sign="`${mchIndex},${goodsIndex},${goodsItem.form.id}`"></app-diy-form> -->
                <!-- <input class="address-input" type="text" v-model="form.sex" placeholder="1: 男, 2: 女, 0: 未知"/> -->
				<radio-group @change="radioChange" class="radio-groups">
					<label class="uni-list-cell uni-list-cell-pd radio-groups" v-for="(item, index) in sex" :key="item.value">
						<view>
							<radio :value="item.value" :checked="index === current" />
						</view>
						<view>{{item.name}}</view>
					</label>
				</radio-group>
            </view>
            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">联系电话:</text>
                <input class="address-input" type="number" v-model="form.mobile" />
            </view>
            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">年龄:</text>
                <input class="address-input" type="number" v-model="form.age" />
            </view>
            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">体重:</text>
                <input class="address-input" type="number" v-model="form.weight" placeholder="kg"/>
            </view>
            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">身高:</text>
                <input class="address-input" type="number" v-model="form.height" placeholder="cm"/>
            </view>
            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">身份证号码:</text>
                <input class="address-input" type="text" v-model="form.idcard" placeholder="请输入18位身份证号"/>
            </view>
<!--            <view class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">所在地区</text>
                <view class="box-grow-1 area-left">
                    <app-area-picker v-if="tt_area_show"
                                     @customevent="areaEvent"
                                     :ids="[form.province_id,form.city_id,form.district_id]"></app-area-picker>
                </view>
            </view> -->

            <!-- #ifndef MP-TOUTIAO -->
  <!--          <view v-if="is_refund_address == 0" class="app-line app-border main-between cross-center">
                <text class="app-text box-grow-0">定位地址</text>
                <view class="h-100 main-right dir-left-nowrap cross-center box-grow-1" @click="getChooseLocation">
                    <view class="box-grow-0 c-address">{{form.location}}</view>
                    <icon class="box-grow-0 icon-arrow-image"></icon>
                </view>
            </view> -->
            <!-- #endif -->

       <!--     <view class="app-line main-between cross-center">
                <text class="app-text box-grow-0">详细地址</text>
                <input class="address-input" type="text" :focus="focus" @blur="focus = false" v-model="form.detail" />
            </view>
            <view class="tip" @click="detailFocus">请输入具体门牌号以便配送</view> -->
        </view>
        <view class="app-button">
            <app-button @click="submit" :theme="theme" arrangement="row" type="important" round width="90%">
                <!-- <text class="app-text">保存地址</text> -->
                <text class="app-text">保存信息</text>
            </app-button>
        </view>
    </app-layout>
</template>

<script>
    import {mapState} from 'vuex';
    import appLayout from "../../components/basic-component/app-layout/app-layout.vue";
    import appAreaPicker from '../../components/page-component/app-area-picker/app-area-picker.vue';
    import addressParse from './address-parse.js';
    import appTextArea from '../../components/basic-component/app-textarea/app-textarea.vue';
    import appDiyForm from '../../components/page-component/app-diy-form/app-diy-form.vue';

    export default {
        name: "address-edit",
        data() {
            return {
				sex:[
					{
						value: '1',
						name: '男'
					},
					{
						value: '2',
						name: '女'
					},
				],
                form: {
                    location: '',
                    latitude: '',
                    longitude: '',
                    id: '',
                    name: '',
                    mobile: '',
                    address: '',
                    province_id: 0,
                    city_id: 0,
                    district_id: 0,
                    detail: '',
                },
                is_refund_address: 0,
                detail_url: '',
                list: [],
                submit_status: false,
                tt_area_show: false,
                automatic: '',
                provinceString: '',
                cityString: '',
                areaString: '',
                focus: false,
            }
        },
        computed: {
            ...mapState({
                theme: state => state.mallConfig.theme,
            }),
        },
        components: {appLayout, appAreaPicker, appTextArea, appDiyForm},

        onLoad: function (options) {
            this.getAutoInfo();
            this.is_refund_address = options.is_refund_address ? options.is_refund_address : 0;

            if (options.is_refund_address > 0) {
                this.detail_url = this.$api.app_admin.refund_address_edit;
                uni.setNavigationBarTitle({
                    title: '编辑退货地址'
                });
            } else {
                this.detail_url = this.$api.user.address_detail;
            }

            if (options.form) {
                this.form = JSON.parse(options.form);
            }

            if (options.id > 0) {
                this.$showLoading({title: `加载中`});
                this.$request({
                    url: this.detail_url,
                    data: options
                }).then(info => {
                    this.$hideLoading();
                    if (info.code === 0) {
                        if (options.is_refund_address > 0) {
                            const detail = info.data.detail;
                            this.getInfo(Object.assign({detail: detail.address_detail}, detail));
                        } else {
                            this.form = info.data.list;
                        }
                    } else {
                        uni.showToast({title: info.msg, icon: 'none'});
                    }
                    this.tt_area_show = true;
                }).catch(() => {
                    this.$hideLoading();
                    this.tt_area_show = true;
                });
            } else {
                this.tt_area_show = true;
            }
        },
        methods: {
			radioChange(e){
				this.form.sex = e.target.value
			},
			handleGoodsFormInput(data, sign) {
			    const signArr = sign.split(',');
			    const mchIndex = parseInt(signArr[0]);
			    const goodsIndex = parseInt(signArr[1]);
			    const formId = parseInt(signArr[2]);
			    const result = [];
			    for (let i in data) {
			        result[i] = {
			            key: data[i].key,
			            label: data[i].name,
			            value: data[i].value,
			            required: data[i].is_required,
			        };
			    }
			    const formData = this.$store.state.orderSubmit.formData;
			    formData.list[mchIndex].goods_list[goodsIndex].form_data = result;
			    this.$store.commit('orderSubmit/mutSetFormData', formData);
			},
			handleGoodsFormValidate(result, sign) {
			    const signArr = sign.split(',');
			    const mchIndex = parseInt(signArr[0]);
			    const goodsIndex = parseInt(signArr[1]);
			    const formData = this.$store.state.orderSubmit.formData;
			    formData.list[mchIndex].goods_list[goodsIndex].goods_form_validate_result = result;
			    this.$store.commit('orderSubmit/mutSetFormData', formData);
			},
            outputData(data) {
                console.log(data);
            },
            async getAutoInfo() {
                const res = await this.$request({
                    url: this.$api.user.auto_address_info,
                    method: 'get'
                });
                if (res.code === 0) {
                    let autoInfo = JSON.parse(res.data);

                    const provinces = autoInfo.reduce((per, cur) => {
                        const {children, ...others} = cur;
                        return per.concat(others);
                    }, []);

                    const cities = autoInfo.reduce((per, cur) => {
                        return per.concat(cur.children.map(({children, ...others}) => ({...others, provinceCode: cur.code})));
                    }, []);

                    const areas = autoInfo.reduce((per, cur) => {
                        const provinceCode = cur.code;
                        return per.concat(cur.children.reduce((p, c) => {
                            const cityCode = c.code;
                            return p.concat(c.children.map(({children, ...others}) => ({...others, cityCode, provinceCode,})));
                        }, []));
                    }, []);

                    this.provinceString = JSON.stringify(provinces);
                    this.cityString = JSON.stringify(cities);
                    this.areaString = JSON.stringify(areas);
                }
            },
            // #ifndef MP-TOUTIAO
            async getChooseLocation() {
                const self = this;
                const [err, res] = await uni.chooseLocation();

                if (res) {
                    self.form.location = res.name;
                    self.form.latitude = res.latitude;
                    self.form.longitude = res.longitude;
                }
                if (err) {
                    const setting = () => {
                        uni.showModal({
                            title: '授权权限',
                            content: '请先授权地理位置权限',
                            success(res) {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success(settingdata) {
                                            if (settingdata.authSetting['scope.userLocation']) {
                                                uni.chooseLocation({
                                                    success: function (res) {
                                                        self.form.location = res.name;
                                                        self.form.latitude = res.latitude;
                                                        self.form.longitude = res.longitude;
                                                    },
                                                });
                                            } else {
                                                uni.showToast({
                                                    title: '授权失败',
                                                    icon: 'none'
                                                });
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    };

                    //#ifdef MP-BAIDU
                    if (err.errCode === 1003) {
                        setting();
                    }
                    //#endif

                    //#ifdef MP-WEIXIN
                    if (err.errMsg === `chooseLocation:fail auth deny`) {
                        setting();
                    }
                    //#endif
                }
            },
            // #endif
            getInfo(detail) {
                this.$request({
                    url: this.$api.user.wechat_district,
                    data: {
                        province_name: detail.address[0],
                        city_name: detail.address[1],
                        county_name: detail.address[2],
                    },
                }).then(info => {
                    if (info.code === 0) {
                        const {province, city, district} = info.data.district;
                        detail.province_id = province.id;
                        detail.city_id = city.id;
                        detail.district_id = district.id;
                        this.form = detail;
                    }
                }).catch(() => {
                    uni.showToast({
                        title: '网络异常',
	                    icon: 'none',
                    });
                })
            },

            areaEvent(data) {
                if (data) {
                    this.form.province_id = data.province.id;
                    this.form.city_id = data.city.id;
                    this.form.district_id = data.district.id;
                    this.list = [data.province.name, data.city.name, data.district.name];
                }
            },

            async submit() {
                try {
                    if (this.submit_status) return;
                    let content;

                    // if (!this.form.detail) {
                    //     content = '详细地址不能为空';
                    // }
                    // if (!this.form.province_id) {
                    //     content = '地区不能为空';
                    // }
					if(!this.form.weight){
						content = '体重不能为空';
					}
					if(!this.form.age){
						content = '年龄不能为空';
					}
                    if (!this.form.name) {
                        content = '参训人不能为空';
                    }     
                    if (!this.form.mobile) {
                        content = '联系方式不能为空';
                    }
					if (!this.form.sex) {
                        content = '性别不能为空';
                    }     
					if (!this.form.idcard) {
                        content = '身份证不能为空';
                    }
					
					let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
					if(!reg.test(this.form.mobile)){
						content = '请检查联系方式';
					}
					let regs = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
					if(!regs.test(this.form.idcard)){
						content = '请检查身份证信息';
					}
					
                    if (content) {
                        uni.showToast({
                            title: content,
                            icon: 'none'
                        });
                        return;
                    }

                    this.submit_status = true;

                    let url = this.$api.user.address_save;
                    let para = this.form;

                    if (this.is_refund_address > 0) {

                        url = this.$api.app_admin.refund_address_edit;
                        // let {id, name, mobile, detail} = this.form;
						let { name, mobile, sex, age, weight, height, idcard} = this.form
                        para = {
                            // form: JSON.stringify({
                            //     id,
                            //     name,
                            //     mobile,
                            //     address_detail: detail,
                            //     address: this.list,
                            //     is_default: 0,
                            //     remark: ''
                            // })
							form:JSON.stringify({
								name, 
								mobile, 
								sex, 
								age,
								weight, 
								height, 
								idcard
							})
                        }
                    }

                    const info = await this.$request({
                        url: url,
                        data: para,
                        method: 'POST',
                    });

                    this.submit_status = false;

                    if (info.code === 0) {
                        uni.showToast({title: info.msg, icon: 'none'});
                        uni.navigateBack({delta: 1});
                    } else {
                        uni.showToast({title: info.msg, icon: 'none'});
                    }
                } catch (e) {
                    this.submit_status = false;
                    throw new Error(e);
                }
            },

            getAddress() {
                let data = addressParse(this.automatic, {} ,this.provinceString, this.cityString, this.areaString);
                if (Object.keys(data).length === 0) return;
                const district = uni.getStorageSync("_DISTRICT");
                let {name, province, city, area, phone, detail} = data;

                for (let i = 0; i < district.length; i++) {
                    if (district[i].name === province) {
                        for (let j = 0; j < district[i].list.length; j++) {
                            if (district[i].list[j].name === city) {
                                for (let k = 0; k < district[i].list[j].list.length; k++) {
                                    if (district[i].list[j].list[k].name === area) {
                                        this.form.province_id = district[i].id;
                                        this.form.city_id = district[i].list[j].id;
                                        this.form.district_id = district[i].list[j].list[k].id;
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        break;
                    }
                }

                this.form.name = name;
                this.form.detail = `${detail}`;
                this.form.mobile = phone;
            },
            detailFocus() {
                console.log(22);
                this.focus = true;
            }
        }
    }
</script>

<style scoped lang="scss">
	.radio-group{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.radio-groups{
		display: flex;
		align-items: center;
		justify-content: space-around;
	}
	.main-betweens{
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}
    // 自动识别功能
    .automatic {
        height: #{100upx};
        margin-bottom: #{20upx};
        padding: #{0 32upx 0 24upx};
        background-color: #ffffff;
        button {
            width: #{150upx};
            height: #{60upx};
            padding: 0;
            line-height: #{58upx};
            border-radius: #{5upx};
            border: #{1upx} solid #ff4544;
            font-size: #{26upx};
            color: #ff4544;
            background-color: transparent;
            margin: 0;
            text-align: center;
        }
        input {
            width: calc(100% - #{182upx});
            font-size: #{28upx};
            color:#353535;
        }
        .place-automatic {
            font-size: #{26upx};
            color: #999999;
        }

    }
    .popup {
        position: fixed;
        background: rgba(0, 0, 0, 0.5);
        padding: #{50rpx};
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 2000;
        .textarea {
            width: 100%;
            background: #fff;
            border: #{1rpx} solid #ccc;
            z-index: 1;
            padding: #{24rpx};
            border-radius: #{5rpx};
        }
        .c {
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 0;
        }
    }
    .h-100 {
        height: 100%;
    }

    .app-button {
        margin: #{40rpx} #{24rpx};
    }

    .address-input {
        width: #{580rpx};
        font-size: #{28rpx};
        color: #353535;
    }

    .area-left {
        padding-left: #{32rpx};
        text-align: right;
        margin-left: auto;
    }

    .app-view {
        background: #f7f7f7;
        .app-line {
            background-color: #ffffff;
            height: #{99rpx};
            line-height: #{99rpx};
            padding: #{0 24upx};
            text.app-text {
                font-size: #{28rpx};
                color: $uni-important-color-black;
                // width: #{124rpx};
                width: #{150rpx};
            }
        }

        .app-border {
            border-bottom: #{1rpx} solid $uni-weak-color-one;
        }

        .c-address {
            padding-right: #{24rpx};
            font-size: #{28rpx};
            color: #353535;
        }

        .icon-arrow-image {
            width: #{12rpx};
            height: #{24rpx};
            background-image: url("../../static/image/icon/arrow-right.png");
            background-size: 100% auto;
            background-repeat: no-repeat;
        }

        .tip {
            padding: #{0 24rpx 24rpx 24rpx};
            background: #ffffff;
            color: #b7b7b7;
        }
    }
</style>