<template>
    <van-cell :title="addressData" is-link :value="currentAreaInfo ? currentAreaInfo : '请选择'" @click="showPopup(true)"></van-cell>
    <view v-if="show" class="popup">
        <view class="common">
            <view class="tit">
                <text @tap="showPopup(false)" class="onClose">取消</text>
                <text class="tit-conter">请选择地址</text>
                <text @tap="determineData" class="determineData">确定</text>
            </view>
            <picker-view indicator-style="height: 50px;" style="width: 100%; height: 300px;" :value="cityAreaIndexs"
                @change="onPickerChange">
                <picker-view-column>
                    <view v-for="(item, index) in provinceArr" :key="index" style="line-height: 50px; text-align: center;">
                        {{ item }}</view>
                </picker-view-column>
                <picker-view-column>
                    <view v-for="(item, index) in cityArr" :key="index" style="line-height: 50px; text-align: center;">
                        {{ item }}</view>
                </picker-view-column>
                <picker-view-column v-if="status == '1' || status == '3' || status == '5' || status == '4'">
                    <view v-for="(item, index) in areaArr" :key="index" style="line-height: 50px; text-align: center;">
                        {{ item }}</view>
                </picker-view-column>
                <picker-view-column v-if="status == '1' || status == '3' || status == '5'">
                    <view v-for="(item, index) in streetArr" :key="index" style="line-height: 50px; text-align: center;">
                        {{ item }}</view>
                </picker-view-column>
            </picker-view>
        </view>
        <van-overlay :show="show" @click="onClickHide" />
    </view>
</template>

<script>
import $http from "@/utils/https";
import Util from '@/utils/utils'
import vanCell from '@/components/cell/index'
import vanOverlay from '@/components/overlay/index'
export default {
    components: {
        'van-cell': vanCell,
        'van-overlay': vanOverlay
    },
    props: {
        provinceDesc: {
            type: String,
            default: ''
        },
        cityDesc: {
            type: String,
            default: ''
        },
        areaDesc: {
            type: String,
            default: ''
        },
        villageDesc: {
            type: String,
            default: ''
        },
        bool: {
            type: String,
            default: ''
        },
        status: {
            type: String,
            default: ''
        },
        addressData: {
            type: String,
            default: ''
        },
        difference: {
            type: String,
            default: ''
        },
        defaultIndexs: {
            type: Array,
            default: []
        },
        defaultProvince: {
            type: Object,
            default: {}
        },
        defaultCity: {
            type: Object,
            default: {}
        },
        defaultArea: {
            type: Object,
            default: {}
        }
    },
    watch: {
        defaultIndexs: function(newData) {
            console.log('数据更新：', newData)
            this.cityAreaIndexs = newData
        },
        provinceDesc: function(newData) {
            this.currentAreaInfo = newData + this.cityDesc + (this.areaDesc?this.areaDesc:'') + (this.villageDesc?this.villageDesc:'')
            this.currentProvinceLabel = newData
        },
        cityDesc: function(newData) {
            this.currentAreaInfo = this.provinceDesc + newData + (this.areaDesc?this.areaDesc:'') + (this.villageDesc?this.villageDesc:'')
            this.currentCityLabel = newData
        },
        areaDesc: function(newData) {
            this.currentAreaInfo = this.provinceDesc + this.cityDesc + newData + (this.villageDesc?this.villageDesc:'')
            this.currentAreaLabel = newData
        },
        villageDesc: function(newData) {
            this.currentAreaInfo = this.provinceDesc + this.cityDesc + this.areaDesc + newData
            this.currentStreetLabel = newData
        }
    },
    data() {
        return {
            setTimeoutTimer: null,
            show: false,
            dataLoadStatus: [false, false], // 数据loading状态
            cityAreaIndexs: [0, 0],
            provinceArr: [],
            provinceAll: [],
            cityArr: [],
            cityAll: [],
            areaArr: [],
            areaAll: [],
            streetArr: [],
            streetAll: [],
            currentAreaInfo: '',
            currentProvinceLabel: '',
            currentCityLabel: '',
            currentAreaLabel: '',
            currentStreetLabel: '',
        }
    },
    created() {
        // console.log('address created')
        const self = this
    },
    mounted() {
        const self = this
        const {
            status,
            provinceDesc,
            cityDesc,
            areaDesc,
            villageDesc,
            defaultProvince
        } = self
        if (self.defaultIndexs.length > 0) self.cityAreaIndexs = self.defaultIndexs
        this.defaultDealAreaData({
            provinceDesc,
            cityDesc,
            areaDesc,
            villageDesc
        })
        // console.log('是否有默认数据', self)
        // console.log(self.defaultProvince)
        // setTimeout(() => {
        //     self.getProvinceDetail(self.defaultProvince.label)
        // }, 200)
    },
    methods: {
        updateDefaultArea() {
            const self = this
            clearTimeout(self.setTimeoutTimer)
            self.setTimeoutTimer = setTimeout(() => {
                self.defaultDataDeal()
            }, 600)
        },

        // 处理默认城市显示数据
        defaultDealAreaData({
            provinceDesc,
            cityDesc,
            areaDesc,
            villageDesc
        }) {
            const self = this
            const {
                status
            } = self
            if (['1', '3', '5'].indexOf(status) > -1) {
                self.currentAreaInfo = provinceDesc + cityDesc + areaDesc + villageDesc
            }
            if (['2'].indexOf(status) > -1) {
                self.currentAreaInfo = provinceDesc + cityDesc
            }
            if (['4'].indexOf(status) > -1) {
                self.currentAreaInfo = provinceDesc + cityDesc + areaDesc
            }
        },
		
		showPopup(bol) {
		    const { status } = this
		    console.log('status：',status)
		    console.log('currentProvinceLabel：', this.currentProvinceLabel)
		    if (['1', '3', '5'].indexOf(status) > -1) {
		        this.dataLoadStatus = [false, false, false, false]
		    }
		    if (['2'].indexOf(status) > -1) {
		        this.dataLoadStatus = [false, false]
		    }
		    if (['4'].indexOf(status) > -1) {
		        this.dataLoadStatus = [false, false, false]
		    }
		    this.getProvinceDetail(this.currentProvinceLabel).then(() => {
				this.defaultDataDeal()
				this.setData({
					show: bol
				})
			})
		},

        defaultDataDeal() {
			return new Promise((resolve, reject) => {
				const { provinceArr, cityArr, areaArr, streetArr } = this
				const { 
					currentProvinceLabel,
					currentCityLabel,
					currentAreaLabel,
					currentStreetLabel
				} = this
				console.log('currentProvinceLabel', currentProvinceLabel)
				console.log('currentCityLabel', currentCityLabel)
				console.log('currentAreaLabel', currentAreaLabel)
				console.log('currentStreetLabel', currentStreetLabel)
				if(currentProvinceLabel && provinceArr && provinceArr.length > 0) {
					console.log('provinceArr', provinceArr)
					for(let i=0;i < provinceArr.length; i++) {
						if(provinceArr[i].indexOf(currentProvinceLabel) > -1) {
							console.log(provinceArr[i],currentProvinceLabel,provinceArr[i].indexOf(currentProvinceLabel) > -1,i)
							this.cityAreaIndexs[0] = i
							break;
						}
					} 
				}
				if(currentCityLabel && cityArr && cityArr.length > 0) {
					console.log('cityArr', cityArr)
					for(let i=0;i < cityArr.length; i++) {
						if(cityArr[i].indexOf(currentCityLabel) > -1) {
							this.cityAreaIndexs[1] = i
							break;
						}
					} 
				}
				if(currentAreaLabel && areaArr && areaArr.length > 0) {
					console.log('areaArr', areaArr)
					for(let i=0;i < areaArr.length; i++) {
						if(areaArr[i].indexOf(currentAreaLabel) > -1) {
							this.cityAreaIndexs[2] = i
							break;
						}
					} 
				}
				if(currentStreetLabel && streetArr && streetArr.length > 0) {
					console.log('streetArr', streetArr)
					for(let i=0;i < streetArr.length; i++) {
						if(streetArr[i].indexOf(currentStreetLabel) > -1) {
							this.cityAreaIndexs[3] = i
							break;
						}
					}
				}
				resolve()
				console.log('cityAreaIndexs：',this.cityAreaIndexs)
				return
				if (this.defaultProvince.hasOwnProperty('value')) {
					this.cityAreaIndexs[0] = this.defaultProvince.value - 1
				}
				if (this.cityAll.length > 0 && this.defaultCity.hasOwnProperty('value')) {
					this.cityAll.map((item, i) => {
						if (item.value == this.defaultCity.value) {
							this.cityAreaIndexs[1] = i
						}
					})
				}
				if (this.areaAll.length > 0 && this.defaultArea.hasOwnProperty('value')) {
					// console.log('areaAll', this.areaAll, this.defaultArea)
					this.areaAll.map((item, i) => {
						// console.log(item.value, this.defaultArea.value)
						if (item.value == this.defaultArea.value) {
							this.cityAreaIndexs[2] = i
						}
					})
				}
			})
        },

        determineData: function () {
            const {
                status,
                cityAreaIndexs,
                provinceAll,
                cityAll,
                areaAll,
                streetAll,
            } = this
            const proviceIndex = cityAreaIndexs[0]
            const cityIndex = cityAreaIndexs[1]
            const areaIndex = cityAreaIndexs.length >= 3 ? cityAreaIndexs[2] : null
            const streetIndex = cityAreaIndexs.length == 4 ? cityAreaIndexs[3] : null

            // console.log(proviceIndex, cityIndex, areaIndex, streetIndex)

            this.setData({
                areaInfo: provinceAll[proviceIndex].label + cityAll[cityIndex].label,
                HometownList: provinceAll[proviceIndex].label + cityAll[cityIndex].label,
                urgentList: provinceAll[proviceIndex].label + cityAll[cityIndex].label,
                bornList: provinceAll[proviceIndex].label + cityAll[cityIndex].label,
                hukouAddressList: provinceAll[proviceIndex].label + cityAll[cityIndex].label
            });

            if (this.cityAreaIndexs.length == 3) {
                this.areaInfo += areaAll[areaIndex].label
                this.urgentList += areaAll[areaIndex].label
                this.hukouAddressList += areaAll[areaIndex].label
            } else if (this.cityAreaIndexs.length == 4) {
                this.areaInfo += streetAll[streetIndex].label
                this.urgentList += streetAll[streetIndex].label
                this.hukouAddressList += streetAll[streetIndex].label
            }

            this.setData({
                show: false
            });
            let arr = [];
            let newObj = streetAll[0];
            arr[0] = provinceAll[proviceIndex];
            arr[1] = cityAll[cityIndex];
            arr[2] = this.cityAreaIndexs.length >= 3 ? areaAll[areaIndex] : [];
            arr[3] = this.cityAreaIndexs.length == 4 ? streetAll[streetIndex] : []
            // console.log(arr)
            if (status == '1') {
                this.$emit('twoLevelCommentBtn', { detail: { value: arr, indexs: cityAreaIndexs } })
            }
            if (status == '5') {
                this.$emit('hukouAddressLists', { detail: { value: arr, indexs: cityAreaIndexs } })
            }
            if (status == '2') {
                let hometown = [];
                hometown[0] = provinceAll[proviceIndex];
                hometown[1] = cityAll[cityIndex];
                this.$emit('onSelectproCitie', { detail: { value: hometown, indexs: cityAreaIndexs } })
            }
            if (status == '3') {
                this.$emit('urgentClick', { detail: { value: arr, indexs: cityAreaIndexs } })
            }
            if (status == '4') {
                let bornData = [];
                bornData[0] = provinceAll[proviceIndex];
                bornData[1] = cityAll[cityIndex];
                bornData[2] = areaAll[areaIndex];
                this.$emit('onBornCitie', { detail: { value: bornData, indexs: cityAreaIndexs } })
            }
            this.defaultDealAreaData({
                provinceDesc: provinceAll[proviceIndex].label,
                cityDesc: cityAll[cityIndex].label,
                areaDesc: areaIndex != null ? areaAll[areaIndex].label:'',
                villageDesc: streetIndex != null ? streetAll[streetIndex].label:''
            })
        },

        onPickerChange(e) {
            const self = this
            const { cityAreaIndexs } = this
            const indexs = e.detail.value
            let resIndexs = null
            if (cityAreaIndexs) {
                indexs.map((item, i) => {
                    const oldIndex = cityAreaIndexs[i]
                    if (item != oldIndex) {
                        self.modeDataDeal(i, item)
                    }
                })
            } else {
                indexs.map((item, i) => {
                    if (item > 0) {
                        self.modeDataDeal(i, item)
                    }
                })
            }
            this.setData({
                cityAreaIndexs: indexs
            })
        },

        modeDataDeal(i, newIndex) {
            const self = this
            const {
                provinceAll,
                cityAll,
                areaAll
            } = this
            switch (i) {
                case 0:
                    self.setData({
                        cityArr: [],
                        areaArr: [],
                        streetArr: [],
                    })
                    self.getCityDetail(provinceAll[newIndex])
                    break;
                case 1:
                    self.setData({
                        areaArr: [],
                        streetArr: []
                    });
                    self.getAreaDetail(cityAll[newIndex])
                    break;
                case 2:
                    self.setData({
                        streetArr: []
                    });
                    self.getStreetDetail(areaAll[newIndex])
                    break;
            }
        },

        /**请求省数据
         * **/
        getProvinceDetail: function (val) {
            const self = this
            return new Promise((resolve, reject) => {
                // console.log(val)
                let data = {
                    params: [{}]
                }
                $http.post("urlS", self, {
                    code: "02010030",
                    data: data,
                    success: function (res) {
                        self.dataLoadStatus[0] = true
                        if (+res.errorCode === 0) {
                            let dataList = res.result.rows ? res.result.rows : [];
                            let arr = [];
                            for (var i = 0; i < dataList.length; i++) {
                                arr.push(dataList[i].label)
                            }
                            console.log(arr)
                            self.setData({
                                provinceArr: arr,
                                provinceAll: dataList,
                            });
                            const provinceIndex = val ? arr.indexOf(val) : ''
                            // console.log('provinceIndex', provinceIndex, res.result.rows[provinceIndex])
                            if (!val) {
                                self.getCityDetail(res.result.rows[0]).then(() => {
									resolve()
								});
                            } else {
                                self.getCityDetail(res.result.rows[provinceIndex], self.currentCityLabel).then(() => {
									resolve()
								});
                            }
                        } else {
                            self.setData({
                                provinceArr: []
                            });
							resolve()
                        }
                    }
                })
            })
        },

        /**请求市数据
         * **/
        getCityDetail: function (obj, desc) {
            const self = this
            return new Promise((resolve, reject) => {
                console.log(obj, desc)
                let data = {
                    params: [{
                        provinceID: obj.value ? obj.value : obj
                    }]
                }
                $http.post("urlS", self, {
                    code: "02010031",
                    data: data,
                    success: function (res) {
                        self.dataLoadStatus[1] = true
                        if (+res.errorCode === 0) {
                            let dataList = res.result.rows ? res.result.rows : [];
                            let arr = [];
                            for (var i = 0; i < dataList.length; i++) {
                                arr.push(dataList[i].label)
                            }
                            self.setData({
                                cityArr: arr,
                                cityAll: dataList,
                                cityIndex: desc ? arr.indexOf(desc) : 0
                            });
                            // console.log(desc)
                            if (!desc) {
                                self.getAreaDetail(res.result.rows[0]).then(() => {
									resolve()
								});
                            } else {
                                const dataArr = res.result.rows.filter(item => item.label == desc)
                                self.getAreaDetail(dataArr[0], self.currentAreaLabel).then(() => {
									resolve()
								});
                            }
                        } else {
                            self.setData({
                                cityArr: []
                            });
							resolve()
                        }
                    }
                });
            })
        },

        /**请求区数据
         * **/
        getAreaDetail: function (obj, desc) {
            console.log(obj,desc)
            const self = this
            return new Promise((resolve, reject) => {
                if(!obj) return
                let data = {
                    params: [{
                        cityID: obj && obj.value ? obj.value : obj
                    }]
                }
                $http.post("urlS", self, {
                    code: "02010032",
                    data: data,
                    success: function (res) {
                        if (self.dataLoadStatus.length > 2) {
                            self.dataLoadStatus[2] = true
                        }
                        if (+res.errorCode === 0) {
                            let dataList = res.result.rows ? res.result.rows : [];
                            let arr = [];
                            for (var i = 0; i < dataList.length; i++) {
                                arr.push(dataList[i].label)
                            }
                            self.setData({
                                areaArr: arr,
                                areaAll: dataList,
                                areaIndex: desc ? arr.indexOf(desc) : 0
                            });
                            if (!desc) {
                                self.getStreetDetail(res.result.rows[0]).then(() => {
									resolve()
								});
                            } else {
                                const dataArr = res.result.rows.filter(item => item.label == desc)
                                self.getStreetDetail(dataArr[0], self.currentStreetLabel).then(() => {
									resolve()
								});
                            }
                        } else {
                            this.setData({
                                areaArr: []
                            });
							resolve()
                        }
                    }
                });
            })

        },

        /**请求街道数据
         * **/
        getStreetDetail: function (obj, desc) {
            console.log(obj, desc)
            return new Promise((resolve, reject) => {
                if(!obj) return
                let data = {
                    params: [{
                        areaID: obj && obj.value ? obj.value : obj
                    }]
                }
                $http.post("urlS", this, {
                    code: "02010033",
                    data: data,
                    success: function (res) {
                        if (this.dataLoadStatus.length > 3) {
                            this.dataLoadStatus[3] = true
                        }
                        if (+res.errorCode === 0) {
                            let dataList = res.result.rows ? res.result.rows : [];
                            let arr = [];
                            for (var i = 0; i < dataList.length; i++) {
                                arr.push(dataList[i].label)
                            }
                            this.setData({
                                streetArr: arr,
                                streetAll: dataList,
                                streetIndex: desc ? arr.indexOf(desc) : 0
                            });
							resolve()
                        } else {
                            this.setData({
                                streetArr: []
                            });
							resolve()
                        }
                    }
                })
            })
        },
    }
}
</script>

<style>
.common {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 999;
    width: 750rpx;
    background: #fff;
}

.common .tit {
    text-align: right;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #fff;
    color: #1989fa;
    text-align: center;
}

.common .onClose {
    float: left;
    margin-left: 40rpx;
}

.common .tit-conter {
    color: #333;
    font-size: 32rpx;
}

.common .determineData {
    margin-right: 40rpx;
    float: right;
}

.van-overlay {
    z-index: 2;
}
</style>