import { ref, computed, watch, type Ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useProjectStore } from '@/stores/project'
import { useDictOptions } from './useDictOptions'
import { createTask, type TaskParams } from '@/api/task'
import {
  showToast,
  navigateTo,
  getCooperationTypeText,
  getFacilityTypeText,
  parseJsonArray
} from '@/utils'
import type { Project, ServicePoint } from '@/types'

export interface PublishTaskForm {
  // 项目基本信息
  projectId?: number
  projectName: string
  servicePointId?: number
  servicePointName: string
  cooperationType: string
  facilityType: string
  address: string
  contactName: string
  contactPhone: string
  contacts: { name: string; phone: string }[]

  // 服务信息
  serviceTime: string        // YYYY-MM-DDTHH:mm:ss
  faultLocation: string
  geoLocation: string
  latitude: string
  longitude: string
  faultDescription: string
  faultPhotos: string[]
  constructionType: string
  constructionFacility: string
  serviceMethod: string
  suggestedVehicles: string[]
  waterDistance: string
  outletNormal: number
  constructionHelp: string
  estimatedQuantity: string
  estimatedHours: string
  acceptanceReq: string
  hasPreviousWork: number
  acceptanceMethod: string
  partyAContacts: { name: string; phone: string; position?: string }[]
  remark: string

  // 自动生成只读
  taskNo: string
  taskName: string
  taskType: string
}

const acceptanceMethods = ['签署验收计量单', '累计自动计费']

// 后台字典默认值兜底
const fallbackConstructionTypes = [
  { value: '疏通', label: '疏通' },
  { value: '清淤', label: '清淤' },
  { value: '排查', label: '排查' }
]
const fallbackConstructionFacilities = [
  { value: 'PVC', label: 'PVC' },
  { value: '直抽直排', label: '直抽直排' },
  { value: '油污', label: '油污' },
  { value: '排污', label: '排污' },
  { value: '油污管', label: '油污管' },
  { value: '化粪池', label: '化粪池' }
]
const fallbackServiceMethods = [
  { value: '应急', label: '应急' },
  { value: '月计划', label: '月计划' }
]
const fallbackSuggestedVehicles = [
  { value: '疏通车', label: '疏通车' },
  { value: '吸污车', label: '吸污车' },
  { value: '高压清洗车', label: '高压清洗车' }
]
const fallbackWaterDistances = [
  { value: '有消防水', label: '有消防水' },
  { value: '无消防水', label: '无消防水' }
]

function mapConstructionTypeToTaskType(type?: string): string {
  switch (type) {
    case '疏通': return 'dredge'
    case '清淤': return 'clean'
    case '排查': return 'inspect'
    default: return 'dredge'
  }
}

function combineDateTime(date: string, time: string): string {
  if (!date) return ''
  return time ? `${date}T${time}` : `${date}T00:00:00`
}

function splitDateTime(value: string): { date: string; time: string } {
  if (!value) return { date: '', time: '' }
  const [date, time] = value.split('T')
  return { date: date || '', time: time || '' }
}

function isRemoteUrl(url: string): boolean {
  return /^https?:\/\//.test(url)
}

function generateTaskNo(): string {
  return `TK-${Date.now()}`
}

function generateTaskName(
  projectName: string,
  servicePointName: string,
  faultLocation: string,
  constructionType: string
): string {
  const suffix = servicePointName || faultLocation || constructionType || '任务'
  return `${projectName || ''}-${suffix}`.slice(0, 100)
}

export function usePublishTaskForm() {
  const projectStore = useProjectStore()

  // 字典
  const constructionTypeDict = useDictOptions('construction_type', fallbackConstructionTypes)
  const constructionFacilityDict = useDictOptions('construction_facility', fallbackConstructionFacilities)
  const serviceMethodDict = useDictOptions('service_method', fallbackServiceMethods)
  const suggestedVehicleDict = useDictOptions('suggested_vehicle', fallbackSuggestedVehicles)
  const waterDistanceDict = useDictOptions('water_distance', fallbackWaterDistances)

  // 表单
  const form = ref<PublishTaskForm>({
    projectId: undefined,
    projectName: '',
    servicePointId: undefined,
    servicePointName: '',
    cooperationType: '',
    facilityType: '',
    address: '',
    contactName: '',
    contactPhone: '',
    contacts: [],

    serviceTime: '',
    faultLocation: '',
    geoLocation: '',
    latitude: '',
    longitude: '',
    faultDescription: '',
    faultPhotos: [],
    constructionType: '',
    constructionFacility: '',
    serviceMethod: '',
    suggestedVehicles: [],
    waterDistance: '',
    outletNormal: 1,
    constructionHelp: '',
    estimatedQuantity: '',
    estimatedHours: '',
    acceptanceReq: '',
    hasPreviousWork: 0,
    acceptanceMethod: '',
    partyAContacts: [],
    remark: '',

    taskNo: generateTaskNo(),
    taskName: '',
    taskType: ''
  })

  const servicePointOptions: Ref<ServicePoint[]> = ref([])
  const submitting = ref(false)

  // 计算属性
  const projectNames = computed(() => [...projectStore.projects.map(p => p.projectName), '+ 新增项目'])
  const projects = computed(() => projectStore.projects)
  const selectedProject = computed(() => projectStore.projects.find(p => String(p.projectId) === String(form.value.projectId)) || null)

  const projectIndex = computed(() => projects.value.findIndex(p => String(p.projectId) === String(form.value.projectId)))

  const constructionTypeLabels = computed(() => constructionTypeDict.options.value.options.map(o => o.label))
  const constructionFacilityLabels = computed(() => constructionFacilityDict.options.value.options.map(o => o.label))
  const serviceMethodLabels = computed(() => serviceMethodDict.options.value.options.map(o => o.label))
  const suggestedVehicleLabels = computed(() => suggestedVehicleDict.options.value.options.map(o => o.label))
  const suggestedVehicleOptions = computed(() => suggestedVehicleDict.options.value.options)
  const waterDistanceLabels = computed(() => waterDistanceDict.options.value.options.map(o => o.label))

  const constructionTypeIndex = computed(() =>
    constructionTypeDict.options.value.options.findIndex(o => o.value === form.value.constructionType))
  const constructionFacilityIndex = computed(() =>
    constructionFacilityDict.options.value.options.findIndex(o => o.value === form.value.constructionFacility))
  const serviceMethodIndex = computed(() =>
    serviceMethodDict.options.value.options.findIndex(o => o.value === form.value.serviceMethod))
  const waterDistanceIndex = computed(() =>
    waterDistanceDict.options.value.options.findIndex(o => o.value === form.value.waterDistance))
  const acceptanceMethodIndex = computed(() =>
    acceptanceMethods.indexOf(form.value.acceptanceMethod))

  const servicePointNames = computed(() =>
    servicePointOptions.value.map((p, idx) => p.name || `服务点${idx + 1}`))
  // servicePointId 存储的是选项索引（服务点 JSON 无 id 字段）
  const servicePointIndex = computed(() => {
    const id = form.value.servicePointId
    if (id === undefined) return -1
    return servicePointOptions.value.findIndex((_, idx) => idx === id)
  })

  const selectedServicePointText = computed(() => form.value.servicePointName || '请选择服务点')

  // 联动：施工类型变化 -> 任务类型
  watch(() => form.value.constructionType, (val) => {
    form.value.taskType = mapConstructionTypeToTaskType(val)
  })

  // 联动：故障位置 / 施工类型 / 服务点变化 -> 任务名称
  watch(
    () => [form.value.projectName, form.value.servicePointName, form.value.faultLocation, form.value.constructionType],
    () => {
      form.value.taskName = generateTaskName(
        form.value.projectName,
        form.value.servicePointName,
        form.value.faultLocation,
        form.value.constructionType
      )
    },
    { deep: true }
  )

  // 初始化
  onLoad(async (query) => {
    await loadDictOptions()
    if (projectStore.projects.length === 0) {
      try { await projectStore.fetchProjects(true) } catch (e) { /* ignore */ }
    }
    if (query?.projectId) {
      const project = projectStore.projects.find(p => String(p.projectId) === String(query.projectId))
      if (project) {
        selectProject(project)
      }
    }
  })

  async function loadDictOptions() {
    await Promise.all([
      constructionTypeDict.load(),
      constructionFacilityDict.load(),
      serviceMethodDict.load(),
      suggestedVehicleDict.load(),
      waterDistanceDict.load()
    ])
  }

  function selectProject(project: Project) {
    form.value.projectId = Number(project.projectId)
    form.value.projectName = project.projectName || ''
    form.value.cooperationType = getCooperationTypeText(project.cooperationType)
    form.value.facilityType = parseJsonArray<string>(project.facilityTypes)
      .map(t => getFacilityTypeText(t))
      .join('、')
    form.value.address = project.address || ''
    form.value.contactName = project.primaryContactName || ''
    form.value.contactPhone = project.primaryContactPhone || ''

    servicePointOptions.value = parseJsonArray<ServicePoint>(project.servicePoints)
    form.value.servicePointId = undefined
    form.value.servicePointName = ''
    form.value.contacts = []

    generateTaskName(
      form.value.projectName,
      form.value.servicePointName,
      form.value.faultLocation,
      form.value.constructionType
    )
  }

  function onProjectSelectChange(e: any) {
    const index = Number(e.detail.value)
    if (index >= projects.value.length) {
      navigateTo('/subPackages/pages-common/addProject')
      return
    }
    selectProject(projects.value[index])
  }

  function onServicePointChange(e: any) {
    const index = Number(e.detail.value)
    const point = servicePointOptions.value[index]
    if (!point) return

    form.value.servicePointId = point.id ?? index
    form.value.servicePointName = point.name || `服务点${index + 1}`
    form.value.address = point.address || form.value.address
    form.value.contactName = point.contact || form.value.contactName
    form.value.contactPhone = point.phone || form.value.contactPhone
  }

  function resetProjectSelection() {
    form.value.projectId = undefined
    form.value.projectName = ''
    form.value.servicePointId = undefined
    form.value.servicePointName = ''
    form.value.cooperationType = ''
    form.value.facilityType = ''
    form.value.address = ''
    form.value.contactName = ''
    form.value.contactPhone = ''
    form.value.contacts = []
    servicePointOptions.value = []
  }

  function onConstructionTypeChange(e: any) {
    const index = Number(e.detail.value)
    const option = constructionTypeDict.options.value.options[index]
    if (option) form.value.constructionType = option.value
  }

  function onConstructionFacilityChange(e: any) {
    const index = Number(e.detail.value)
    const option = constructionFacilityDict.options.value.options[index]
    if (option) form.value.constructionFacility = option.value
  }

  function onServiceMethodChange(e: any) {
    const index = Number(e.detail.value)
    const option = serviceMethodDict.options.value.options[index]
    if (option) form.value.serviceMethod = option.value
  }

  function onWaterDistanceChange(e: any) {
    const index = Number(e.detail.value)
    const option = waterDistanceDict.options.value.options[index]
    if (option) form.value.waterDistance = option.value
  }

  function onAcceptanceMethodChange(e: any) {
    const index = Number(e.detail.value)
    form.value.acceptanceMethod = acceptanceMethods[index] || ''
  }

  function toggleVehicle(value: string) {
    const idx = form.value.suggestedVehicles.indexOf(value)
    if (idx > -1) {
      form.value.suggestedVehicles.splice(idx, 1)
    } else {
      form.value.suggestedVehicles.push(value)
    }
  }

  function chooseLocation() {
    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        uni.chooseLocation({
          success: (res) => {
            form.value.geoLocation = res.address || res.name || ''
            form.value.latitude = String(res.latitude ?? '')
            form.value.longitude = String(res.longitude ?? '')
          },
          fail: () => {
            uni.showToast({ title: '选择位置失败', icon: 'none' })
          }
        })
      },
      fail: () => {
        uni.showModal({
          title: '需要位置权限',
          content: '请在设置中允许使用位置信息',
          success: (res) => {
            if (res.confirm) uni.openSetting()
          }
        })
      }
    })
  }

  // 联系人
  function addContact() {
    form.value.contacts.push({ name: '', phone: '' })
  }

  function removeContact(index: number) {
    form.value.contacts.splice(index, 1)
  }

  function addPartyAContact() {
    form.value.partyAContacts.push({ name: '', phone: '', position: '' })
  }

  function removePartyAContact(index: number) {
    form.value.partyAContacts.splice(index, 1)
  }

  // 日期时间
  const serviceTimeDate = computed({
    get: () => splitDateTime(form.value.serviceTime).date,
    set: (val: string) => {
      const { time } = splitDateTime(form.value.serviceTime)
      form.value.serviceTime = combineDateTime(val, time)
    }
  })

  const serviceTimeTime = computed({
    get: () => splitDateTime(form.value.serviceTime).time,
    set: (val: string) => {
      const { date } = splitDateTime(form.value.serviceTime)
      form.value.serviceTime = combineDateTime(date, val)
    }
  })

  function onServiceTimeDateChange(e: any) { serviceTimeDate.value = e.detail.value }
  function onServiceTimeTimeChange(e: any) { serviceTimeTime.value = e.detail.value }

  // 布尔选择
  function setOutletNormal(value: number) {
    form.value.outletNormal = value
  }

  function setHasPreviousWork(value: number) {
    form.value.hasPreviousWork = value
  }

  function validateForm(): boolean {
    if (!form.value.projectId) { showToast('请选择项目'); return false }
    if (!form.value.address.trim()) { showToast('请输入项目地址'); return false }
    if (!form.value.serviceTime) { showToast('请选择服务时间'); return false }
    if (!form.value.faultLocation.trim()) { showToast('请输入故障位置'); return false }
    if (!form.value.faultDescription.trim()) { showToast('请输入故障描述'); return false }
    if (!form.value.constructionType) { showToast('请选择施工类型'); return false }
    if (!form.value.constructionFacility) { showToast('请选择施工设施'); return false }
    if (!form.value.serviceMethod) { showToast('请选择服务方式'); return false }
    if (form.value.suggestedVehicles.length === 0) { showToast('请选择建议出车'); return false }
    if (!form.value.acceptanceMethod) { showToast('请选择验收方式'); return false }
    return true
  }

  function buildPayload(): TaskParams {
    const project = selectedProject.value
    const address = form.value.address.trim() || project?.address || '-'

    return {
      projectId: form.value.projectId!,
      taskNo: generateTaskNo(),
      taskName: form.value.taskName,
      taskType: form.value.taskType,
      status: 'auditing',
      planDate: form.value.serviceTime.slice(0, 10),
      address,
      remark: form.value.remark,
      facilityType: form.value.facilityType,
      servicePointId: form.value.servicePointId,
      servicePointName: form.value.servicePointName,
      serviceContent: form.value.faultDescription,
      faultLocation: form.value.faultLocation,
      constructionType: form.value.constructionType,
      constructionFacility: form.value.constructionFacility,
      serviceMethod: form.value.serviceMethod,
      waterDistance: form.value.waterDistance,
      outletNormal: form.value.outletNormal,
      assistantInfo: form.value.constructionHelp,
      estimatedWorkload: form.value.estimatedQuantity,
      estimatedDuration: form.value.estimatedHours,
      acceptanceRequirement: form.value.acceptanceReq,
      hasPreviousWork: form.value.hasPreviousWork,
      acceptanceMethod: form.value.acceptanceMethod,
      toolRequirement: form.value.suggestedVehicles.join(','),
      expectedArrivalTime: form.value.serviceTime,
      extraData: JSON.stringify({
        projectName: project?.projectName,
        servicePointName: form.value.servicePointName,
        contactName: form.value.contactName,
        contactPhone: form.value.contactPhone,
        contacts: form.value.contacts,
        partyAContacts: form.value.partyAContacts,
        geoLocation: form.value.geoLocation,
        latitude: form.value.latitude,
        longitude: form.value.longitude,
        faultPhotos: form.value.faultPhotos
      })
    }
  }

  async function submitTask() {
    if (!validateForm()) return

    if (form.value.faultPhotos.some((u) => !isRemoteUrl(u))) {
      showToast('图片正在上传，请稍候')
      return
    }

    submitting.value = true
    try {
      const payload = buildPayload()
      await createTask(payload)
      showToast({ title: '任务发布成功', icon: 'success' })
      setTimeout(() => uni.navigateBack(), 1500)
    } finally {
      submitting.value = false
    }
  }

  return {
    form,
    submitting,
    projectNames,
    projectIndex,
    selectedProject,
    servicePointNames,
    servicePointIndex,
    selectedServicePointText,
    constructionTypeLabels,
    constructionTypeIndex,
    constructionFacilityLabels,
    constructionFacilityIndex,
    serviceMethodLabels,
    serviceMethodIndex,
    suggestedVehicleLabels,
    suggestedVehicleOptions,
    waterDistanceLabels,
    waterDistanceIndex,
    acceptanceMethods,
    acceptanceMethodIndex,
    serviceTimeDate,
    serviceTimeTime,

    onProjectSelectChange,
    onServicePointChange,
    resetProjectSelection,
    onConstructionTypeChange,
    onConstructionFacilityChange,
    onServiceMethodChange,
    onWaterDistanceChange,
    onAcceptanceMethodChange,
    toggleVehicle,
    chooseLocation,
    addContact,
    removeContact,
    addPartyAContact,
    removePartyAContact,
    onServiceTimeDateChange,
    onServiceTimeTimeChange,
    setOutletNormal,
    setHasPreviousWork,
    submitTask
  }
}
