<template>
    <div class="addressCom">
        <div class="btn-list">
            <el-button type="primary" @click="newlyAddress">新增地址</el-button>
        </div>
        <div class="table">
            <el-table border ref="singleTable" :data="tableData" highlight-current-row style="width: 100%"
                @current-change="handleCurrentChange">
                <el-table-column label="选中" width="70" align="center">
                    <template slot-scope="scope">
                        <div class="radio-box" :class="scope.row.receiveId == activeId ? 'active' : ''">
                            <i class="el-icon-check"></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="地址ID" prop="receiveId" align="center">
                </el-table-column>
                <el-table-column label="地址标签" prop="label" align="center">
                </el-table-column>
                <el-table-column label="收货人姓名" prop="receiveName" align="center">
                </el-table-column>
                <el-table-column label="收货人电话号码" prop="receivePhone" align="center">
                </el-table-column>
                <el-table-column label="收货地址" prop="receiveAdress" align="center">
                </el-table-column>
                <el-table-column label="详细地址" prop="address" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="edit(scope.row)">编辑地址</el-button>
                        <el-button type="text" @click="deleteClick(scope.row.receiveId)">删除地址</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </div>
        <div class="select-info">
            <template v-if="Object.keys(addressObj).length > 0">
                <el-descriptions title="选择的地址信息（用于购物车的发货）">
                    <el-descriptions-item label="收货人姓名">{{ addressObj.receiveName }}</el-descriptions-item>
                    <el-descriptions-item label="收货人电话号码">{{ addressObj.receivePhone }}</el-descriptions-item>
                    <el-descriptions-item label="地址标签">
                        <el-tag size="small">{{ addressObj.label }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="是否是默认地址">
                        {{ addressObj.ifDefault == 1?'是':'否' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="收货地址">{{ addressObj.receiveAdress }}{{ addressObj.address }}</el-descriptions-item>
                </el-descriptions>
            </template>
            <template v-else>
                <el-empty :image-size="200" description="暂未选择你的收货地址" :imageSize="100">
                    <!-- <el-button type="primary">去选择收货地址</el-button> -->
                </el-empty>
            </template>
        </div>
        <el-dialog :close-on-click-modal="false" title="地址详情" width="50%" :visible.sync="visible" @close="closeDialog">
            <el-form class="formList" ref="form" :rules="rules" :model="form" label-width="150px">
                <el-form-item label="收货人姓名" prop="receiveName">
                    <el-input v-model="form.receiveName"></el-input>
                </el-form-item>

                <el-form-item label="收货人电话号码" prop="receivePhone">
                    <el-input v-model="form.receivePhone"></el-input>
                </el-form-item>

                <el-form-item label="地址标签" prop="label">
                    <el-input v-model="form.label"></el-input>
                </el-form-item>
                <el-form-item label="收货地址" prop="receiveAdress">
                    <el-cascader :props="props" v-model="form.receiveAdress"></el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input type="textarea" v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="设置默认地址">
                    <el-radio-group v-model="form.ifDefault">
                        <el-radio :label="0">否</el-radio>
                        <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="dialog-list">
                <el-button type="info" plain @click="cancel">取消</el-button>
                <el-button type="primary" @click="preser">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getAddress, searchParentId, addAddress, deleteAddress,editAddress } from '@/api/threeSelection'

let resetForm = {
    "receiveName": "",
    "receivePhone": "",
    "receiveAdress": "",
    "areaId": "",
    "communityId": "",
    "address": "",
    "label": "",
    "ifDefault": 0
}

export default {
    created() {
        this.getList()
    },
    props: {
        addressObj: {
            type: Object,
        },
    },
    data() {
        return {
            name: "dsadkajshdjkashdjkashjd",
            queryData: {
                page: 1,
                pageSize: 10
            },
            tableData: [],
            currentRow: null,
            // 控制弹框
            visible: false,
            form: { ...resetForm },
            props: {
                lazy: true,
                label: "name",
                value: "name",
                lazyLoad(node, resolve) {
                    const { level, data } = node;
                    if (level == 0) {
                        searchParentId({ parentId: 0 }).then(res => {
                            resolve(res.data)
                        })
                    } else {
                        searchParentId({ parentId: data.id }).then(res => {
                            resolve(res.data)
                        })
                    }
                }
            },
            //  表单的正则校验
            rules: {
                receiveName: [{ required: true, message: '收货人姓名不能为空', trigger: 'blur' }],
                receivePhone: [{ pattern: /^1[3456789]\d{9}$/, message: '收货的手机号码必须以1开头的11位手机号', trigger: 'blur' }, { required: true, message: '收货的手机号码不能为空', trigger: 'blur' }],
                label: [{ required: true, message: '地址标签不能为空', trigger: 'blur' }, { min: 1, max: 5, message: '地址标签长度必须在 1 到 5 个字符', trigger: 'blur' }],
                receiveAdress: [{ required: true, message: '收货地址不能为空', trigger: 'blur' }],
                address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
            },
            //  判断是编辑还是新增
            isEdit: 0, // 0表示新增 1表示编辑
            //  列表地址的激活态
            activeId: ''
        }
    },
    methods: {
        //  单选地址
        handleCurrentChange(val) {
            this.activeId = val.receiveId;
            this.$emit('selectAddress', val)
        },
        async getList() {
            let res = await getAddress(this.queryData)
            this.tableData = res.data.list
            res.data.list.forEach(item => {
                if (item.ifDefault == 1) {
                    this.activeId = item?.receiveId
                    let obj = {...item}
                    obj.receiveAdress.join('-')
                    this.$emit('selectAddress', obj)
                }
            })
        },
        //  新增地址
        newlyAddress() {
            this.visible = true
            this.isEdit = 0
        },
        // 保存按钮
        preser() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.preserAddress()
                } else {
                    return false;
                }
            });
        },
        //  删除地址
        async deleteClick(id) {
            this.$confirm('是否将该地址从你的地址列表中删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await deleteAddress({ receiveId: id })
                if (res.code == "") {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }
            })

        },
        // 编辑地址
        async edit(row) {
            this.form = row
            this.isEdit = 1
            this.form.receiveAdress = row.receiveAdress.split('-')
            this.visible = true
        },
        //  添加地址
        async preserAddress() {
            //  走到这里表示通过了验证
            let obj = { ...this.form }
            // 对数据进行处理
            obj.receiveAdress = obj.receiveAdress.join('-')
            let res = null
            if (this.isEdit == 0) {
                res = await addAddress(obj);

            } else if (this.isEdit == 1) {
                res = await editAddress(obj);
            }
            if (res.code == "") {
                this.$message({
                    message: '更新添加地址成功',
                    type: 'success'
                })
                console.log("走到这里来了");
                this.visible = false
                this.getList()
            }

        },
        // 取消按钮
        cancel() {
            this.visible = false
        },
        // 关闭弹框的回调
        closeDialog() {
            this.form = { ...resetForm }
        }
    }
}
</script>

<style lang="scss" scoped>
.addressCom {
    .btn-list {
        margin: 20px 0px;
    }

    .radio-box {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        width: 20px;
        height: 20px;
        margin: 0 auto;
        border: 1px solid #000;
        color: #FFFFFF
    }

    .active {
        background-color: #409eff;
        color: #FFFFFF;
    }

    .formList {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
    }

    ::v-deep .el-form-item {
        width: 50%;
    }

    .dialog-list {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 20px 0 10px;
        gap: 20px;
    }

    ::v-deep .el-cascader {
        width: 100%;
    }

    ::v-deep .el-table__body tr.current-row>td.el-table__cell,
    .el-table__body tr.selection-row>td.el-table__cell {
        background-color: #fffc86;
    }
}

.select-info {
    margin: 30px 0;

    ::v-deep .el-descriptions__body {
        padding: 20px;
        box-sizing: border-box;
    }

    ::v-deep .el-descriptions-item {
        margin-top: 20px;
    }
}
</style>