<script setup>
import {
  fromItemLabelMap,
  operationOptions,
  sortBy,
  sortType,
  yValueType
} from '@vue2-client/components/g2Charts/constants'
import { computed, inject, watch } from 'vue'

const config = inject('config')
const fieldColumn = inject('fieldColumnOptions')

// 当前y轴类型下的查询模式
const yFiledMolds = computed(() => {
  return yValueType.filter(item => item.value === config.value.yFieldType)[0]?.molds || []
})

// 修改添加y数据字段方法，增加饼图限制
const addYField = () => {
  // 如果是饼图且已有字段，则不允许添加
  if (config.value.type === 'pie' && config.value.yField?.length >= 1) {
    return
  }
  config.value.yField.push({
    field: undefined,
    mold: 'sum',
    label: undefined // 添加label属性
  })
}

// 删除字段
const removeField = (index) => {
  config.value.yField.splice(index, 1)
}

// 上移字段
const moveFieldUp = (index) => {
  if (index > 0) {
    const temp = config.value.yField[index]
    config.value.yField.splice(index, 1)
    config.value.yField.splice(index - 1, 0, temp)
  }
}

// 下移字段
const moveFieldDown = (index) => {
  if (index < config.value.yField.length - 1) {
    const temp = config.value.yField[index]
    config.value.yField.splice(index, 1)
    config.value.yField.splice(index + 1, 0, temp)
  }
}

// 修改处理操作的实现
const handleMenuClick = ({ key }, index) => {
  console.log('Menu clicked:', key, 'at index:', index)
  switch (key) {
    case 'delete':
      removeField(index)
      break
    case 'moveUp':
      moveFieldUp(index)
      break
    case 'moveDown':
      moveFieldDown(index)
      break
  }
}

// 修改显示添加按钮的计算属性
const showAddFieldBtn = computed(() => {
  if (config.value.type === 'pie') {
    return !config.value.yField?.length || config.value.yField.length === 0
  }
  return !config.value.Group
})

// 修改显示分组字段的计算属性，只负责计算显示逻辑
const showGroupField = computed(() => {
  // 饼图不显示分组
  if (config.value.type === 'pie') {
    return false
  }

  // 多个数据字段时不显示分组
  if (config.value.yField.length > 1) {
    return false
  }
  return true
})

// 添加对y轴字段数量的监听，处理分组配置
watch(
  () => config.value.yField.length,
  (newLength) => {
    if (newLength > 1) {
      config.value.Group = false
      config.value.groupField = undefined
    }
  }
)

// 添加对图表类型的监听，处理分组配置
watch(
  () => config.value.type,
  (newType) => {
    if (newType === 'pie') {
      config.value.Group = false
      config.value.groupField = undefined
    }
  }
)

// 添加对分组开关的监听
watch(() => config.value.Group, (newValue) => {
  // 当分组关闭时，清除分组字段
  if (!newValue) {
    config.value.groupField = undefined
  }
})

// 修改字段类型变更处理
const fieldTypeChange = (type) => {
  if (type === 'count') {
    // 类型为统计记录总数时，清空字段 不能选择y轴字段
    config.value.yField = []
  }
}

const validateYFields = computed(() => {
  if (config.value.yFieldType === 'sum' && (!config.value.yField || config.value.yField.length === 0)) {
    return '请至少添加一个统计字段'
  }
  if (config.value.yFieldType === 'sum' && config.value.yField.some(field => !field.field)) {
    return '请选择统计字段'
  }
  return ''
})

// 添加横轴字段验证
const validateXField = computed(() => {
  if (!config.value.xField) {
    return '请选择横轴字段'
  }
  return ''
})

// 添加 field 变化的监听处理
const handleFieldChange = (value, index) => {
  // 从 fieldColumn 中找到对应的字段配置
  const fieldConfig = fieldColumn.value.find(item => item.value === value)
  if (fieldConfig) {
    // 自动设置 label 为字段的显示名称
    config.value.yField[index].label = fieldConfig.label
  }
}

</script>

<template>
  <div>
    <a-form-model-item
      :label="fromItemLabelMap[config.type]['xField']"
      :validateStatus="validateXField ? 'error' : ''"
      :help="validateXField">
      <a-select
        v-model="config.xField"
        style="width: 100%"
        :showSearch="true"
        :getPopupContainer=" triggerNode => { return triggerNode.parentNode } "
        :options="fieldColumn"
        placeholder="选择横轴字段"
      >
      </a-select>
    </a-form-model-item>
    <a-form-model-item label="排序依据">
      <a-radio-group v-model="config.xFieldSortBy">
        <a-radio-button :value="item.value" :key="index" v-for="(item,index) in sortBy">
          <a-tooltip :title="item.placeholder">
            {{ item.label }}
          </a-tooltip>
        </a-radio-button>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item label="排序规则">
      <a-radio-group v-model="config.xFieldSortType">
        <a-radio-button :value="item.value" :key="index" v-for="(item,index) in sortType">
          {{ item.label }}
        </a-radio-button>
      </a-radio-group>
    </a-form-model-item>

    <a-form-model-item :label="fromItemLabelMap[config.type]['yFieldType']" :validateStatus="validateYFields ? 'error' : ''" :help="validateYFields">
      <a-select
        v-model="config.yFieldType"
        style="width: 100%"
        :options="yValueType"
        placeholder="设置纵轴字段"
        @change="fieldTypeChange"
      />
      <template v-if="config.yFieldType === 'sum'">
        <a-input-group compact style="width: 100%;margin-top: 12px" v-for="(item,index) in config.yField" :key="index">
          <a-select
            :options="fieldColumn"
            :getPopupContainer=" triggerNode => { return triggerNode.parentNode } "
            :showSearch="true"
            v-model="item.field"
            placeholder="选择字段"
            style="width: 45%"
            @change="(value) => handleFieldChange(value, index)"
          />
          <a-select
            :options="yFiledMolds"
            v-model="item.mold"
            placeholder="统计方式"
            style="width: 30%"
            :showArrow="false"/>
          <a-dropdown>
            <a-menu slot="overlay" @click="e => handleMenuClick(e, index)">
              <a-menu-item
                :key="operaItem.value"
                v-for="operaItem in operationOptions"
                :disabled="(operaItem.value === 'moveUp' && index === 0) || (operaItem.value === 'moveDown' && index === config.yField.length - 1)"
              >
                <a-icon :type="operaItem.icon"/>
                {{ operaItem.label }}
              </a-menu-item>
            </a-menu>
            <a-button icon="more"/>
          </a-dropdown>
        </a-input-group>
        <a-tooltip :title="config.type === 'pie' ? '饼图只能添加一个统计字段' : '仅可选择值为数字的字段'" v-if="showAddFieldBtn">
          <a-button type="link" @click="addYField">
            <a-icon type="plus"/>
            添加字段
          </a-button>
        </a-tooltip>
      </template>
    </a-form-model-item>    <!-- 修改分组字段的显示条件 -->
    <template v-if="showGroupField">
      <a-form-item label="分组聚合" style="margin-top: 12px">
        <a-switch checked-children="开" un-checked-children="关" v-model="config.Group"/>
        <a-select
          v-if="config.Group"
          v-model="config.groupField"
          style="width: 100%"
          :options="fieldColumn"
          placeholder="选择分组字段"
        >
        </a-select>
      </a-form-item>
    </template>
  </div>
</template>

<style scoped lang="less">

</style>
