<template>
    <view>
        <form @submit="onSubmit">
            <view class="weui-cells__group weui-cells__group_form">
                <view class="weui-cells weui-cells_form">
                    <view class="weui-cell bb1">
                        <view class="weui-cell__hd">
                            <label class="weui-label">姓名</label>
                        </view>
                        <view class="weui-cell__bd">
                            <input
                                name="contacts"
                                type="text"
                                :value="address.contacts"
                                class="weui-input tr"
                                placeholder="请输入姓名"
                                placeholder-class="weui-input__placeholder"
                            />
                        </view>
                    </view>
                    <view class="weui-cell bb1">
                        <view class="weui-cell__hd">
                            <label class="weui-label">手机号</label>
                        </view>
                        <view class="weui-cell__bd">
                            <input
                                name="contactsTel"
                                type="number"
                                :value="address.contactsTel"
                                class="weui-input tr"
                                placeholder="请输入手机号"
                                placeholder-class="weui-input__placeholder"
                            />
                        </view>
                    </view>
                    <!-- <view class="weui-cell">
          <view class="weui-cell__hd"><label class="weui-label">地区</label></view>
          <view class="weui-cell__bd">
            <picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange" value="{{multiIndexTemp}}" range="{{multiArrayTemp}}">
              <view class="picker tr">
                <view wx:if="{{multiSelected}}" style="text-align: left;  display: inline-block">{{multiArray[0][multiIndex[0]]}}，{{multiArray[1][multiIndex[1]]}}，{{multiArray[2][multiIndex[2]]}}</view>
                <view wx:else style="text-align: left;display: inline-block;color: #b2b2b2;">请选择地区</view>
              </view>
            </picker>
          </view>
      </view>-->
                    <view class="weui-cell">
                        <view class="weui-cell__hd p0">
                            <label class="weui-label m0">详细地址</label>
                        </view>
                        <view class="weui-cell__bd textarea tr">
                            <textarea
                                name="address"
                                :value="addressStr"
                                class="weui-textarea"
                                placeholder="请输入详细地址"
                                style
                                placeholder-class="weui-input__placeholder"
                                :auto-height="true"
                            ></textarea>
                        </view>
                        <view>
                            <i class="iconfont icon-dingwei pl8" @click="chooseMap" style="padding: 8px 0 8px 8px"></i>
                        </view>
                    </view>

                    <!-- <view class="weui-cell"></view> -->
                </view>
            </view>
            <view class="weui-cell mark mt16">
                <view class="weui-cell__hd">
                    <label class="weui-label" style="width: 60px">标签</label>
                </view>
                <view class="weui-cell__bd tr">
                    <view
                        @tap="selectAddressClassify"
                        data-classify="0"
                        :class="'adTag ' + (addressClassify == 0 && addressClassify !== '' && addressClassify !== null ? 'active' : '')"
                    >
                        家
                    </view>
                    <view @tap="selectAddressClassify" data-classify="1" :class="'adTag ' + (addressClassify == 1 ? 'active' : '')">公司</view>
                    <view @tap="selectAddressClassify" data-classify="2" :class="'adTag ' + (addressClassify == 2 ? 'active' : '')">其它</view>
                </view>
            </view>
            <button formType="submit" :disabled="btnLoading" class="loginOut normalBtn" style="font-weight: 400; margin-top: 70px; margin-bottom: 20px">保存</button>
            <view class="tc f14" hover-class="thover" style="color: #576b95" @tap="delAddress" v-if="recordId">删除该地址</view>

            <!-- 2{{recordId}}3 -->
        </form>
    </view>
</template>

<script>
const app = getApp();
import { isEmptyCheck } from '../../../utils/commonUtil';
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
// pages/addAddress/index.js
export default {
    data() {
        return {
            multiSelected: false,
            multiIndex: [0, 0, 0],
            multiIndexTemp: [0, 0, 0],
            // multiArray: [['无脊柱动物', '脊柱动物'], ['扁性动物', '线形动物', '环节动物', '软体动物', '节肢动物'], ['猪肉绦虫', '吸血虫']],
            multiArray: [[], [], []],
            multiArrayTemp: [[], [], []],
            multiArrayRecord: [[], [], []],
            title: '添加地址',
            btnLoading: false,
            address: {
                contacts: '',
                contactsTel: ''
            },
            addressClassify: '',
            addressStr: '',
            recordId: '',
            locationObj: {
                provinceName: '',
                cityName: '',
                districtName: ''
            }
            // provinceId: '',
            // cityId: '',
            // districtId: '',
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        console.log(options);
        if (!isEmptyCheck(options.id)) {
            this.recordId = options.id;
            this.title = '修改地址';
            this.setData({
                recordId: options.id
            });
            this.getDetail();
        } else {
            this.getProvinceByPid();
        }
        uni.setNavigationBarTitle({
            title: this.title
        });
        qqmapsdk = new QQMapWX({
            key: '5PTBZ-YI7C6-MZGS3-ES7QN-4T5O2-EJFVR'
        });
        console.log(123);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    methods: {
        delAddress: function (e) {
            var that = this;
            // var record = e.currentTarget.dataset.record;
            // console.log(record);

            uni.showModal({
                title: '提示',
                content: `确定要删除该地址吗？`,
                cancelColor: '#666666',
                confirmColor: '#ff4400',
                success(res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                        uni.request({
                            url: app.globalData.ip + '/user/address/deleteUserAddress',
                            method: 'POST',
                            header: app.globalData.headers,
                            data: {
                                id: that.recordId
                            },
                            success: function (res) {
                                console.log(res);
                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    uni.navigateBack({
                                        delta: -1
                                    });
                                }, 2000);
                            }
                        });
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },

        getProvinceByPid: function () {
            var that = this;
            uni.request({
                url: app.globalData.ip + '/city/getProvince',
                data: {},
                header: app.globalData.headers,
                method: 'POST',
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        that.multiArrayRecord[0] = [
                            {
                                id: -1,
                                name: '请选择'
                            }
                        ].concat(res.data.data);
                        var nameArray = ['请选择'];
                        res.data.data.forEach((item, index) => {
                            nameArray.push(item.name);
                        });
                        that.multiArrayTemp[0] = nameArray;
                        that.setData({
                            multiArrayTemp: that.multiArrayTemp
                        });

                        //如果有省市回显处理
                        if (
                            app.globalData.isNotEmptyCheck(that.address.provinceId) &&
                            app.globalData.isNotEmptyCheck(that.address.cityId) &&
                            app.globalData.isNotEmptyCheck(that.address.districtId)
                        ) {
                            that.multiArrayRecord[0].forEach((item, index) => {
                                if (item.id == that.address.provinceId) {
                                    that.multiIndex[0] = index;
                                }
                            });
                            that.setData({
                                multiArray: that.multiArrayTemp,
                                multiIndex: that.multiIndex,
                                multiIndexTemp: that.multiIndex
                            });
                            that.getCityByPid2(1, that.address.provinceId);
                        }
                    } else {
                        app.globalData.showTips(that, res.data.msg);
                    }
                }
            });
        },

        bindMultiPickerChange: function (e) {
            console.log('picker发送选择改变，携带值为', e.detail.value);
            var that = this;
            var multiSelected = false;
            if (e.detail.value[0] > 0 && e.detail.value[1] > 0 && e.detail.value[2] > 0) {
                multiSelected = true;
            }
            this.setData({
                multiIndex: e.detail.value,
                multiSelected: multiSelected,
                multiArray: that.multiArrayTemp
            });
        },

        bindMultiPickerColumnChange: function (e) {
            console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
            var that = this;
            if (e.detail.column == 0) {
                that.multiIndexTemp[0] = e.detail.value;
                that.multiIndexTemp[1] = 0;
                that.multiIndexTemp[2] = 0;
                that.multiArrayTemp[1] = [];
                that.multiArrayTemp[2] = [];
                this.setData({
                    multiIndexTemp: that.multiIndexTemp,
                    multiArrayTemp: that.multiArrayTemp
                });
            }
            if (e.detail.column < 2) {
                this.getCityByPid(e.detail.column, e.detail.value);
            }
        },

        getCityByPid: function (column, value) {
            var that = this;
            // var pid = that.data.userDetails.bankProvinceCode;
            console.log(that.multiArrayRecord[column][value]);
            var pid = that.multiArrayRecord[column][value].id;
            uni.request({
                url: app.globalData.ip + '/city/getCityByPid',
                data: {
                    pid: pid
                },
                header: app.globalData.headers,
                method: 'POST',
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        that.multiArrayRecord[column + 1] = [
                            {
                                id: -1,
                                name: '请选择'
                            }
                        ].concat(res.data.data);
                        var nameArray = ['请选择'];
                        res.data.data.forEach((item, index) => {
                            nameArray.push(item.name);
                        });
                        that.multiArrayTemp[column + 1] = nameArray;
                        that.setData({
                            multiArrayTemp: that.multiArrayTemp
                        });
                    } else {
                        app.globalData.showTips(that, res.data.msg);
                    }
                }
            });
        },

        getCityByPid2: function (column, pid) {
            var that = this;
            uni.request({
                url: app.globalData.ip + '/city/getCityByPid',
                data: {
                    pid: pid
                },
                header: app.globalData.headers,
                method: 'POST',
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        that.multiArrayRecord[column] = [
                            {
                                id: -1,
                                name: '请选择'
                            }
                        ].concat(res.data.data);
                        var nameArray = ['请选择'];
                        res.data.data.forEach((item, index) => {
                            nameArray.push(item.name);
                        });
                        that.multiArrayTemp[column] = nameArray;
                        that.multiArrayRecord[column].forEach((item, index) => {
                            if (column == 1 && item.id == that.address.cityId) {
                                that.multiIndex[column] = index;
                            } else if (column == 2 && item.id == that.address.districtId) {
                                that.multiIndex[column] = index;
                            }
                        });
                        that.setData({
                            multiArray: that.multiArrayTemp,
                            multiArrayTemp: that.multiArrayTemp,
                            multiIndex: that.multiIndex,
                            multiIndexTemp: that.multiIndex
                        });
                        if (column == 1) {
                            that.getCityByPid2(2, that.address.cityId);
                        }
                    } else {
                        app.globalData.showTips(that, res.data.msg);
                    }
                }
            });
        },

        selectAddressClassify: function (e) {
            var that = this;
            var classify = e.currentTarget.dataset.classify;
            console.log(classify);
            that.setData({
                addressClassify: classify
            });
        },

        getDetail() {
            var that = this;
            uni.request({
                url: app.globalData.ip + '/user/address/getUserAddressDetail?id=' + that.recordId,
                method: 'GET',
                header: app.globalData.headers,
                data: {},
                success: function (res) {
                    console.log(res);
                    if (app.globalData.isNotEmptyCheck(res.data.data)) {
                        that.setData({
                            address: res.data.data,
                            addressClassify: res.data.data.classify,
                            addressStr: res.data.data.address
                        });
                        if (
                            app.globalData.isNotEmptyCheck(res.data.data.provinceId) &&
                            app.globalData.isNotEmptyCheck(res.data.data.cityId) &&
                            app.globalData.isNotEmptyCheck(res.data.data.districtId)
                        ) {
                            that.setData({
                                multiSelected: true
                            });
                        }
                        that.getProvinceByPid();
                    }
                }
            });
        },

        onSubmit(e) {
            console.log(e);
            var that = this;
            that.setData({
                btnLoading: true
            });
            if (app.globalData.isEmptyCheck(e.detail.value.contacts)) {
                uni.showToast({
                    icon: 'none',
                    title: '请输入姓名',
                    duration: 3000
                });
                that.setData({
                    btnLoading: false
                });
                return;
            }
            var myreg = /^[1][3456789][0-9]{9}$/;
            if (!myreg.test(e.detail.value.contactsTel) || e.detail.value.contactsTel == '') {
                uni.showToast({
                    icon: 'none',
                    title: '请输入正确手机号',
                    duration: 3000
                });
                that.setData({
                    btnLoading: false
                });
                return;
            }
            // if (that.data.multiIndex[0] == 0 || that.data.multiIndex[1] == 0 || that.data.multiIndex[2] == 0) {
            // 	wx.showToast({
            // 		icon: "none",
            // 		title: "请选择详细地区",
            // 		duration: 3000,
            // 	});

            // 	that.setData({
            // 		btnLoading: false,
            // 	});
            // 	return;
            // }

            if (!e.detail.value.address) {
                uni.showToast({
                    icon: 'none',
                    title: '请输入详细地址',
                    duration: 3000
                });
                that.setData({
                    btnLoading: false
                });
                return;
            }
            // if (app.isEmptyCheck(that.data.addressClassify)) {
            // 	wx.showToast({
            // 		icon: "none",
            // 		title: "请选择标签",
            // 		duration: 3000,
            // 	});

            // 	that.setData({
            // 		btnLoading: false,
            // 	});
            // 	return;
            // }

            var formData = e.detail.value;
            formData['id'] = that.recordId;
            formData['classify'] = that.addressClassify;
            if (that.locationObj.provinceName) {
                // formData["provinceId"] = that.data.multiArrayRecord[0][that.data.multiIndex[0]].id;
                // formData["cityId"] = that.data.multiArrayRecord[1][that.data.multiIndex[1]].id;
                // formData["districtId"] = that.data.multiArrayRecord[2][that.data.multiIndex[2]].id;
                formData['provinceName'] = that.locationObj.provinceName;
                formData['cityName'] = that.locationObj.cityName;
                formData['districtName'] = that.locationObj.districtName;
            } else {
                uni.showToast({
                    icon: 'none',
                    title: '请选择地区',
                    duration: 3000
                });
            }
            console.log(formData);
            that.setData({
                btnLoading: false
            });
            uni.request({
                url: app.globalData.ip + '/user/address/addOrUpdateUserAddress',
                method: 'POST',
                header: app.globalData.headers,
                data: formData,
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        uni.navigateBack({
                            delta: 1
                        });
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: res.data.msg,
                            duration: 2000
                        });
                        that.setData({
                            btnLoading: false
                        });
                    }
                }
            });
        },

        chooseMap: function () {
            var that = this;
            console.log('1111111');
            // wx.chooseLocation({
            uni.chooseLocation({
                success: function (res) {
                    console.log('res', res);
                    that.addressStr = res.name;
                    qqmapsdk.reverseGeocoder({
                        location: `${res.latitude},${res.longitude}`,
                        success: function (res) {
                            console.log(res.result);
                            let address = res.result.address_component;
                            that.addressStr = `${address.province} ${address.city} ${address.district} ` + that.addressStr;
                            that.setData({
                                addressStr: that.addressStr,
                                locationObj: {
                                    provinceName: res.result.address_component.province,
                                    cityName: res.result.address_component.city,
                                    districtName: res.result.address_component.district
                                }
                            });
                        },
                        fail: function (res) {
                            console.log(res);
                        }
                    });
                },
                fail: function (e) {
                    console.log(e);
                }
            });
        },

        goAddAddress: function () {
            uni.navigateTo({
                url: '/pages/addressBook/index'
            });
        },

        /**
         * 用户点击右上角分享
         */
        onShareAppMessage1: function () {}
    }
};
</script>
<style>
@import './index.css';
</style>
