<template>
    <a-modal 
        :width="800" 
        :open="modal.open" 
        :title="modal.title" 
        :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" 
        :cancel-text="cancelText" 
        :ok-text="okText" 
        @ok="handleOk" 
        @cancel="handleCancel"
    >
        <a-form layout="vertical" ref="formRef" :model="formData" :rules="formRules">
            <a-card class="mb-4">
                <a-row :gutter="16">
                    <!-- 基本信息区域 -->
                    <a-col :span="12">
                        <a-form-item :label="'站点名称'" name="name" :required="true">
                            <a-input v-model:value="formData.name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'所在节点'" name="nodeType" :required="true">
                            <a-select v-model:value="formData.nodeType" @change="handleChange">
                                <a-select-option value="jack">已结单</a-select-option>
                                <a-select-option value="lucy">已作废</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'机构代码'" name="code" :required="true">
                            <a-input v-model:value="formData.code"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'站点类型'" name="type" :required="true">
                            <a-select v-model:value="formData.type" @change="handleChange">
                                <a-select-option value="type1">社区服务中心</a-select-option>
                                <a-select-option value="type2">养老服务站</a-select-option>
                                <a-select-option value="type3">综合服务中心</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'负责人姓名'" name="manager" :required="true">
                           <a-input v-model:value="formData.manager"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'联系电话'" name="phone" :required="true">
                           <a-input v-model:value="formData.phone" placeholder="请输入联系电话"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'星级等级'" name="starLevel">
                            <a-select v-model:value="formData.starLevel">
                                <a-select-option value="1">一星</a-select-option>
                                <a-select-option value="2">二星</a-select-option>
                                <a-select-option value="3">三星</a-select-option>
                                <a-select-option value="4">四星</a-select-option>
                                <a-select-option value="5">五星</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'人员编制（个）'" name="staffCount">
                            <a-input-number v-model:value="formData.staffCount" min="0" style="width: 100%"></a-input-number>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>

            <!-- 地址信息区域 -->
            <a-card class="mb-4" title="地址信息">
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item :label="'服务中心地址'" name="address">
                            <a-cascader
                                v-model:value="formData.address"
                                :options="addressOptions"
                                placeholder="请选择省/市/区"
                                style="width: 100%"
                            ></a-cascader>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'详细地址'" name="detailAddress">
                            <a-input v-model:value="formData.detailAddress" placeholder="请输入详细地址"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'地图定位地址'" name="location">
                            <a-row :gutter="8">
                                <a-col :span="18">
                                    <a-input 
                                        v-model:value="formData.location" 
                                        placeholder="请选择地图位置" 
                                        readonly
                                    ></a-input>
                                </a-col>
                                <a-col :span="6">
                                    <a-button type="primary" block @click="openMapSelector">选择地图位置</a-button>
                                </a-col>
                            </a-row>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>

            <!-- 站点信息区域 -->
            <a-card class="mb-4" title="站点信息">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item :label="'建成时间'" name="buildTime">
                            <a-date-picker 
                                v-model:value="formData.buildTime" 
                                format="YYYY-MM-DD" 
                                placeholder="请选择建成时间"
                            ></a-date-picker>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'建筑面积（平方米）'" name="area">
                            <a-input-number 
                                v-model:value="formData.area" 
                                min="0" 
                                style="width: 100%" 
                                placeholder="请输入建筑面积"
                            ></a-input-number>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="'服务介绍'" name="description">
                            <a-textarea 
                                v-model:value="formData.description" 
                                rows="4" 
                                placeholder="请输入服务介绍"
                            ></a-textarea>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>

            <!-- 服务信息区域 -->
            <a-card class="mb-4" title="服务信息">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item :label="'开始营业时间'" name="openTime">
                            <a-time-picker 
                                v-model:value="formData.openTime" 
                                format="HH:mm" 
                                placeholder="请选择开始营业时间"
                            ></a-time-picker>
                            <a-time-picker 
                                v-model:value="formData.closeTime" 
                                format="HH:mm" 
                                placeholder="请选择结束营业时间"
                            ></a-time-picker>
                        </a-form-item>
                    </a-col>
                    
                    <a-col :span="12">
                        <a-form-item :label="'营业状态'" name="businessStatus">
                            <a-select v-model:value="formData.businessStatus">
                                <a-select-option value="open">营业中</a-select-option>
                                <a-select-option value="closed">已关闭</a-select-option>
                                <a-select-option value="suspended">暂停营业</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    
                    <a-col :span="24">
                        <a-form-item name="services">
                            <template #label>
                                <span>
                                    提供服务
                                    <a-tooltip>
                                        <template #title>
                                            勾选以下服务类型在小程序可见
                                        </template>
                                        <question-circle-outlined class="info-icon" />
                                    </a-tooltip>
                                </span>
                            </template>
                            <div class="service-tags">
                                <a-tag 
                                    v-for="service in allServices" 
                                    :key="service.value"
                                    :checked="formData.services?.includes(service.value)"
                                    @click="handleServiceClick(service.value)"
                                    :class="{'ant-tag-checkable-checked': formData.services?.includes(service.value)}"
                                    class="service-tag"
                                >
                                    {{ service.label }}
                                </a-tag>
                            </div>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item :label="'是否有厨房'" name="hasKitchen">
                            <a-select v-model:value="formData.hasKitchen">
                                <a-select-option value="yes">是</a-select-option>
                                <a-select-option value="no">否</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'提供餐饮'" name="provideMeal">
                            <a-select v-model:value="formData.provideMeal">
                                <a-select-option value="yes">是</a-select-option>
                                <a-select-option value="no">否</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'支持送餐'" name="supportDelivery">
                            <a-select v-model:value="formData.supportDelivery">
                                <a-select-option value="yes">是</a-select-option>
                                <a-select-option value="no">否</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'助餐点名称'" name="mealPointName">
                            <a-input v-model:value="formData.mealPointName" placeholder="请输入助餐点名称"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'床位数'" name="bedCount" :required="true">
                            <a-input-number v-model:value="formData.bedCount" placeholder="请输入床位数" min="0" style="width: 100%"></a-input-number>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'日间照料中心名称'" name="daycareCenterName">
                            <a-input v-model:value="formData.daycareCenterName" placeholder="请输入日间照料中心名称"></a-input>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>

            <!-- 图片上传区域 -->
            <a-card class="mb-4" title="图片上传">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item :label="'资质附件'" name="qualificationFiles">
                            <a-upload
                                list-type="picture-card"
                                v-model:file-list="formData.qualificationFiles"
                                :before-upload="beforeUpload"
                            >
                                <div v-if="formData.qualificationFiles.length < 5">
                                    <plus-outlined />
                                    <div class="ant-upload-text">上传</div>
                                </div>
                            </a-upload>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'站点图片'" name="siteImages">
                            <a-upload
                                list-type="picture-card"
                                v-model:file-list="formData.siteImages"
                                :before-upload="beforeUpload"
                            >
                                <div v-if="formData.siteImages.length < 5">
                                    <plus-outlined />
                                    <div class="ant-upload-text">上传</div>
                                </div>
                            </a-upload>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>
            
        </a-form>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { QuestionCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import apis from '@/apis'
import { useModal, useForm } from '@/hooks'
import { menuTypeEnum, statusTypeEnum } from '@/enums/system'
import { ref, reactive } from 'vue'
import { config } from '@/config'
import { useI18n } from 'vue-i18n'
import storage from '@/utils/storage'
import { message } from 'ant-design-vue'
const emit = defineEmits(['ok'])
const { t } = useI18n() // 解构出t方法
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formData, formRef, formRules, resetForm } = useForm()

// 初始化表单数据
formData.value = {
    name: '', // 站点名称
    parent_id: '',
    nodeType: '',
    code: '',
    type: '',
    manager: '',
    phone: '',
    starLevel: '',
    staffCount: 0,
    address: [], // 省市区三级联动
    detailAddress: '',
    location: '', // 地图定位地址
    buildTime: null, // 建成时间
    area: 0, // 建筑面积
    description: '', // 服务介绍
    openTime: null, // 开始营业时间
    closeTime: null, // 结束营业时间
    businessStatus: '', // 营业状态
    services: [], // 提供的服务
    hasKitchen: '', // 是否有厨房
    provideMeal: '', // 提供餐饮
    supportDelivery: '', // 支持送餐
    mealPointName: '', // 助餐点名称
    bedCount: 0, // 床位数
    daycareCenterName: '', // 日间照料中心名称
    qualificationFiles: [], // 资质附件
    siteImages: [], // 站点图片
    resources: []
}

// 表单验证规则
formRules.value = {
    name: [
        { required: true, message: '请输入站点名称' }
    ],
    nodeType: [
        { required: true, message: '请选择所在节点' }
    ],
    code: [
        { required: true, message: '请输入机构代码' }
    ],
    type: [
        { required: true, message: '请选择站点类型' }
    ],
    manager: [
        { required: true, message: '请输入负责人姓名' }
    ],
    phone: [
        { required: true, message: '请输入联系电话' },
        { 
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的联系电话' 
        }
    ],
    bedCount: [
        { required: true, message: '请输入床位数' },
        { 
            validator: (_, value) => {
                if (value !== null && value !== undefined && value !== '') {
                    if (typeof value === 'number' && value >= 0) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('床位数必须为非负数'));
                }
                return Promise.reject(new Error('请输入床位数'));
            }
        }
    ],
    address: { required: true, message: '请选择省市区' },
    detailAddress: { required: true, message: '请输入详细地址' },
    buildTime: { required: true, message: '请选择建成时间' },
    area: { 
        required: true, 
        validator: (_, value) => {
            if (value && value > 0) {
                return Promise.resolve();
            }
            return Promise.reject(new Error('请输入有效的建筑面积'));
        }
    },
    openTime: { required: true, message: '请选择开始营业时间' },
    closeTime: { required: true, message: '请选择结束营业时间' },
    businessStatus: { required: true, message: '请选择营业状态' },
    services: { 
        required: true, 
        validator: (_, value) => {
            if (value && value.length > 0) {
                return Promise.resolve();
            }
            return Promise.reject(new Error('请至少选择一项服务'));
        }
    },
    hasKitchen: { required: true, message: '请选择是否有厨房' },
    provideMeal: { required: true, message: '请选择是否提供餐饮' }
}

// 表格列定义
const columns = [
    { title: t('pages.system.menu.form.path'), dataIndex: 'types', key: 'types' },
    { title: t('button.action'), dataIndex: 'action', key: 'action' }
]

// 请求类型
const reqType = ['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE']

// 取消和确认按钮文本
const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const platform = ref('')

// 地址选项 - 实际项目中可以从接口获取
const addressOptions = ref([
    {
        value: 'beijing',
        label: '北京',
        children: [
            {
                value: 'haidian',
                label: '海淀区',
                children: [
                    { value: 'zhongguancun', label: '中关村' },
                    { value: 'wudaokou', label: '五道口' }
                ]
            },
            {
                value: 'chaoyang',
                label: '朝阳区',
                children: [
                    { value: 'cbd', label: 'CBD' },
                    { value: 'sanlitun', label: '三里屯' }
                ]
            }
        ]
    },
    {
        value: 'shanghai',
        label: '上海',
        children: [
            {
                value: 'pudong',
                label: '浦东新区',
                children: [
                    { value: 'lujiazui', label: '陆家嘴' },
                    { value: 'zhangjiang', label: '张江' }
                ]
            }
        ]
    }
])

// 所有可提供的服务
const allServices = [
    { value: 'meal', label: '助餐' },
    { value: 'daycare', label: '日间照料' },
    { value: 'equipment', label: '辅具租赁' },
    { value: 'entertainment', label: '休闲/娱乐' },
    { value: 'health', label: '健康管理' }
]

/**
 * 新建
 */
function handleCreate() {
    formData.value.resources = []
    formData.value.qualificationFiles = []
    formData.value.siteImages = []
    showModal({
        type: 'create',
        title: '新增服务站点',
    })
}

/**
 * 添加下级
 */
function handleCreateChild(record = {}) {
    formData.value.resources = []
    formData.value.qualificationFiles = []
    formData.value.siteImages = []
    showModal({
        type: 'create',
        title: '新增服务站点',
    })
    formData.value.parent_id = record.id
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: t('pages.system.menu.edit'),
    })
    const { data } = await apis.menu.getMenu(record.id).catch(() => {
        throw new Error()
    })
    formData.value = cloneDeep(data)
    formData.value.properties = formData.value.properties ? JSON.parse(formData.value.properties) : ''
    formData.value.resources = formData.value.resources || []
    formData.value.qualificationFiles = formData.value.qualificationFiles || []
    formData.value.siteImages = formData.value.siteImages || []
    platform.value = data.platform
}

/**
 * 确定提交
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                const params = {
                    ...values,
                }
                params.sequence = Number.parseInt(params.sequence) || 0
                params.properties = JSON.stringify(params.properties)
                
                // 处理地址数据
                params.province = params.address[0]
                params.city = params.address[1]
                params.district = params.address[2]
                
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        params.platform = storage.local.getItem('platform')
                        result = await apis.menu.createMenu(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        newApiData()
                        params.resources = formData.value.resources
                        params.platform = platform.value
                        result = await apis.menu.updateMenu(formData.value.id, params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.success) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

/**
 * 处理API数据
 */
function newApiData() {
    if (formData.value.resources)
        formData.value.resources.forEach((item) => {
            item.menu_id = formData.value.id
        })
}

/**
 * 关闭后重置
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

/**
 * 添加API
 */
function handleAddApi() {
    formData.value.resources.push({
        method: 'GET',
        path: '',
    })
}

/**
 * 删除API
 */
function handleDelete(index) {
    formData.value.resources.splice(index, 1)
}

/**
 * 处理服务点击事件
 */
function handleServiceClick(value) {
    if (!formData.value.services) {
        formData.value.services = []
    }
    
    const index = formData.value.services.indexOf(value)
    if (index > -1) {
        // 如果已选中，则取消选中
        formData.value.services.splice(index, 1)
    } else {
        // 如果未选中，则添加选中
        formData.value.services.push(value)
    }
}

/**
 * 打开地图选择器
 */
function openMapSelector() {
    // 实际项目中可以调用地图组件或打开地图选择弹窗
    // 这里使用模拟数据
    formData.value.location = '北京市海淀区中关村大街1号 (经纬度: 39.9847, 116.3055)'
}

/**
 * 上传前处理
 */
function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式的图片!')
        return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        message.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

defineExpose({
    handleCreate,
    handleCreateChild,
    handleEdit,
})
</script>

<style lang="less" scoped>
.service-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 8px 0;
}

// 服务标签选中样式
.service-tag {
    cursor: pointer;
    
    &.ant-tag-checkable-checked {
        background-color: #1890ff; // 蓝色背景
        color: #fff; // 白色文字
        border-color: #1890ff;
        
        &:hover {
            background-color: #40a9ff;
            border-color: #40a9ff;
        }
    }
    
    &:not(.ant-tag-checkable-checked) {
        &:hover {
            border-color: #1890ff;
        }
    }
}

// 信息图标样式
.info-icon {
    margin-left: 4px;
    color: #1890ff;
    cursor: pointer;
}

.ant-upload-list {
    margin-top: 8px;
}
</style>