<template>
    <view class="address-create">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <view class="form-control">
            <label for="shouHuoRen">收货人姓名</label>
            <input
                class="input"
                type="text"
                id="shouHuoRen"
                placeholder="请输入收货人姓名"
                placeholder-class="placeholder"
                v-model="formData.shouHuoRen"
                maxlength="20"
            />
        </view>
        <tui-divider :height="dividerHeight"></tui-divider>
        <view class="form-control">
            <label for="mobile">联系方式</label>
            <input
                class="input"
                type="text"
                id="mobile"
                v-model="formData.mobile"
                placeholder="请输入联系方式"
                placeholder-class="placeholder"
                maxlength="20"
            />
        </view>
        <tui-divider :height="dividerHeight"></tui-divider>
        <view class="form-control">
            <label for="name">收货地址</label>
            <uni-data-picker
                v-model="formData.townId"
                :localdata="cityData"
                popup-title="请选地区"
                :map="{ text: 'name', value: 'id' }"
                class="input picker"
            ></uni-data-picker>
        </view>
        <tui-divider :height="dividerHeight"></tui-divider>
        <view class="form-control">
            <textarea
                class="input"
                v-model="formData.address"
                placeholder="详细地址：如道路、门牌号、小区、楼房号、单元室等"
                placeholder-class="placeholder"
                maxlength="100"
            />
        </view>
        <tui-divider :height="dividerHeight"></tui-divider>
        <!-- 默认地址 -->
        <view class="set-default">
            <text>设为默认地址</text>
            <switch :checked="isDefault" color="#f83c6c" class="switch" @change="switchChange" />
        </view>
        <view class="confirm">
            <tui-button type="base" :size="28" width="650rpx" height="88rpx" shape="circle" @click="submit">
                保存
            </tui-button>
        </view>
    </view>
</template>

<script>
import { fetchCityList } from '@/services/api/common.js'
import { saveAddress } from '@/services/api/user.js'
import { validation } from '@/components/common/tui-validation/tui-validation.min.js'
import { objAssign } from '@/common/utils.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            type: 'add',
            isRequest: true,
            dividerHeight: 40,
            isDefault: false,
            cityData: [],
            pickerValue: '',
            // 表单数据
            formData: {
                addressId: '', // 当前地址id
                userId: '', // 用户id
                shouHuoRen: '', //收货人
                townId: '', //区ID
                address: '', //地址
                mobile: '', //手机
                defaultFlag: 0 //是否默认收货地址(0 不是默认,1 默认)
            },
            // 表单验证规则
            rules: [
                { name: 'userId', rule: ['required'], msg: ['用户ID不能为空'] },
                { name: 'shouHuoRen', rule: ['required'], msg: ['收货人姓名不能为空'] },
                { name: 'townId', rule: ['required'], msg: ['收货地址不能为空'] },
                { name: 'address', rule: ['required'], msg: ['详细地址不能为空'] },
                { name: 'mobile', rule: ['required'], msg: ['联系方式不能为空'] }
            ]
        }
    },
    computed: {
        ...mapGetters(['userId'])
    },
    onLoad(options) {
        this.type = options.type
        this.formData.userId = this.userId
        this.fetchCityList()

        if (this.type === 'edit') {
            this.initFormData()
        }
    },
    beforeDestroy() {
        uni.removeStorageSync('eidtAddress')
    },
    methods: {
        // 初始化表单数据
        initFormData() {
            const address = uni.getStorageSync('eidtAddress')
            objAssign(this.formData, address)
            this.formData.townId = address.townId + 'T'
            this.formData.defaultFlag = parseInt(address.defaultFlag)
            this.isDefault = Boolean(this.formData.defaultFlag)
        },
        // 默认状态修改
        switchChange(e) {
            this.isDefault = e.target.value
            this.formData.defaultFlag = Number(this.isDefault)
        },
        // 提交保存
        async submit() {
            console.log(this.formData)
            const valide = validation(this.formData, this.rules)
            if (valide) {
                return this.$toast.error(valide)
            }
            try {
                const params = { ...this.formData, townId: parseInt(this.formData.townId) }
                const res = await saveAddress(params)
                this.$toast.success('已保存该收货地址')
                if (this.type === 'choose') {
                    this.$router.addRefreshType('chooseAddress')
                    uni.setStorageSync('CHOOSE_ADDRESS', res.data)
                    setTimeout(() => this.$router.navigateBack(), 1000)
                } else {
                    this.$router.addRefreshType('createAddressBack')
                    setTimeout(() => this.$router.navigateBack(), 1000)
                }
            } catch (e) {
                console.log(e)
            }
        },
        // 获取城市列表
        async fetchCityList() {
            try {
                const res = await fetchCityList()
                this.cityData = this.formatCityList(res.data)
                console.log(this.cityData)
            } catch (e) {
                console.log(e)
            } finally {
                this.isRequest = false
            }
        },
        // 处理城市列表k-v
        formatCityList(list = []) {
            const result = []
            // 判断是否非空数组
            function notEmptyArr(arr) {
                return arr && arr instanceof Array && arr.length > 0
            }
            list.forEach(item => {
                const obj = {}
                // obj.id = item.townId || item.cityId || item.provinceId

                if (item.townId) {
                    obj.id = item.townId + 'T'
                } else if (item.cityId) {
                    obj.id = item.cityId + 'C'
                } else {
                    obj.id = item.provinceId + 'P'
                }

                obj.name = item.name

                let children = []

                if (notEmptyArr(item.cityList)) {
                    children = item.cityList
                }

                if (notEmptyArr(item.townList)) {
                    children = item.townList
                }

                if (children.length > 0) {
                    obj.children = this.formatCityList(children)
                }

                result.push(obj)
            })

            return result
        }
    }
}
</script>

<style scoped>
.form-control >>> .input-value-border {
    border: 0;
}

.form-control >>> .selected-item-active,
.form-control >>> .check {
    border-color: #f83c6c;
}

.picker >>> .input-value,
.picker >>> .selected-list {
    padding: 0 !important;
}
</style>

<style lang="scss" scoped>
.address-create {
    height: 100vh;
    padding: 0 24rpx;
    padding-top: 24rpx;
    background-color: #fff;
    box-sizing: border-box;
    color: #333;

    .form-control {
        @extend .cm-flex-between;
        // padding: 24rpx 0;
        font-size: 28rpx;

        label {
            width: 160rpx;
        }

        .input {
            flex: 1;
        }

        .picker {
            max-width: 564rpx;
        }
    }

    .set-default {
        @extend .cm-flex-between;
        justify-content: flex-start;
        text {
            font-size: 28rpx;
        }
        .switch {
            transform: scale(0.6);
        }
    }

    .confirm {
        @extend .cm-flex-center;
        margin-top: 80rpx;
    }
}
</style>
