<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-button-props="{ disabled: isViewMode }"
    @ok="handleOk" @cancel="handleCancel">
    <a-form layout="vertical" ref="formRef" :model="formData" :rules="isViewMode ? {} : rules">
      <!-- 基本信息区域 -->
      <a-card class="mb-4">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="站点名称" name="name" required>
              <a-input v-model:value="formData.name" :disabled="isViewMode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所在机构" name="organizationId" required>
              <a-select v-model:value="formData.organizationId" :disabled="isViewMode">
                <a-select-option v-for="item in nodeOptions" :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="code" required>
              <a-input v-model:value="formData.code" :disabled="isViewMode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="站点类型" name="type" required>
              <a-select v-model:value="formData.type" :disabled="isViewMode" @change="handleChange">
                <a-select-option v-for="item in dicsStore.dictOptions.Station_Type" :key="item.dval" :value="item.dval">
                  {{ item.introduction }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="负责人姓名" name="manager" required>
              <a-input v-model:value="formData.manager" :disabled="isViewMode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" name="phone" required>
              <a-input v-model:value="formData.phone" :disabled="isViewMode" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="星级等级" name="starLevel">
              <a-select v-model:value="formData.starLevel" :disabled="isViewMode">
                <a-select-option v-for="item in dicsStore.dictOptions.Level" :key="item.dval" :value="item.dval">
                  {{ item.introduction }}
                </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" :disabled="isViewMode" min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- 地址信息区域 -->
      <a-card class="mb-4" title="地址信息" style="margin-top: 20px">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="服务中心地址" name="address">
              <AreaCascader v-model:value="formData.address" :disabled="isViewMode" @change="onAreaChange" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="详细地址" name="detailAddress">
              <a-input v-model:value="formData.detailAddress" :disabled="isViewMode" placeholder="请输入详细地址" />
            </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 :disabled="isViewMode" />
                </a-col>
                <a-col :span="6">
                  <a-button type="primary" block :disabled="isViewMode" @click="openMapSelector">
                    选择地图位置
                  </a-button>
                </a-col>
              </a-row>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- 站点信息区域 -->
      <a-card class="mb-4" title="站点信息" style="margin-top: 20px">
        <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="请选择建成时间"
                :disabled="isViewMode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="建筑面积（平方米）" name="area">
              <a-input-number v-model:value="formData.area" :disabled="isViewMode" min="0" style="width: 100%"
                placeholder="请输入建筑面积" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="服务介绍" name="description">
              <a-textarea v-model:value="formData.description" :disabled="isViewMode" rows="4" placeholder="请输入服务介绍" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- 服务信息区域 -->
      <a-card class="mb-4" title="服务信息" style="margin-top: 20px">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="营业时间" name="openTime">
              <div style="display: flex; gap: 8px">
                <a-time-picker v-model:value="formData.openTime" format="HH:mm" placeholder="开始时间"
                  :disabled="isViewMode" />
                <a-time-picker v-model:value="formData.closeTime" format="HH:mm" placeholder="结束时间"
                  :disabled="isViewMode" />
              </div>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="营业状态" name="businessStatus">
              <a-select v-model:value="formData.businessStatus" :disabled="isViewMode">
                <a-select-option v-for="item in dicsStore.dictOptions.Business_Status" :key="item.dval"
                  :value="item.dval">
                  {{ item.introduction }}
                </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" :class="{
                  'ant-tag-checkable-checked': formData.services?.includes(service.value),
                }" class="service-tag" :style="{ cursor: isViewMode ? 'default' : 'pointer' }"
                  @click="isViewMode ? null : handleServiceClick(service.value)">
                  {{ service.label }}
                </a-tag>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <!-- 图片上传区域 -->
      <a-card class="mb-4" title="图片上传" style="margin-top: 20px">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="资质附件" name="qualificationFiles">
              <UploadInput v-model="formData.qualificationFiles" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="站点图片" name="siteImages">
              <gx-upload v-model="formData.siteImages" :fileNumber="1" accept-types=".jpg,.png,.webp" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>

    <MapPickerModal :open="showMapPicker" @update:open="(val) => (showMapPicker = val)"
      @select="handleLocationSelect" />
  </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 { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import MapPickerModal from '@/components/Map/index.vue'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
import UploadInput from '@/components/Upload/UploadInput.vue'
import { getBirthDate, spliceUrl } from '@/utils/util'
const emit = defineEmits(['ok'])
const { t } = useI18n()
const { modal, showModal, hideModal } = useModal()
const { formData, formRef, resetForm } = useForm()

// 初始化表单数据
const initFormData = () => ({
  id: undefined,
  name: '',
  parent_id: '',
  organizationId: '',
  organization: '',
  code: '',
  type: '',
  manager: '',
  phone: '',
  starLevel: '',
  staffCount: 0,
  address: [],
  detailAddress: '',
  location: '',
  buildTime: null,
  area: 0,
  description: '',
  openTime: null,
  closeTime: null,
  businessStatus: '',
  services: [],
  qualificationFiles: [],
  siteImages: [],
  latitude: 0,
  longitude: 0,
})

formData.value = initFormData()

const rules = {
  organizationId: [{ required: true, message: '请选择所在节点', trigger: 'change' }],
  name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入机构代码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择站点类型', trigger: 'change' }],
  manager: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}

const isViewMode = computed(() => modal.value.mode === 'view')
const cancelText = computed(() => (isViewMode.value ? '关闭' : '取消'))
const okText = computed(() =>
  modal.value.mode === 'create' ? '确定' : '保存'
)

const showMapPicker = ref(false)
const dicsStore = useDicsStore()
const nodeOptions = ref([])

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

// ================== Methods ==================

async function fetchNodeOptions() {
  try {
    const res = await apis.serviceMenu.getOrgSelect()
    if (res.success && Array.isArray(res.data)) {
      nodeOptions.value = res.data.map((item) => ({ id: item.id, name: item.name }))
      console.log('nodeOptions', nodeOptions.value)
    } else {
      nodeOptions.value = []
      message.warning('未获取到服务站点数据')
    }
  } catch (error) {
    console.error('获取机构数据失败:', error)
    message.error('获取机构数据失败')
  }
}

function handleCreate() {
  fetchNodeOptions()
  formData.value = initFormData()
  showModal({ mode: 'create', title: '新增服务站点' })
}

function handleCreateChild(record = {}) {
  formData.value = initFormData()
  formData.value.parent_id = record.id
  showModal({ mode: 'create', title: '新增服务站点' })
}

async function handleEdit(record = {}) {
  console.log('handleEdit', record)
  showModal({ mode: 'edit', title: '编辑服务站点' })
  await loadRecord(record.id, false)
}

async function handleView(record = {}) {
  showModal({ mode: 'view', title: '查看服务站点' })
  await loadRecord(record.id, true)
}

async function loadRecord(id, forView = false) {
  try {
    const { data } = await apis.serviceMenu.getServiceSiteDetail(id)
    const record = cloneDeep(data)

    const org = record.organization || {}
    console.log('rdataecord', data)
    console.log('org', org)
    const stationTypeText = record.stationType || ''
    const typeOption = dicsStore.dictOptions.Station_Type?.find(
      item => item.introduction === stationTypeText
    )
    const stationTypeValue = typeOption ? typeOption.dval : ''

    formData.value = {
      ...initFormData(),
      id: record.id,
      name: record.name || '',
      organizationId: org.id || '',
      organization: org.name || '',
      code: org.orgCode || '',
      type: stationTypeValue,
      manager: org.concatName || '',
      phone: org.concatPhone || '',
      starLevel: record.starLv || '',
      staffCount: record.memberNum || 0,
      address: record.areaLabels || [],
      detailAddress: record.address || '',
      location: record.location || '',
      buildTime: record.completionAt ? dayjs(record.completionAt) : null,
      area: record.area || 0,
      description: record.content || '',
      openTime: record.openAt ? dayjs(`1970-01-01 ${record.openAt}`) : null,
      closeTime: record.closeAt ? dayjs(`1970-01-01 ${record.closeAt}`) : null,

      status: record.status || '',
      services: record.provideServices || [],
      qualificationFiles: (record.qualificationAttachment && record.qualificationAttachment.length > 0) ? record.qualificationAttachment.map(item => config('http.apiUpload') + item) : [],
      siteImages: (record.stationImgs && record.stationImgs.length > 0) ? record.stationImgs.map(item => config('http.apiUpload') + item) : [],
      latitude: record.latitude || 0,
      longitude: record.longitude || 0,
    }

    // 仅在编辑/创建时才需要拉取机构选项（查看模式不需要）
    if (!forView) {
      await fetchNodeOptions()
    }
  } catch (error) {
    message.error('获取数据失败')
    console.error(error)
  }
}

async function handleOk() {
  if (isViewMode.value) return

  try {
    formRef.value.validateFields().then(async (values) => {
      console.log('values', values)
      try {
        const params = {
          Name: values.name,
          organizationId: values.organizationId,
          organizationName: nodeOptions.value.find(opt => opt.id === values.organizationId)?.name || '',
          OrgCode: values.code,
          StationType: (() => {
            const typeItem = dicsStore.dictOptions.Station_Type?.find(
              (item) => item.dval === values.type
            )
            return typeItem ? typeItem.introduction : values.type || ''
          })(),
          StationTypeValue: values.type, // 传 dval 给后端
          ConcatName: values.manager,
          ConcatPhone: values.phone,
          StarLv: values.starLevel || '',
          MemberNum: values.staffCount || 0,
          AreaLabels: values.address?.length ? values.address : null,
          Address: values.detailAddress || '',
          Latitude: formData.value.latitude || 0,
          Longitude: formData.value.longitude || 0,
          CompletionAt: values.buildTime ? values.buildTime.toDate() : null,
          Area: values.area || 0,
          Content: values.description || '',
          OpenAt: values.openTime ? values.openTime.format('HH:mm') : '',
          CloseAt: values.closeTime ? values.closeTime.format('HH:mm') : '',
          Status: '1',
          ProvideServices: values.services?.length ? values.services : null,
          QualificationAttachment: values.qualificationFiles?.map(f => f.url || f.response?.url) || null,
          QualificationAttachment: (values.qualificationFiles && values.qualificationFiles.length) > 0 ? values.qualificationFiles.map(item => spliceUrl(item)) : [],
          StationImgs: (values.siteImages && values.siteImages.length) > 0 ? values.siteImages.map(item => spliceUrl(item)) : [],
        }

        console.log('params', params)

        let result
        if (modal.value.mode === 'create') {
          result = await apis.serviceMenu.createServiceSite(params)
        } else if (modal.value.mode === 'edit') {
          result = await apis.serviceMenu.updateServiceSite(formData.value.id, params)
        }

        if (result?.success) {
          message.success(modal.value.mode === 'create' ? '新增成功' : '更新成功')
          hideModal()
          emit('ok')
        } else {
          message.error(result?.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        message.error('操作失败，请重试')
      }
    })
  } catch (error) {
    console.error('表单校验失败:', error)
    return
  }


}

function handleCancel() {
  hideModal()
}

function onAfterClose() {
  resetForm()
}

function handleServiceClick(value) {
  if (isViewMode.value) return
  const services = formData.value.services || []
  const index = services.indexOf(value)
  if (index > -1) {
    services.splice(index, 1)
  } else {
    services.push(value)
  }
  formData.value.services = [...services]
}

function openMapSelector() {
  if (isViewMode.value) return
  showMapPicker.value = true
}

function handleLocationSelect(lngLat) {
  formData.value.location = lngLat.address || ''
  formData.value.longitude = lngLat.lng || 0
  formData.value.latitude = lngLat.lat || 0
  showMapPicker.value = false
}

function onAreaChange(value) {
  // 可选：清空详细地址或经纬度
  // formData.value.detailAddress = ''
}

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
}

function handleChange() {
  // 可选：站点类型变化时清空某些字段
}

defineExpose({
  handleCreate,
  handleCreateChild,
  handleEdit,
  handleView,
})
</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;
}
</style>