<template>
    <view class="container">
        <view class="row">
            <view class="row_label"><span>*</span>收货人</view>
            <view class="row_con">
                <u--input placeholder="请输入姓名" clearable border="none" v-model="name"></u--input>
            </view>
        </view>

        <view class="row">
            <view class="row_label"><span>*</span>手机号</view>
            <view class="row_con">
                <u--input type="number" placeholder="请输入手机号" clearable border="none" v-model="phone" ></u--input>
            </view>
        </view>

        <view class="tabList">
            <view class="tabItem" :class="{ 'active': tab == 0 }" @click="changeTab(0)">地图选址</view>
            <view class="tabItem" :class="{ 'active': tab == 1 }" @click="changeTab(1)">地区选择</view>
        </view>

        <view class="tabItems" v-if="tab == 0">
            <view class="row">
                <view class="row_label">地址</view>
                <view class="row_con">
                    <view class="choseAddress" @click="chooseAddress">
                        <text v-if="showOrientation">请选择地址</text>
                        <text v-if="!showOrientation" style="color: #000;">{{ orientation.region }} {{orientation.district}}</text>
                    </view>

                    <view class="currentAddress" v-if="showOrientation">
                        <view class="currentAddress1">
                            <view class="currentAddress1_left">当前定位：{{orientation.district}}</view>
                            <view class="currentAddress1_right" @click="headerConfirmClick">使用</view>
                        </view>
                        <view class="currentAddress2">{{orientation.region}}</view>
                    </view>
                </view>
            </view>
            <view class="row">
                <view class="row_label">门牌号</view>
                <view class="row_con noneborder">
                    <u--input placeholder="例：6栋201室" clearable border="none" v-model="houseNumber"></u--input>
                    <!-- <view class="tips">记得完善门牌号</view> -->
                </view>
            </view>
        </view>

        <view class="tabItems" v-if="tab == 1">
            <view>
                <picker-view indicator-style="height: 50px;" style="width: 100%; height: 400rpx;" :value="id"
                    @change="bindChange">
                    <picker-view-column>
                        <view v-for="(item, index) in provList" :key="index"
                            style="line-height: 50px; text-align: center;">{{ item.short_name }}</view>
                    </picker-view-column>
                    <picker-view-column>
                        <view v-for="(item, index) in defaultCity" :key="index"
                            style="line-height: 50px; text-align: center;">{{ item.short_name }}</view>
                    </picker-view-column>
                    <picker-view-column>
                        <view v-for="(item, index) in defaultDist" :key="index"
                            style="line-height: 50px; text-align: center;">{{ item.short_name }}</view>
                    </picker-view-column>
                </picker-view>
            </view>

            <view class="row">
                <view class="row_label"><span>*</span>详细地址</view>
                <view class="row_con">
                    <u--input placeholder="小区、门牌号" clearable border="none" v-model="houseNumber"></u--input>
                </view>
            </view>
        </view>

        <view class="line"></view>
        <view class="isdef" @click="headerSettingDefaultAddressClick">
            <view class="isdef_left">
                <view class="isdef_left1">设置默认地址</view>
                <view class="isdef_left2">提醒：下单时会优先选择</view>
            </view>
            <view class="isdef_right">
                <img v-if="isDefault == 2" src="https://static.hshuishang.com/property-img-file/com_check1.png" alt="" />
                <img v-if="isDefault == 1" src="https://static.hshuishang.com/property-img-file/com_check2.png" alt=""  />
            </view>
        </view>

        <view class="btn" @click="headerSubmitClick">确定</view>

    </view>
</template>

<script>
import {
    apiArr
} from '../../../api/area';
import { apiArr as apiArr2 } from '../../../api/shop';
import {
    picUrl,
    menuButtonInfo,
    request,
    NavgateTo
} from '../../../utils';
export default {
    data() {
        return {
            top: "",
            localHeight: "",
            value: '',
            type: "error",
            tab: 0,

            provList: [], // 省
            cityList: [], //市
            distList: [], // 区
            defaultCity: [],  // 默认展示的市区数据
            defaultDist: [], // 默认展示的县/区数据
            confirmProv: {}, // 默认选中省
            confirmProv1: {},
            confirmCity: {}, // 默认选中市
            confirmDist: {}, // 默认选中区/县
            sf: true,
            xsq: {},
            value2: '',

            isShow: false,
            id: '',
            type: '',
            orientation: uni.getStorageSync('location'),
            name: '',
            phone: '',
            houseNumber: '',
            isDefault: 2,
            showOrientation: true,
        }
    },
    methods: {
        changeTab(e) {
            this.tab = e;
        },
        chooseAddress() {
            console.log(123);
            this.isShow = true;
            NavgateTo("/pages/shopcity/shopcity")
        },
        /////////////////////////////////// 省市区方法///////////////////////////////////////////
        // 获取省份信息
        async getProvList() {
            const res = await request(apiArr.getArea, 'POST', {}, { silent: false });
            this.provList = res.rows;
            this.confirmProv1 = res.rows[0]
            // 缓存省市区数据
            this.getCityList();
        },

        // 获取市区信息
        async getCityList(sq, x,) {
            console.log('11swq', sq);
            console.log('获取x', x);
            if (!this.sf) {
                console.log('省份没变，查市跟区', this.cityList)
                let newDist = this.cityList[sq];
                console.log('新的市信息', newDist);
                if (!this.xsq || this.xsq.ad_code !== newDist.ad_code) {
                    console.log('新市区跟旧市区不一致')
                    this.xsq = newDist;
                    this.confirmCity = newDist;
                    this.getDistList(newDist, x);
                } else {
                    console.log('新市区跟旧市区一致');
                    this.confirmDist = this.defaultDist[x]
                }
                return
            }
            const res = await request(apiArr.getArea, 'POST', { parent_ad_code: this.confirmProv1.ad_code }, { silent: false });
            this.cityList = res.rows;
            
            this.defaultCity = res.rows;
            this.confirmCity = res.rows[0]; // 拿市的第一条区查区
            this.xsq = res.rows[0]; // 初始化xsq为第一个城市
            this.getDistList(this.xsq, x);
        },
        // 获取 县/区 信息
        async getDistList(xsq, x) {
            console.log('页面传递的x',x);
            const res = await request(apiArr.getArea, 'POST', { parent_ad_code: xsq ? xsq.ad_code : this.confirmCity.ad_code }, { silent: false });
            this.distList = res.rows;
            this.defaultDist = res.rows;
            this.confirmDist = res.rows[0] // 区的第一条信息
        },

        async headerSubmitClick() {
            console.log('省' ,this.confirmProv1);
            console.log('xsq' ,this.xsq);
            console.log('confirmCity' ,this.confirmCity);
            console.log('confirmDist' ,this.confirmDist);
            const { confirmProv1, xsq, confirmCity, confirmDist  } = this;
            if(!this.name) {
                uni.showToast({
					title: '请输入收货人名称',
					icon: 'none'
				})
                return
            }
            if(!this.phone) {
                uni.showToast({
					title: '请输入收货人手机号',
					icon: 'none'
				})
                return
            }
            if(this.tab == 0 && this.showOrientation) {
                uni.showToast({
					title: '请输入收货地址',
					icon: 'none'
				})
                return
            }
            if(!this.houseNumber) {
                uni.showToast({
					title: '请输入门牌号',
					icon: 'none'
				})
                return
            }
            if(this.type === 'edit') {
                const res = await request(apiArr2.updateAddress, "POST", {
                    id: this.id,
                    name: this.name,
                    phone: this.phone,
                    address: this.tab === 0 ? this.orientation.region + this.orientation.district : `${confirmProv1.short_name}${xsq.short_name ? xsq.short_name : confirmCity.short_name}${confirmDist.short_name}`,
                    house_number: this.houseNumber,
                    is_default: this.isDefault
                }, { nested: true})
                console.log('编辑成功', res);
                if(res.code === 1) {
                    uni.showToast({
                        title: '地址更新成功',
                        icon: 'success',
                        mask: true
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    }, 1000)
                }
            } else {
                const res = await request(apiArr2.addAddress, 'POST', {
                    name: this.name,
                    phone: this.phone,
                    address: this.tab === 0 ? this.orientation.region + this.orientation.district : `${confirmProv1.short_name}${xsq.short_name ? xsq.short_name : confirmCity.short_name}${confirmDist.short_name}`,
                    house_number: this.houseNumber,
                    is_default: this.isDefault
                }, { nested: true})
                if(res.code === 1) {
                    uni.showToast({
                        title: '地址添加成功',
                        icon: 'success',
                        mask: true
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    }, 1000)
                }
            }
            
        },

        headerConfirmClick() {
            this.showOrientation = false;
            this.isShow = true;
            this.orientation = uni.getStorageSync('location');
        },
        headerSettingDefaultAddressClick() {
            this.isDefault = this.isDefault == 2 ? 1 : 2;
        },
        async init() {
            uni.showLoading({
                title: '加载中',
                mask: true
            });
            try {
                this.getProvList()
                uni.hideLoading();
            } catch (error) {
                uni.hideLoading();
                console.log('获取省市区信息异常', error);
            }
        },
        // 切换省市区时联动改变参数值
        bindChange(e) {
            console.log('[1231331], e', e);
            const { value } = e.detail;
            let newCrty = this.provList[value[0]];
            console.log('新的省份信息', newCrty);
            console.log('旧的省信息', this.confirmProv1);
            
            // 判断省份是否变化
            if (newCrty.ad_code === this.confirmProv1.ad_code) {
                console.log('省份信息没变');
                this.sf = false;
            } else {
                this.sf = true;
            }
            
            console.log('this.cityListthis.cityList', this.cityList);
            this.confirmProv1 = newCrty
            this.getCityList(value[1], value[2])
        },
        /////////////////////////////////// 省市区方法///////////////////////////////////////////
    },
    onLoad(options) {
        console.log('12231', options);
        if(options.item) {
            const item = JSON.parse(options.item);
            console.log('1231', item);
            this.name = item.name;
            this.phone = item.phone;
            this.orientation = {
                region: item.address,
                district: ''
            }
            this.showOrientation = false;
            this.id = item.id;
            this.type = 'edit';
            this.isShow = false;
            this.isDefault = item.is_default;
            this.houseNumber = item.house_number;
        }
        const meun = menuButtonInfo();
        this.top = meun.top;
        this.localHeight = meun.height;
        this.init()
    },
    onShow() {
        if(!this.isShow ) return;
        if(this.orientation.district !== uni.getStorageSync('location').district) {
            this.orientation = uni.getStorageSync('location');
            this.showOrientation = false;
        }
    },
    onReachBottom() {

    },
}
</script>

<style>
@import url("./index.css");
</style>