<template>
    <nav-bar :navbar-data="navbarData" />
    <view class="update-address" :style="{ marginTop: height + 'px' }">
        <view class="address">
            <van-cell-group>
                <view class="row">
                    <label>姓名</label>
                    <view class="row-right">
                        <input type="text" v-model="patName" placeholder="请输入姓名" @input="onBlurName">
                    </view>
                </view>
                <view class="row">
                    <label>手机号码</label>
                    <view class="row-right">
                        <input type="number" v-model="mobile" placeholder="请输入手机号码" @input="getBlurMobileValue">
                    </view>
                </view>
                <!-- <view class="row">
                    <label>所在地区</label>
                    <view class="row-right">
                        <input type="number" :value="addressDesc" placeholder="请选择取药人所在信息" @focus="handleAddressSelectFocus">
                    </view>
                </view> -->
                <view class="row">
                    <label>所在地区</label>
                    <view class="row-right">
                        <view :class="addressDesc ? 'select-picker-value' : 'select-picker-value placeholder'" @tap="handleAddressSelectFocus">{{ addressDesc ? addressDesc : '请选择取药人所在地区' }}</view>
                    </view>
                </view>
                <!-- <common provinceDesc="{{provinceDesc}}" cityDesc="{{cityDesc}}" areaDesc="{{areaDesc}}" villageDesc="{{villageDesc}}" status="1" addressData='所在地区' id="componentId" bind:twoLevelCommentBtn='twoLevelCommentBtnClick' /> -->
                <view class="row">
                    <label>详细地址</label>
                    <view class="row-right">
                        <input type="text" v-model="address" placeholder="街道、小区、楼号等信息" @input="onBlurAddress">
                    </view>
                </view>
            </van-cell-group>
            <view class="cont-down">
                <van-button type="info" class="btn" :disabled="saveState" @tap="saveData">{{ saveState ? '保存中...' : '保存并使用' }}</van-button>
            </view>
            <view class="cont-delete" v-if="optionType == 'edit'">
                <van-button class="btn" size="normal" @tap="deleteAddr(id)" hairline plain>删除该地址</van-button>
            </view>
        </view>
    </view>
    <addressSelectionControl ref="addressSelectionControl" @addressBoxAssignment="addressBoxAssignment" />
</template>

<script>
import $http from "@/utils/https";
import Utils from '@/utils/utils';
import navBar from '@/components/navBar/index';
import VanCellGroup from '@/components/cell-group/index';
import VanCell from '@/components/cell/index';
import VanButton from '@/components/button/index';
import addressSelectionControl from '@/components/addressSelectionControl/index';
const app = getApp()
export default {
    components: {
        'nav-bar': navBar,
        'van-button': VanButton,
        'van-cell-group': VanCellGroup,
        'van-cell': VanCell,
        'addressSelectionControl': addressSelectionControl
    },
    data() {
        return {
            height: app.globalData.height,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "新增收货地址",
                // homePath: "../../tabBar/index/index",
            },
            visible: false,
            detelist: {},
            id: '',
            patName: '',
            mobile: '',
            provinceID: '1',
            cityID: '1',
            areaID: '1',
            villageID: '1',
            address: '',
            selectAddress: [],
            turnFlag: "N",
            detailObj: {},
            cardDetails: {},
            addressDesc: "",
            saveState: false,
            optionType: 'add', // 操作类型
        }
    },
    onLoad: function (options) {
        if (options && options.optionType) {
            this.optionType = options.optionType
            if(options.optionType == 'edit') {
                this.navbarData.title = '编辑收货地址'
            }
        }

        if (options.jsonStr) {
            let item = JSON.parse(options.jsonStr)
            let { cardDetails } = this;
            cardDetails.location = item ? item.provinceDesc +'-'+ item.cityDesc +'-'+ item.addressDesc +'-'+ item.villageDesc : "";
            this.setData({
                detelist: item,
                id: item.id,
                cardDetails
            }, () => {
                this.getAddressInfon()
            })
        }

        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on("detailObj", (data) => {
            if(data && data.hasOwnProperty('addressObj')) {
                this.setData({
                    detailObj: data.detailObj,
                    addressObj: data.hasOwnProperty('addressObj') && data.addressObj,
                    turnFlag: data.flag,
                    id: data.hasOwnProperty('addressObj') && data.addressObj.id
                });
            } else {
                this.setData({
                    detailObj: data.detailObj,
                    turnFlag: data.flag
                });
            }
        })
    },
    methods: {
        twoLevelCommentBtnClick: function (e) {
            console.log(33333, e.detail)
            this.setData({
                selectAddress: e.detail
            });
            // if(e.detil.length>0){
            //   this.setData({
            //   })
            // }
        },

        onBlurName: function (event) {
            this.setData({
                patName: event.detail.value
            })
        },

        getBlurMobileValue: function (event) {
            this.setData({
                mobile: event.detail.value
            })
        },

        onChangeMobile: function (event) {
            var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
            if (event == '') {
                return false
            } else if (event.length != 11) {
                return false
            } else if (!myreg.test(event)) {
                return false
            }
            return true
        },

        onBlurAddress: function (event) {
            this.setData({
                address: event.detail.value
            })
        },

        formSubmit: function (event) {
            console.log(event)
        },

        /*保存*/
        saveData: function () {
            const self = this
			self.setData({ saveState: true })
			console.log('提交次数')
            let { patName, mobile, address, cardDetails } = self;
            if (!patName) {
                self.setData({ saveState: false })
                Utils.showToast('姓名有误', 'error')
                return
            }
            if (!self.onChangeMobile(mobile)) {
                self.setData({ saveState: false })
                Utils.showToast('手机号有误', 'error')
                return
            }
            if (!(cardDetails && cardDetails.location)) {
                self.setData({ saveState: false })
                Utils.showToast('请选择所在地区', 'error')
                return
            }
            if (!address) {
                self.setData({ saveState: false })
                Utils.showToast('请输入详细地址', 'error')
                return
            }
            let userData = this.$cache.get('userData');
            let data = {
                params: [{
                    pubAccCode: userData.pubAccCode,
                    openID: userData.openID,
                    id: self.id,
                    name: patName,
                    mobile: mobile,
                    provinceID: cardDetails && cardDetails.provID ? cardDetails.provID : (cardDetails && cardDetails.provinceID ? cardDetails.provinceID : ""),
                    cityID: cardDetails && cardDetails.cityID ? cardDetails.cityID : "",
                    areaID: cardDetails && cardDetails.countryID ? cardDetails.countryID : (cardDetails && cardDetails.areaID ? cardDetails.areaID : ""),
                    villageID: cardDetails && cardDetails.regionID ? cardDetails.regionID : (cardDetails && cardDetails.villageID ? cardDetails.villageID : ""),
                    address: address
                }]
            }
            $http.post("urlS", self, {
                code: "01020005",
                data: data,
                success: function (res) {
                    console.log("save", res)
                    if (+res.errorCode === 0) {
                        self.setData({ saveState: false })
                        Utils.showToast(res.errorMessage, 'success')
                        setTimeout(() => {
                            if (self.turnFlag == 'N') {
                                // console.log('turn', this.turnFlag)
                                uni.navigateBack()
                            } else {
                                var detailObj = self.detailObj
                                uni.navigateTo({
                                    url: "/pages/order/pages/distributionInfo/distributionInfo",
                                    success: (re) => {
										this.$cache.set('addrDetailObj', {
                                            detailObj: detailObj,
                                            addressObj: res.result.address
                                        })
                                        // re.eventChannel.emit('addrDetailObj', {
                                        //     detailObj: detailObj,
                                        //     addressObj: res.result.address
                                        // })
                                    },
                                })
                            }
                        }, 500)
                    } else {
                        self.setData({ saveState: false })
                        Utils.showToast(res.errorMessage, 'error')
                    }
                }
            })
        },

        onChange(event) {
            // event.detail 为当前输入的值
            console.log(event.detail);
        },

        handleAddressSelectFocus() {
            this.$refs.addressSelectionControl.onClickShow()
        },

        // 给地址选框赋值
        addressBoxAssignment() {
            // 获取城市描述
            let cityData = this.$refs.addressSelectionControl.exportCitySelectInfo("ID");
            let { cardDetails } = this;
            cardDetails.location = cityData && cityData.addressDesc ? cityData.addressDesc : "";
            // console.log(cardDetails, cityData)
            this.setData({ cardDetails: { ...cardDetails, ...cityData }, addressDesc: cardDetails && cardDetails.location ? cardDetails.location : "" }, () => {
                this.$refs.addressSelectionControl.onClickHide(); // 关闭城市弹窗
            })
        },

        /*获取地址详细*/
        getAddressInfon: function () {
            let data = {
                params: [{
                    id: this.id
                }]
            }
            $http.post("urlS", this, {
                code: "01020016",
                data: data,
                success: function (res) {
                    let userInfo = res.result.address;
                    let addressDesc = userInfo && userInfo.provinceDesc ? (((userInfo.provinceDesc) + ((userInfo.cityDesc ? ('-' + userInfo.cityDesc) + ((userInfo.areaDesc ? ('-' + userInfo.areaDesc) + (userInfo.villageDesc ? ('-' + userInfo.villageDesc) : '') : '')) : '')))) : ""
                    userInfo.provID = userInfo.provinceID;
                    userInfo.provDesc = userInfo.provinceDesc;
                    userInfo.cityID = userInfo.cityID;
                    userInfo.cityDesc = userInfo.cityDesc;
                    userInfo.countryID = userInfo.areaID;
                    userInfo.countryDesc = userInfo.areaDesc;
                    userInfo.regionID = userInfo.villageID;
                    userInfo.regionDesc = userInfo.villageDesc;
                    userInfo.location = addressDesc;
                    if (+res.errorCode === 0) {
                        this.setData({
                            patName: res.result.address.name,
                            mobile: res.result.address.mobile,
                            address: res.result.address.address,
                            cardDetails: userInfo,
                            addressDesc
                        });
                        // if (res.result.address.provinceDesc) {
                        //   this.selectComponent("#componentId").getProvinceDetail(res.result.address.provinceDesc)
                        // }
                        // if (res.result.address.cityDesc) {
                        //   this.selectComponent("#componentId").getCityDetail(res.result.address.provinceID, res.result.address.cityDesc)
                        // }
                        // if (res.result.address.areaDesc) {
                        //   this.selectComponent("#componentId").getAreaDetail(res.result.address.cityID, res.result.address.areaDesc)
                        // }
                        // if (res.result.address.villageDesc) {
                        //   this.selectComponent("#componentId").getStreetDetail(res.result.address.areaID, res.result.address.villageDesc)
                        // }
                    } else {
                        this.setData({
                            detelist: {}
                        });
                    }
                }
            });
        },

        /*删除*/
        deleteAddr(id) {
            console.log(456, id)
            uni.showModal({
                title: '提示',
                content: '地址删除后不可恢复',
                success: (res) => {
                    console.log(res)
                    if (res.confirm) {
                        console.log('用户点击确定')
                        this.deleteAddress(id)
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        },

        deleteAddress(id) {
            console.log('222', id)
            let data = {
                params: [{
                    id: id,
                }]
            }
            $http.post("urlS", this, {
                code: "01020007",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        Utils.showToast(res.errorMessage,'success')
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 2000)
                    } else {
                        Utils.showToast(res.errorMessage,'error')
                    }
                }
            });
        },
    }
}
</script>

<style lang="scss">
.address {
	padding-top: 20rpx;
    .van-cell {
        /* justify-content: space-between; */
        position: relative;

        .van-cell__title {
            flex: none;
            width: 180rpx;
        }

        .van-cell__value {
            display: block;
            flex: none;
            width: calc(100% - 16rpx - 180rpx - 16rpx);
            text-align: left;
            color: #666;
        }
    }

    .van-field__input {
        color: #666 !important;
    }
}

.select-picker-value {
    font-size: 28rpx;
}

.cont-down,
.cont-delete {
    margin-top: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    padding: 0 24rpx;
    box-sizing: border-box;

    .van-button,
    .btn {
        background-color: var(--button-info-background-color, #1989fa);
        color: #fff;
        width: 100%;
        text-align: center;
        border-radius: 10rpx;
        font-size: 32rpx;
        height: 100rpx;
        line-height: 100rpx;
    }
}

.cont-delete {

    .van-button,
    .btn {
        background-color: var(--button-default-background-color, #fff);
        color: #505050;
    }
}
</style>