<template>
    <!-- 地址选择控件 -->
    <van-overlay :show="visible" @click.stop="onClickHide">
        <view class="selected_view" :style="{ height: (widHeight * 8 / 9) + 'rpx' }" @tap.stop="handleStopPropagation">
            <view class="selected_top_view" :style="{ height: (100 + (85 * areaListData.length)) + 'rpx' }">
                <view class="selected_top_title_view">请选择</view>
                <view class="district_item_view" v-for="(itemVal, idx) in areaListData" :key="idx">
                    <view class="left_line_view">
                        <view v-if="idx === 0" class="line_white_view"></view>
                        <view v-else class="line_view"></view>
                        <view class="circle_view"></view>
                        <view
                            v-if="idx === (areaListData && areaListData.length ? (areaListData.length > 3 ? 3 : (areaListData.length - 1)) : 0)"
                            class="line_white_view"></view>
                        <view v-else class="line_view"></view>
                    </view>
                    <view class="district_view" :class="activeSteps - 1 === idx ? 'selectedView' : ''"
                        @tap.stop="handleStepsChildClick" :data-index="idx">{{ itemVal.label }}</view>
                </view>
            </view>
            <view class='selected_bottom_view'>
                <scroll-view scroll-y class="selected_scrollview" :scroll-into-view="scrollPosition"
                    :style="{ height: (widHeight * 8 / 9 - 100 - (85 * areaListData.length)) + 'rpx' }">
                    <view @tap.stop="handleStopPropagation" class="selected_title_view">{{ activeSteps === '1' ? "选择省" :
                        (activeSteps === '2' ? "选择城市" : (activeSteps === '3' ? "选择县（区）" : (activeSteps === '4' ? "选择镇（街道）" :
                            "选择省"))) }}</view>
                    <view
                        :class="areaListData && areaListData.length && areaListData[(activeSteps - 1)].value === itemVal.value ? 'cell_view_active cell_view' : 'cell_view'"
                        v-for="(itemVal, idx) in (activeSteps === '1' ? provSelectData : (activeSteps === '2' ? citySelectData : (activeSteps === '3' ? countrySelectData : (activeSteps === '4' ? regionSelectData : provSelectData))))"
                        :key="idx" @tap.stop='handleRadioChange' :data-obj="itemVal" :data-index="idx"
                        :id="'list' + itemVal.value">
                        {{ itemVal.label }}
                    </view>
                </scroll-view>
            </view>
        </view>
    </van-overlay>
</template>

<script>
import $http from "@/utils/https";
import globalMixin from "@/mixins/globalMixin";
import VanOverlay from '@/components/overlay/index'
const app = getApp()
export default {
	mixins: [globalMixin],
    components: {
        'van-overlay': VanOverlay
    },
	props: {
		selectedStop: { //1:省 2:市 3:区 4:街道
			type: Number,
			value: 4
		}, 
	},
    data() {
        return {
            visible: false,
            provSelectData: [],
            provValue: {},
            citySelectData: [],
            cityValue: {},
            countrySelectData: [],
            countryValue: {},
            regionSelectData: [],
            regionValue: {},
            stepListData: [],
            currentArray: [],
            widHeight: 1200,
            activeSteps: "1",
            areaListData: [],
            scrollPosition: "list"
        }
    },
    methods: {
        /*
          打开弹窗所需入参
            新增不需要传入参数，直接调用方法即可。
            编辑（数据回显）所需参数 --- userInfo为一个对象，需要包括至少八个字段（如果需要 ）
              如果为编辑的话需要参数id为必填字段
              1）、provID -- 省ID
              2）、provDesc -- 省描述
              3）、cityID -- 市ID
              4）、cityDesc -- 市描述
              …………
        */
        onClickShow(userInfo) {
            if (userInfo && userInfo.id) {
                let stepListData = [];
                let obj = {};
                obj.prov = this.filterIdAndDescripts(userInfo.provID, userInfo.provDesc);
                obj.city = this.filterIdAndDescripts(userInfo.cityID, userInfo.cityDesc);
                obj.country = this.filterIdAndDescripts(userInfo.countryID, userInfo.countryDesc);
                obj.region = this.filterIdAndDescripts(userInfo.regionID, userInfo.regionDesc);
                stepListData.push(obj);
                this.setData({ visible: true, stepListData, provValue: obj.prov[0], cityValue: obj.city[0], countryValue: obj.country[0], regionValue: obj.region[0] }, () => {
                    this.filterStepsData();
                    this.getProvSelectData(userInfo.provID);
                });
            } else {
                this.setData({ visible: true }, () => {
                    this.getProvSelectData();
                });
            }
        },

        // 将ID与描述处理成组件所需格式
        filterIdAndDescripts(id, desc) {
            if (id && desc) {
                let arr = [];
                let obj = {}
                obj.value = id ? id : "";
                obj.label = desc ? desc : "";
                arr.push(obj);
                return arr;
            } else {
                return [];
            }
        },

        // 关闭弹窗
        onClickHide() {
            this.setData({ visible: false });
        },

        // 获取省数据
        getProvSelectData(provID) {
            let data = {
                params: [{}]
            }
            $http.post("urlS", this, {
                code: "02010030",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.rows.length > 0 ? res.result.rows : [];
                        this.setData({ provSelectData: arr }, () => {
                            if (provID) {
                                this.setData({ scrollPosition: 'list' + provID })
                            }
                        })
                    }
                }
            });
        },

        // 获取市数据
        getCitySelectData(item) {
            let data = {
                params: [{
                    provinceID: item && item.value ? item.value : ""
                }]
            }
            $http.post("urlS", this, {
                code: "02010031",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.rows.length > 0 ? res.result.rows : [];
                        this.setData({ citySelectData: arr })
                    }
                }
            });
        },

        // 获取县（区）的数据
        getCountrySelectData(item) {
            let data = {
                params: [{
                    cityID: item && item.value ? item.value : ""
                }]
            }
            $http.post("urlS", this, {
                code: "02010032",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.rows.length > 0 ? res.result.rows : [];
                        this.setData({ countrySelectData: arr });
                    }
                }
            });
        },

        // 获取镇（街道）的数据
        getRegionSelectData(item) {
            let data = {
                params: [{
                    areaID: item && item.value ? item.value : ""
                }]
            }
            $http.post("urlS", this, {
                code: "02010033",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.rows.length > 0 ? res.result.rows : [];
                        if (!(arr && arr.length > 0)) {
                            let { stepListData } = this;
                            stepListData[0].region = [];
                            this.setData({ stepListData, regionSelectData: [], activeSteps: "3" }, () => {
                                this.filterStepsData();
                                this.$emit('addressBoxAssignment'); // 关闭弹窗
                            })
                        } else {
                            this.setData({ regionSelectData: arr });
                        }
                    }
                }
            });
        },

        handleRadioChange(e) {
            var item = e.currentTarget.dataset.obj
            let { activeSteps, stepListData } = this;
            if (!(stepListData && stepListData.length > 0)) {
                stepListData.push({});
            }
            let arr = [];
            arr.push(item);
            if (activeSteps === "1") {
				if(+this.selectedStop == 1) {
					this.setData({ stepListData, provValue: item}, () => {
						this.$emit('addressBoxAssignment'); // 关闭弹窗
					})
					return
				}
                let cityData = [
                    {
                        label: "请选择城市"
                    }
                ]
                stepListData[0].prov = arr;
                stepListData[0].city = cityData;
                stepListData[0].country = [];
                stepListData[0].region = [];
                this.setData({ stepListData, provValue: item, activeSteps: "2" }, () => {
                    this.filterStepsData();
                    this.getCitySelectData(this.provValue);
                })
            } else if (activeSteps === "2") {
				if(+this.selectedStop == 2) {
					this.setData({ stepListData, cityValue: item }, () => {
						this.$emit('addressBoxAssignment'); // 关闭弹窗
					})
					return
				}
                let countryData = [
                    {
                        label: "请选择县（区）"
                    }
                ]
                stepListData[0].city = arr;
                stepListData[0].country = countryData;
                stepListData[0].region = [];
                this.setData({ stepListData, cityValue: item, activeSteps: "3" }, () => {
                    // console.log(this.stepListData);
                    this.filterStepsData();
                    this.getCountrySelectData(this.cityValue);
                })
            } else if (activeSteps === "3") {
				if(+this.selectedStop == 3) {
					this.setData({ stepListData, countryValue: item }, () => {
						this.$emit('addressBoxAssignment'); // 关闭弹窗
					})
					return
				}
                let regionData = [
                    {
                        label: "请选择镇（街道）"
                    }
                ]
                stepListData[0].country = arr;
                stepListData[0].region = regionData
                this.setData({ stepListData, countryValue: item, activeSteps: "4" }, () => {
                    // console.log(this.stepListData);
                    this.filterStepsData();
                    this.getRegionSelectData(this.countryValue);
                })
            } else if (activeSteps === "4") {
                stepListData[0].region = arr;
                this.setData({ stepListData, regionValue: item }, () => {
                    // console.log(this.stepListData, this.activeSteps);
                    this.filterStepsData();
                    this.$emit('addressBoxAssignment'); // 关闭弹窗
                })
            }
        },

        // 修改选择省市区
        handleStepsChildClick(e) {
            var index = e.currentTarget.dataset.index;
            let { stepListData } = this;
            if (String(index) === "0") {
                let provData = [
                    {
                        label: "请选择省"
                    }
                ]
                stepListData[0].prov = provData;
                stepListData[0].city = [];
                stepListData[0].country = [];
                stepListData[0].region = [];
                this.setData({ activeSteps: String(index + 1), stepListData, provValue: {}, cityValue: {}, countryValue: {}, regionValue: {} }, () => {
                    this.filterStepsData();
                    this.getProvSelectData()
                })
            } else if (String(index) === "1") {
                let cityData = [
                    {
                        label: "请选择城市"
                    }
                ]
                stepListData[0].city = cityData;
                stepListData[0].country = [];
                stepListData[0].region = [];
                this.setData({ activeSteps: String(index + 1), stepListData, cityValue: {}, countryValue: {}, regionValue: {} }, () => {
                    this.filterStepsData();
                    this.getCitySelectData(this.provValue)
                })
            } else if (String(index) === "2") {
                let countryData = [
                    {
                        label: "请选择县（区）"
                    }
                ]
                stepListData[0].country = countryData;
                stepListData[0].region = [];
                this.setData({ activeSteps: String(index + 1), stepListData, countryValue: {}, regionValue: {} }, () => {
                    this.filterStepsData();
                    this.getCountrySelectData(this.cityValue)
                })
            } else if (String(index) === "3") {
                let regionData = [
                    {
                        label: "请选择镇（街道）"
                    }
                ];
                stepListData[0].region = regionData
                this.setData({ activeSteps: String(index + 1), stepListData, regionValue: {} }, () => {
                    this.filterStepsData();
                    this.getRegionSelectData(this.countryValue)
                })
            }
        },

        // 过滤steps数据
        filterStepsData() {
            let arr = this.stepListData;
            let filterArr = [];
            if (arr && arr.length > 0) {
                if (arr[0].prov && arr[0].prov.length > 0) {
                    filterArr.push(arr[0].prov[0]);
                }
                if (arr[0].city && arr[0].city.length > 0) {
                    filterArr.push(arr[0].city[0]);
                }
                if (arr[0].country && arr[0].country.length > 0) {
                    filterArr.push(arr[0].country[0]);
                }
                if (arr[0].region && arr[0].region.length > 0) {
                    filterArr.push(arr[0].region[0]);
                }
            }
            // console.log(filterArr)
            this.setData({ areaListData: filterArr })
        },

        // 输入省市县街道数据
        exportCitySelectInfo(type) {
            let { provValue, cityValue, countryValue, regionValue } = this;
            let provTitle = provValue && provValue.label ? provValue.label : "";
            let cityTitle = cityValue && cityValue.label ? cityValue.label : "";
            let countryTitle = countryValue && countryValue.label ? countryValue.label : "";
            let regionTitle = regionValue && regionValue.label ? regionValue.label : "";
            let addressDesc = provTitle + "-" + cityTitle + "-" + countryTitle + (regionTitle ? "-" + regionTitle : "")
            if (type === "descripts") {
                return addressDesc
            } else if (type === "ID") {
                let { provValue, cityValue, countryValue, regionValue } = this;
                let provID = provValue && provValue.value ? provValue.value : "";
                let cityID = cityValue && cityValue.value ? cityValue.value : "";
                let countryID = countryValue && countryValue.value ? countryValue.value : "";
                let regionID = regionValue && regionValue.value ? regionValue.value : "";
                return {
                    provID: provID,
                    provDesc: provTitle,
                    cityID: cityID,
                    cityDesc: cityTitle,
                    countryID: countryID,
                    countryDesc: countryTitle,
                    regionID: regionID,
                    regionDesc: regionTitle,
                    addressDesc,
                }
            } else {
                let obj = {};
                obj.provData = provValue;
                obj.cityData = cityValue;
                obj.countryData = countryValue;
                obj.regionData = regionValue;
                obj.addressDesc = addressDesc
                return obj
            }
        },

        handleStopPropagation: function () {
            return;
        }
    }
}
</script>

<style>
/* pages/common/addressSelectionControl/addressSelectionControl.wxss */
.selected_view {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 20rpx 20rpx 0 0;
  background-color: #fff;
}

.selected_top_title_view {
  width: 100%;
  text-align: center;
  height: 100rpx;
  line-height: 100rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.district_item_view {
  padding-top: 14rpx;
  font-size: 32rpx;
  display: flex;
  padding: 0 20rpx;
  /* border-bottom: 1px #66CC99 solid; */
}

/* 左侧的竖线 */
.left_line_view {
  /* display: flex; */
  flex-direction: column;
  height: 80rpx;
  overflow: hidden;
  align-items: center;
  justify-content: center;
  /* background-color: red; */

}

.line_white_view {
  background-color: white;
  width: 2rpx;
  height: 40rpx;
  margin: 0;
  padding: 0;
  margin-left: 9rpx;
  /* flex: 1; */
}

.circle_view {
  /* display: block; */
  background-color: #47B7FB;
  width: 20rpx;
  height: 20rpx;
  border-radius: 10rpx;
  /* flex: 1; */
}

.line_view {
  width: 2rpx;
  height: 30rpx;
  background-color: #47B7FB;
  margin: 0;
  padding: 0;
  margin-left: 9rpx;
  /* flex: 1; */
}

.district_view {
  margin-left: 40rpx;
  /* background-color: yellow; */
  height: 80rpx;
  line-height: 80rpx;
}

/* 选中层级的颜色 */
.selectedView {
  color: #47B7FB;
}

.selected_bottom_view {
  border-top: 1px solid whitesmoke;
  background-color: #fff;
}

.selected_title_view {
  background-color: #fff;
  text-align: left;
  color: #ccc;
  font-size: 28rpx;
  height: 80rpx;
  line-height: 80rpx;
  width: 100%;
  padding: 0 24rpx;
  box-sizing: border-box;
}

.selected_scrollview {
  background-color: #fff;
}

.cell_view {
  padding-left: 20rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
}

/* 地址选中操作 */
.cell_view_active {
  background: whitesmoke;
  color: #47B7FB;
}
</style>