<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="600px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formDataInfo" label-width="90px" :rules="formRules">
                <el-form-item label="门店logo" prop="image">
                    <material-picker v-model="formDataInfo.image" :limit="1" />
                </el-form-item>
                <el-form-item label="门店名称" prop="name">
                    <el-input v-model="formDataInfo.name" clearable placeholder="请输入门店名称" :readonly="false" />
                </el-form-item>
                <el-form-item label="简介" prop="introduction">
                    <el-input v-model="formDataInfo.introduction" clearable placeholder="请输入简介" type="textarea"
                        :rows="3" :readonly="false" />
                </el-form-item>
                <el-form-item label="负责人" prop="staff_name">
                    <el-input v-model="formDataInfo.staff_name" clearable placeholder="请输入负责人姓名" :readonly="false" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="formDataInfo.phone" clearable placeholder="请输入手机号码/管理员账号"
                        :readonly="mode == 'edit'" />
                    <div class="text-sm text-orange-400">输入的手机号将作为管理员账户登录</div>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="mode=='add'">
                    <el-input v-model="formDataInfo.password" clearable placeholder="请输入登录密码" :readonly="false" />
                </el-form-item>
                <el-form-item label="登录密码" v-else>
                    <el-input v-model="formDataInfo.password" clearable placeholder="请输入登录密码" :readonly="false" />
                    <div class="text-sm text-orange-400">不修改请留空</div>
                </el-form-item>
                <el-form-item label="营业状态" prop="is_show">
                    <el-switch v-model="formDataInfo.is_show" :active-value="1" :inactive-value="0" active-text="营业"
                        inactive-text="打烊" inline-prompt />
                </el-form-item>
                <el-form-item label="营业时间" prop="startEndTime">
                    <el-time-picker v-model="formDataInfo.startEndTime"
                        :default-value="[new Date(2024, 6, 1, 8, 0), new Date(2024, 6, 1, 22, 0)]" is-range
                        start-placeholder="开始时间" end-placeholder="结束时间" />
                </el-form-item>
                <el-form-item label="门店地址" prop="selectedValues">
                    <el-cascader v-model="formDataInfo.selectedValues" :options="options" :props="props"
                        :load="loadOptions" class="w-full" />
                </el-form-item>
                <el-form-item label="详细地址" prop="detailed_address">
                    <el-input v-model="formDataInfo.detailed_address" clearable placeholder="请输入详细地址"
                        :readonly="false" />
                </el-form-item>
                <el-form-item label="到店自提" prop="is_store">
                    <el-switch v-model="formDataInfo.is_store" :active-value="1" :inactive-value="0" active-text="开启"
                        inactive-text="关闭" inline-prompt disabled />
                </el-form-item>
                <el-form-item label="同城配送" prop="is_send">
                    <el-switch v-model="formDataInfo.is_send" :active-value="1" :inactive-value="0" active-text="开启"
                        inactive-text="关闭" inline-prompt />
                </el-form-item>
                <el-form-item label="具体坐标" prop="coord">
                    <div class="flex w-full">
                        <el-input v-model="formDataInfo.coord" clearable placeholder="请输入具体坐标, 例如116.403872, 39.904989"
                            class="flex-1 mr-4" :readonly="false" />
                        <a href="https://lbs.qq.com/getPoint/" target="_blank"><el-button
                                type="primary">获取坐标</el-button></a>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="systemStoreEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSystemStoreAdd, apiSystemStoreEdit, apiSystemStoreDetail } from '@/api/system_store'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { apiProvince, apiCity, apiArea, apiStreet } from "@/api/public"
import { ElMessage } from 'element-plus'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑门店列表' : '新增门店列表'
})

// 表单数据
const formData = reactive({
    id: '',
    name: '',
    introduction: '',
    phone: '',
    detailed_address: '',
    image: '',
    is_show: 1,
    password: "",
    staff_name: "",
    is_store: 1,
    is_send: 0
})

const formDataInfo = reactive({
    id: '',
    name: '',
    introduction: '',
    phone: '',
    detailed_address: '',
    image: '',
    is_show: 1,
    password: "",
    staff_name: "",
    is_store: 1,
    is_send: 0,
    coord: '',
    startEndTime: [],
    selectedValues: []
})


// 表单验证
const formRules = reactive<any>({
    name: [{
        required: true,
        message: '请输入门店名称',
        trigger: ['blur']
    }],
    phone: [{
        required: true,
        message: '请输入手机号码',
        trigger: ['blur']
    }],
    staff_name: [{
        required: true,
        message: '请输入负责人姓名',
        trigger: ['blur']
    }],
    password: [{
        required: true,
        message: '请输入登录密码',
        trigger: ['blur']
    }],
    detailed_address: [{
        required: true,
        message: '请输入详细地址',
        trigger: ['blur']
    }],
    image: [{
        required: true,
        message: '请输入门店logo',
        trigger: ['blur', 'change']
    }],
    coord: [{
        required: true,
        message: '请输入坐标',
        trigger: ['blur']
    }],
    startEndTime: [{
        required: true,
        message: '请选择营业时间',
        trigger: ['blur', 'change']
    }],
    selectedValues: [{
        required: true,
        message: '请选择门店地址',
        trigger: ['blur', 'change']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            // formData[key] = data[key]
            formDataInfo[key] = data[key]
        }
    }

    if (data.province && data.city && data.area && data.street) {
        formDataInfo.selectedValues = [data.province + '', data.city + '', data.area + '', data.street + ''];
    } else formDataInfo.selectedValues = [];
    if (data.latitude && data.longitude) {
        formDataInfo.coord = data.latitude + ',' + data.longitude;
    } else formDataInfo.coord = '';
    if (data.day_start && data.day_end) {
        formDataInfo.startEndTime = [new Date(2024, 6, 1, data.day_start.split(':')[0], data.day_start.split(':')[1]), new Date(2024, 6, 1, data.day_end.split(':')[0], data.day_end.split(':')[1])];
    } else formDataInfo.startEndTime = [];
}


// 获取详情
const getDetail = async (row: Record<string, any>) => {
    const data = await apiSystemStoreDetail({
        id: row.id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    Object.keys(formData).forEach((key: string) => {
        if (formDataInfo[key]!==''&&formDataInfo[key]!==null&&formDataInfo[key]!==undefined) formData[key] = formDataInfo[key];
    })
    const data = { ...formData };
    if(mode.value=='edit' && !data.password) data.password = '';
    const test = /^[+-]?\d*(\.\d+)?$/;
    let latlng = formDataInfo.coord.split(',');
    if (latlng.length < 2 || !test.test(latlng[0]) || !test.test(latlng[1])) return ElMessage.error('请输入正确的坐标');
    data.latitude = latlng[0];
    data.longitude = latlng[1];
    data.day_start = timeFormat(formDataInfo.startEndTime[0], 'hh:MM')
    data.day_end = timeFormat(formDataInfo.startEndTime[1], 'hh:MM')
    data.province_code = formDataInfo.selectedValues[0]
    data.city_code = formDataInfo.selectedValues[1]
    data.area_code = formDataInfo.selectedValues[2]
    data.street_code = formDataInfo.selectedValues[3]
    mode.value == 'edit'
        ? await apiSystemStoreEdit(data)
        : await apiSystemStoreAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}


const options = ref([]);

// 异步加载数据的方法
const loadOptions = async (node: any, resolve: any) => {
    const level = node.level;
    let response;
    if (level !== 0 && !node.data.code) return resolve([]);
    if (level === 0) {
        response = await apiProvince();
        response = response.map((item: any) => {
            return {
                code: item.province_code,
                name: item.province_name
            }
        })
    } else if (level === 1) {
        response = await apiCity({
            code: node.data.code
        });
        response = response.map((item: any) => {
            return {
                code: item.city_code,
                name: item.city_name
            }
        })
    } else if (level === 2) {
        response = await apiArea({
            code: node.data.code
        });
        response = response.map((item: any) => {
            return {
                code: item.area_code,
                name: item.area_name
            }
        })
    }
    else {
        response = await apiStreet({
            code: node.data.code
        });
        response = response.map((item: any) => {
            return {
                code: item.street_code,
                name: item.street_name,
                leaf: true
            }
        })
    }

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


// 初始化第一级数据
onMounted(async () => {
    const response = await apiProvince();
    options.value = response.map((item: any) => {
        return {
            code: item.province_code,
            name: item.province_name
        }
    });
});


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
