<template>
    <a-modal :open="modal.open" :title="modal.title" :width="800" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" @ok="handleOk" @cancel="handleCancel">
        <a-card>
            <a-spin tip="Loading..." :spinning="spining">
                <a-form ref="formRef" :model="formData" :rules="formRules">
                    <a-row :gutter="24">
                        <!-- 姓名 -->
                        <a-col :span="12">
                            <a-form-item label="服务对象" name="name">
                                <a-input v-model:value="formData.name" placeholder="请输入姓名" disabled />
                            </a-form-item>
                        </a-col>
                        <!-- 性别 -->
                        <a-col :span="12">
                            <a-form-item label="服务站点" name="stationName">
                               <a-input v-model:value="formData.stationName" placeholder="请输入服务站点" disabled/>
                            </a-form-item>
                        </a-col>
                        <!-- 出生日期 -->
                        <a-col :span="24">
                            <div style="margin-bottom: 20px;">
                                <span style="margin-right: 10px;"><span style="color: red;">*</span> 服务项目:</span>
                                <!-- 显示已选项目 -->
                                <a-tag v-for="item in selectedServices" :key="item.id" closable
                                    @close="handleRemove(item)">
                                    {{ item.name }}
                                </a-tag>
                                <a-tag @click="showModal2" color="#108ee9" style="cursor: pointer;">
                                    添加服务
                                </a-tag>
                            </div>

                        </a-col>

                        <a-col :span="12">
                            <a-form-item label="服务费用" name="price">
                                <a-input-number v-model:value="formData.price" style="width: 100%;"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <template v-if="formData.orderType == '2'">
                            <a-col :span="12">
                                <a-form-item label="服务人员" name="servicePersonId">
                                    <a-select v-model:value="formData.servicePersonId">
                                        <a-select-option v-for="item in servicePersonList" :key="item.id"
                                            :value="item.id">
                                            {{ item.name }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="计划日期" name="planeDate">
                                    <a-range-picker v-model:value="formData.planeDate" placeholder="请选择计划日期" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="计划开始时间" name="plannedStartDate">
                                    <a-time-picker v-model:value="formData.plannedStartDate" format="HH:mm"
                                        style="width: 100%;" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="要求工单时长" name="workDuration">
                                    <a-input-number v-model:value="formData.workDuration">
                                        <template #addonAfter>分钟</template>
                                    </a-input-number>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="服务地址(如修改服务地址，请务必更新地图定位地址)" name="areaCodes">
                                    <AreaCascader v-model:value="formData.areaCodes" @change="onAreaChange" ref="areaCascaderRef"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="详细地址" name="detailAddress">
                                    <a-input v-model:value="formData.detailAddress"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="地理地图定位" name="gps">
                                    <div @click="mapVisible = true">
                                        <span>{{ gps }}</span>
                                        <AimOutlined style="color: #40a9ff;" />
                                    </div>
                                </a-form-item>
                            </a-col>
                        </template>

                        <a-col :span="24">
                            <a-form-item label="服务内容" name="content">
                                <a-input v-model:value="formData.content"></a-input>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </a-spin>

        </a-card>
    </a-modal>
    <a-modal v-model:open="modalVisible" title="选择服务项目" @ok="handleConfirm" @cancel="handleCancel2" okText="确认"
        cancelText="取消" :width="600">
        <a-table :dataSource="serviceList" :columns="columns" :row-key="record => record.id"
            :row-selection="rowSelection" :pagination="false" :loading="loading" size="small">
            <template #bodyCell="{ index, column, record }">
                <template v-if="column.key === 'categoryType'">
                    <span>{{ dicsStore.getDictLabel('PROJECT_TYPE', record.categoryType) }}</span>
                </template>
            </template>
        </a-table>
    </a-modal>
    <a-modal v-model:open="mapVisible" title="选择地址" @ok="mapVisible = false" @cancel="mapVisible = false" okText="确认"
        cancelText="取消" :width="600">
        <gx-map @handleGetLng="handleGetLng" />
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, computed } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal, usePagination } from '@/hooks'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { validatePhone, validateEmail, validateIdCard } from '@/utils/validate'
import { getBirthDate, spliceUrl } from '@/utils/util'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { selectProps } from 'ant-design-vue/es/vc-select'
import { AimOutlined } from '@ant-design/icons-vue'
import GxMap from '@/components/GxMap/index.vue'
const emit = defineEmits(['ok'])
const activeKey = ref('1')
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const { paginationState } = usePagination()
const cancelText = ref('取消')
const servicePersonList = ref([])
const gps = ref('')
const mapVisible = ref(false)
const stationList = ref([])
const spining = ref(false)
const areaCascaderRef=ref()
formRules.value = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    identityType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
    identityNo: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
    contact1: [{ validator: validatePhone, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
    planeDate: [{ required: true, message: '请选择计划日期', trigger: ['blur', 'input'] }],
    servicePersonId: [{ required: true, message: '请选择服务人员', trigger: ['blur', 'input'] }],
    plannedStartDate: [{ required: true, message: '请选择计划开始时间', trigger: ['blur', 'input'] }],
    workDuration: [{ required: true, message: '请选择计划日期', trigger: ['blur', 'input'] }],
    areaCodes: [{ required: true, message: '请选择服务地址', trigger: ['blur', 'input'] }],
    detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

const dicsStore = useDicsStore()
// 已选中的服务项目（用于显示）
const selectedServices = ref([])

// 模态框控制
const modalVisible = ref(false)
const loading = ref(false)

// 服务项目列表（来自接口）
const serviceList = ref([])

// 表格列定义
const columns = [
    { title: '类型', dataIndex: 'categoryType', key: 'categoryType', align: 'center', width: 100, },
    { title: '分类名称', dataIndex: 'name', key: 'name', align: 'center', width: 180, },
    { title: '项目名称', dataIndex: 'name', key: 'name', align: 'center', },
    { title: '价格', dataIndex: 'price', key: 'price', align: 'center', },
    { title: '简介', dataIndex: 'remark', key: 'remark', align: 'center', },
]
// 1. 定义 selectedRowKeys 为普通 ref（只用于存储值）
const selectedRowKeys = ref([])
const rowSelection = computed(() => ({
    selectedRowKeys: selectedRowKeys.value,
    onChange: (newSelectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys:', newSelectedRowKeys, 'selectedRows:', selectedRows)
        selectedRowKeys.value = newSelectedRowKeys
        selectedServices.value = selectedRows
        formData.value.price = selectedServices.value.reduce((sum, item) => sum + item.price, 0)
    },
    getCheckboxProps: (record) => ({
        disabled: record.name === 'Disabled User',
        name: record.name,
    }),
}))
getSeveicePeople()
async function getSeveicePeople() {
    try {
        const { success, data, total } = await apis.serviceStaffList
            .getProjectList({
                pageSize: 100,
                current: 1,
            })
            .catch(() => {
                throw new Error()
            })

        if (config('http.code.success') === success) {
            servicePersonList.value = data.map(item => ({ id: item.id, name: item.name }))
        }
    } catch (error) {

    }
}
function onAreaChange(value, labels) {
    formData.value.areaLabels = [...labels]
}
function handleGetLng(obj) {
    gps.value = obj.address
    formData.value.lat = obj.lat
    formData.value.lng = obj.lng
}
// 打开模态框
async function showModal2() {
    modalVisible.value = true
    // 第一次加载数据
    //   if (serviceList.value.length === 0) {
    // fetchServices()
    //   }
    // 恢复已选中状态

    try {
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.serviceProject
            .getProjectList({
                pageSize, current,
            })
            .catch(() => {
                throw new Error()
            })

        if (config('http.code.success') === success) {
            serviceList.value = data
            paginationState.total = total
            if (selectedServices.value.length > 0) {
                const selectedIds = selectedServices.value.map(s => s.id)
                selectedRowKeys.value = selectedIds
            } else {
                selectedRowKeys.value = []
            }

        }
    } catch (error) {

    }
}

// 移除已选项目
const handleRemove = (item) => {
    selectedServices.value = selectedServices.value.filter(s => s.id !== item.id)
    formData.value.price = selectedServices.value.reduce((sum, item) => sum + item.price, 0)
}

// 确认选择
const handleConfirm = () => {
    modalVisible.value = false
}

// 取消
const handleCancel2 = () => {
    modalVisible.value = false
}
/**
 * 新建
 */
function handleCreate() {
    formData.value.gender = '1'
    showModal({
        type: 'create',
        title: '新建项',
    })
}

/**
 * 编辑
 */
async function handleEdit(record = {}, type) {
    showModal({
        type: 'edit',
        title: type == '1' ? '线上工单' : '线下工单'
    })
    try {
        spining.value = true
        formData.value.orderType = type, //线下2 线上1]
            formData.value.customerId = record.id
        formData.value.name = record.name
        formData.value.stationName = record.stationName
        formData.value.stationId = record.stationId
        formData.value.areaCodes = [...record.archive.homeAreaCodes]
        formData.value.areaLabels = record.archive.homeAreaLabels
        nextTick(() => {
            areaCascaderRef.value.initData(record.archive.homeAreaCodes)
        })
        if (type == '2') {
            formData.value.detailAddress = record.archive.homeDetailAddress
            gps.value = record.region.join('') + record.archive.homeDetailAddress
            formData.value.lat = record.archive.lag
            formData.value.lng = record.archive.lat
        }

        getServiceStation()
        spining.value = false
    } catch (error) {
        spining.value = false
    }

}
async function getServiceStation() {
    try {
        showLoading()
        const { success, data, total } = await apis.serviceMenu
            .getServiceSiteList({
                pageSize: 100,
                current: 1,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            stationList.value = data.map(item => ({ id: item.id, name: item.name }))
        }
    } catch (error) {
        hideLoading()
    }
}
/**
 * 确定
 */
function handleOk() {
    if (!selectedServices.value.length) {
        return message.error('请选择服务项目')
    }
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()

                let params = {
                    ...formData.value,

                    orderingMethod: 'pc'
                }
                if (formData.value.planeDate && formData.value.planeDate.length > 0) {
                    params.plannedServiceStartDate = formData.value.planeDate[0]
                    params.plannedEndDate = formData.value.planeDate[1]
                }
                params.projects = serviceList.value
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.serverObj.createItem(params).catch(() => {
                            throw new Error()
                        })
                        console.log('result', result.code)
                        break
                    case 'edit':
                        console.log(params)
                        result = await apis.serverObj.createOrderItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === true) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
                // message.error(error.message)
            }
        })
        .catch(() => {
            hideLoading()
        })
}


/**
 * 取消
 */
function handleCancel() {
    selectedServices.value = []
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    selectedServices.value = []
    resetForm()
    hideLoading()
}

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

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