<script setup>
import { ref, onMounted, onUnmounted, reactive } from "vue";
import { apiProvince, apiCity, apiArea, apiStreet, apiVillage, apiBrigade } from '@/api/public'
import { userShipApi, userAddApi, userArchivesSmsApi } from "@/api/user"
import { ElMessage } from "element-plus";
import authCode from "@/components/authCode.vue";
import { useUserStore } from "@/store/user";

const userStore = useUserStore();
const formDataRef = ref(null);
const formDataInfo = reactive({
    mobile: '',
    code: '',
    real_name: '',
    user_ship: 0,
    selectedValues: [],
})

const formDataRules = reactive({
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    real_name: [
        { required: true, message: '请输入用户姓名', trigger: 'blur' }
    ],
    user_ship: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
    ],
    selectedValues: [
        { required: true, message: '请选择用户地址', trigger: 'change' }
    ]
})

const options = ref([]);
// 异步加载数据的方法
const loadOptions = async (node, resolve) => {
    const level = node.level;
    let response;
    if (level !== 0 && !node.data.code) return resolve([]);
    // if (level === 0) {
    //     response = await apiProvince();
    //     response = response.data.map((item) => {
    //         return {
    //             code: item.province_code,
    //             name: item.province_name
    //         }
    //     })
    // } else 
    if (level === 0) {
        response = await apiCity({
            province_code: 510000 // 四川省
        });
        response = response.data.map((item) => {
            return {
                code: item.city_code,
                name: item.city_name
            }
        })
    } else if (level === 1) {
        response = await apiArea({
            city_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.area_code,
                name: item.area_name
            }
        })
    }
    else if (level === 2) {
        response = await apiStreet({
            area_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.street_code,
                name: item.street_name,
            }
        })
    }
    else if (level === 3) {
        response = await apiVillage({
            street_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.village_code,
                name: item.village_name,
            }
        })
    }
    else if (level === 4) {
        response = await apiBrigade({
            village_code: node.data.code
        });
        response = response.data.map((item) => {
            return {
                code: item.id,
                name: item.brigade_name,
                leaf: true
            }
        })
    }

    resolve(response);
};
const props = {
    value: 'code',
    label: 'name',
    children: 'children',
    multiple: false,
    lazy: true,
    lazyLoad: loadOptions
};

const userShip = ref([])
const getUserShip = () => {
    // userShipApi({
    //     type_id: 4
    // }).then(res => {
    //     userShip.value = res.data.lists?.filter((item) => {
    //         return item.id == 0 || item.id == 4
    //     });
    // })
}
getUserShip()

const emit = defineEmits(['close'])
const addUser = () => {
    formDataRef.value.validate(async (valid) => {
        if (valid) {
            let forms = {};
            forms.mobile = formDataInfo.mobile;
            forms.code = formDataInfo.code;
            forms.user_ship = formDataInfo.user_ship;
            forms.real_name = formDataInfo.real_name;
            forms.province = "510000";
            forms.city = formDataInfo.selectedValues[0]
            forms.area = formDataInfo.selectedValues[1]
            forms.street = formDataInfo.selectedValues[2]
            forms.village = formDataInfo.selectedValues[3]
            forms.brigade = formDataInfo.selectedValues[4]
            forms.store_id = userStore.userInfo.store_id;
            userAddApi(forms).then(res=>{
                formDataInfo.mobile = '';
                formDataInfo.code = '';
                formDataInfo.user_ship = 0;
                formDataInfo.real_name = '';
                formDataInfo.selectedValues = [];
                formDataRef.value.resetFields();
                emit('close')
            })
        }
    });

}

const authCodeRef = ref(null)
const getSms = ()=>{
    formDataRef.value.validateField('mobile',(valid)=>{
        if(valid){
            userArchivesSmsApi({
                mobile:formDataInfo.mobile
            }).then(res=>{
                ElMessage.success('发送成功')
                authCodeRef.value.startCountDown();
            }).catch(err=>{
                ElMessage.error('发送失败')
            })
        }
    })
    
}

defineExpose({
    addUser
})

</script>

<template>
    <div class="add-user">
        <el-form :model="formDataInfo" :rules="formDataRules" ref="formDataRef" label-width="80px">
            <el-form-item label="用户电话" prop="mobile">
                <el-input v-model="formDataInfo.mobile" placeholder="请输入用户电话" />
            </el-form-item>
            <el-form-item label="验证码" prop="code">
                <el-input v-model="formDataInfo.code" placeholder="请输入验证码"  style="flex: 1;"/>
                <!-- <el-button type="primary" style="margin-left: 1rem;" @click="getSms">获取验证码</el-button> -->
                <authCode ref="authCodeRef" style="margin-left: 1rem;" @sendCode="getSms" :start="false"></authCode>
            </el-form-item>
            <el-form-item label="用户姓名" prop="real_name">
                <el-input v-model="formDataInfo.real_name" placeholder="请输入用户姓名" />
            </el-form-item>
            <!-- <el-form-item label="用户类型" prop="user_ship">
                <el-select v-model="formDataInfo.user_ship" placeholder="请选择用户类型" style="width: 100%;">
                    <el-option v-for="item in userShip" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="用户地址" prop="selectedValues">
                <el-cascader style="width: 100%;" v-model="formDataInfo.selectedValues" :options="options"
                    :props="props" :load="loadOptions" class="w-full" />
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped lang="scss"></style>
