const {
  createParameterGroupConfig,
  createParameterGroupDialogState,
  createParameterDialogState,
  createParameterRegisterChangedData,
  createParameterRegisterDialogState,
  findParameterGroup,
  findParameterRegister,
  getDialogDataTypeState,
  getOption
} = require('./view-model.js')
const {
  buildActiveParameterRegisterRows
} = require('./drag-view-model.js')

function getParameterGroupsFromState(state = {}) {
  return state.parameterGroups || []
}

function createDialogHandlers(parameterGroupService) {
  return {
    updateParameterDialog(changedData) {
      this.setData({
        parameterDialog: {
          ...this.data.parameterDialog,
          ...changedData
        }
      })
    },

    openParameterDraft(event) {
      const groupId = event && event.currentTarget && event.currentTarget.dataset
        ? event.currentTarget.dataset.groupId
        : ''
      const group = groupId ? findParameterGroup(getParameterGroupsFromState(this.data), groupId) : null

      this.updateParameterDialog(createParameterGroupDialogState(group))
    },

    closeParameterDraft() {
      this.parameterGroupLongPressGuard = ''
      this.parameterRegisterLongPressGuard = ''
      this.updateParameterDialog(createParameterDialogState())
    },

    onParameterDraftInput(event) {
      const field = event.currentTarget.dataset.field
      if (!field) return

      const value = event.detail.value
      this.updateParameterDialog({
        [field]: value,
        ...(field === 'structDefinition' ? {
          parsedStructRegisters: [],
          structParsedSummary: ''
        } : {})
      })
    },

    onParameterDraftSwitchChange(event) {
      const field = event.currentTarget.dataset.field
      if (!field) return

      this.updateParameterDialog({
        [field]: !!event.detail.value
      })
    },

    parseParameterStructDefinition() {
      const dialog = this.data.parameterDialog || createParameterDialogState()
      const sourceText = dialog.structDefinition || ''
      if (!sourceText.trim()) {
        if (this.pageToast) this.pageToast.show('请先粘贴结构体/枚举定义', 'error')
        return
      }

      const registerType = getOption(this.data.parameterRegisterTypeOptions, dialog.registerTypeIndex)
      if (registerType.key === 'coil' || registerType.key === 'discrete') {
        if (this.pageToast) this.pageToast.show('结构体解析仅支持寄存器类型', 'error')
        return
      }

      try {
        const parsed = parameterGroupService.parseStructDefinition(sourceText)
        const inputRegisterIndex = Math.max(
          0,
          this.data.parameterRegisterTypeOptions.findIndex((item) => item.key === 'input')
        )
        const inputRegisterType = getOption(this.data.parameterRegisterTypeOptions, inputRegisterIndex)
        this.updateParameterDialog({
          groupName: parsed.name || dialog.groupName,
          parsedStructRegisters: parsed.registers,
          quantity: String(parsed.registers.length),
          registerTypeIndex: inputRegisterIndex,
          registerTypeText: inputRegisterType.label || '',
          structParsedSummary: `${parsed.structName} · ${parsed.registers.length} 个字段`
        })
        if (this.pageToast) this.pageToast.show('结构体/枚举解析完成')
      } catch (error) {
        if (this.pageToast) this.pageToast.show(error.message || '结构体/枚举解析失败', 'error')
      }
    },

    onParameterDraftTypeChange(event) {
      const registerTypeIndex = Number(event.detail.value)
      const registerType = getOption(this.data.parameterRegisterTypeOptions, registerTypeIndex)
      const clearParsedStruct = registerType.key === 'coil' || registerType.key === 'discrete'

      this.updateParameterDialog({
        ...(clearParsedStruct ? {
          parsedStructRegisters: [],
          structParsedSummary: ''
        } : {}),
        registerTypeIndex,
        registerTypeText: registerType.label || ''
      })
    },

    onParameterDialogDataTypeChange(event) {
      const dataTypeIndex = Number(event.detail.value)

      this.updateParameterDialog(getDialogDataTypeState(
        this.data.parameterDialog,
        this.data.parameterDataTypeOptions,
        dataTypeIndex
      ))
    },

    openParameterGroupEdit(event) {
      const groupId = event.currentTarget.dataset.groupId
      const group = findParameterGroup(getParameterGroupsFromState(this.data), groupId)
      if (!group) return

      this.parameterGroupLongPressGuard = groupId

      this.updateParameterDialog(createParameterGroupDialogState(group))
    },

    openParameterRegisterInfo(event) {
      const groupId = event.currentTarget.dataset.groupId
      const registerIndex = Number(event.currentTarget.dataset.index)
      const registerKey = `${groupId}:${registerIndex}`
      if (this.parameterRegisterLongPressGuard === registerKey) {
        this.parameterRegisterLongPressGuard = ''
        return
      }

      const {
        group,
        register
      } = findParameterRegister(getParameterGroupsFromState(this.data), groupId, registerIndex)
      if (!register) return

      this.updateParameterDialog(createParameterRegisterDialogState('viewRegister', group, register, registerIndex))
    },

    openParameterRegisterEdit(event) {
      const groupId = event.currentTarget.dataset.groupId
      const registerIndex = Number(event.currentTarget.dataset.index)
      const {
        group,
        register
      } = findParameterRegister(getParameterGroupsFromState(this.data), groupId, registerIndex)
      if (!register) return

      this.parameterRegisterLongPressGuard = `${groupId}:${registerIndex}`
      this.updateParameterDialog(createParameterRegisterDialogState('editRegister', group, register, registerIndex))
    },

    async confirmParameterDialog() {
      const dialog = this.data.parameterDialog || createParameterDialogState()
      const mode = dialog.mode

      if (mode === 'createGroup') {
        const group = parameterGroupService.addGroupFromConfig(createParameterGroupConfig(dialog))
        if (group) {
          if (this.pageToast) this.pageToast.show(`${group.name}已添加`)
          this.closeParameterDraft()
          this.setData({
            activeParameterGroup: group,
            activeParameterGroupId: group.id,
            activeParamView: 'parameterGroup',
            activeParameterRegisterRows: buildActiveParameterRegisterRows(group, this.parameterRegisterDrag)
          })
        }
        return
      }

      if (mode === 'editGroup') {
        const group = parameterGroupService.updateGroupConfig(dialog.groupId, createParameterGroupConfig(dialog))
        if (group) {
          if (this.pageToast) this.pageToast.show(`${group.name}已更新`)
          this.closeParameterDraft()
          if (this.data.activeParameterGroupId === group.id) {
            this.setData({
              activeParameterGroup: group,
              activeParameterRegisterRows: buildActiveParameterRegisterRows(group, this.parameterRegisterDrag)
            })
          }
        }
        return
      }

      if (mode === 'editRegister') {
        let changedData
        try {
          changedData = createParameterRegisterChangedData(dialog, this.data.parameterDataTypeOptions)
        } catch (error) {
          if (this.pageToast) this.pageToast.show(error.message || '公式无效', 'error')
          return
        }
        parameterGroupService.updateRegister(dialog.groupId, dialog.registerIndex, changedData)
        if (this.pageToast) this.pageToast.show(`${dialog.name || '寄存器'}已更新`)
        this.closeParameterDraft()
      }
    }
  }
}

module.exports = {
  createDialogHandlers
}
