<script setup>
import g2Charts from './index.vue'
import { computed, defineProps, onMounted, provide, ref, watch } from 'vue'
import { chartsTools, tabList, } from './constants'
import DesignerBaseConfig from '@vue2-client/components/g2Charts/designerBaseConfig.vue'
import DesignerDataConfig from '@vue2-client/components/g2Charts/designerDataConfig.vue'
import DesignerStyleConfig from '@vue2-client/components/g2Charts/designerStyleConfig.vue'
import { parseConfig } from '@vue2-client/services/api/common'

// 定义props 传参
defineProps({
  height: {
    type: String,
    default: '500px'
  },
  isDev: {
    type: Boolean,
    default: false
  }
})

const key = ref('类型与数据')

const g2ChartsRef = ref(null)

// 添加默认配置对象
const defaultConfig = {
  type: 'line',
  title: '',
  description: '',
  chartsTools: [],
  dataSource: 'curCrud',
  crudConfigName: undefined,
  logicName: undefined,
  xField: undefined,
  xFieldSortBy: 'value',
  xFieldSortType: 'asc',
  yFieldType: 'sum',
  yField: [{
    field: undefined,
    mold: 'sum'
  }],
  Group: false,
  groupField: undefined,
  colorIndex: 0,
}

// 修改配置初始化
const config = ref({ ...defaultConfig })

const fieldColumn = ref([])
// 可以使用的字段应该是过滤掉 横轴字段/y轴字段/分组字段的数据
const fieldColumnOptions = computed(() => {
  return fieldColumn.value.filter(item => {
    return !['xField', 'yField', 'GroupField'].includes(item.value)
  })
})

const onTabChange = (newKey) => {
  key.value = newKey
}

const filteredChartsTools = computed(() => {
  return chartsTools.filter(item => item.match.includes(config.value.type))
})

const configTypeChange = (value) => {
  config.value.type = value[0]
  // 工具默认全部选中
  config.value.chartsTools = filteredChartsTools.value.map(item => item.value)
  // 圆饼图
  if (value[0] === 'pie') {
    if (config.value.yField?.length > 1) {
      config.value.yField = [config.value.yField[0]]
    }
    // 清除分组配置
    config.value.Group = false
    config.value.groupField = undefined
  }
}
/**
 *
 * @param _config 现有的配置
 * @param curdColumn curd 查询配置的字段集合
 * @param curdConfig 编辑curd时，临时配置
 * @param systemName curd配置所属的命名空间
 */
// 修改 init 方法，添加验证
const init = async ({ config: _config = {}, curdColumn = [], curdConfig }) => {
  config.value = Object.assign(config.value, _config)
  // 编辑表单预览时，需要将配置内容解析后使用
  if (curdConfig) {
    config.value.queryParams = await parseConfig(curdConfig, 'CRUD_FORM')
  }
  configTypeChange([config.value.type])
  const uniqueKeys = new Set()
  fieldColumn.value = curdColumn
    .filter(item => {
      if (uniqueKeys.has(item.key)) {
        return false
      } else {
        uniqueKeys.add(item.key)
        return true
      }
    })
    .map(item => ({
      label: item.title,
      value: item.key,
    }))

  // 直接调用图表初始化，验证逻辑由图表组件处理
  g2ChartsRef.value?.init(config.value, {})
}

// 添加重置方法
const resetConfig = () => {
  config.value = { ...defaultConfig }
}

// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 创建防抖后的初始化函数
const debouncedInit = debounce((config) => {
  g2ChartsRef.value?.init(config, {})
}, 300)

// 修改 watch 逻辑, 使用防抖
watch(
  () => {
    const { title, description, ...rest } = config.value
    return rest
  },
  () => {
    console.log('Config changed, updating chart...')
    debouncedInit(config.value)
  },
  {
    deep: true,
    immediate: false
  }
)

onMounted(() => {
  // init({})
})

provide('filteredChartsTools', filteredChartsTools)
provide('fieldColumnOptions', fieldColumnOptions)
provide('configTypeChange', configTypeChange)
provide('config', config)
defineExpose({ init, config, resetConfig })
</script>

<template>
  <a-row>
    <a-col :span="16">
      <a-card
        :tab-list="[{key:'演示效果',tab:'演示效果'}]"
        :body-style="{maxHeight:height,height:height}">
        <div class="custom-chart-title" v-if="config.title">{{ config.title }}</div>
        <div class="custom-chart-desc" v-if="config.description">{{ config.description }}</div>
        <g2Charts ref="g2ChartsRef" :isDev="isDev"></g2Charts>
      </a-card>
    </a-col>
    <a-col :span="8">
      <a-card
        :tab-list="tabList"
        :active-tab-key="key"
        @tabChange="onTabChange"
        :body-style="{maxHeight:height,overflowY: 'scroll'}">
        <a-form-model layout="vertical">
          <template v-if="key === '类型与数据'">
            <designer-base-config/>
            <a-divider/>
            <designer-data-config/>
          </template>
          <designer-style-config v-else/>
        </a-form-model>
      </a-card>
    </a-col>
  </a-row>
</template>
<style lang="less" scoped>

.custom-chart-title {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 8px;
}

.custom-chart-desc {
  font-size: 12px;
  color: rgba(0, 0, 0, .45);
  margin-bottom: 16px;
}

:deep(.ant-select-selection__rendered) {
  display: flex;
  align-items: center;
}

:deep(.ant-form-vertical .ant-form-item ) {
  margin-bottom: 12px !important;
}

:deep(.ant-divider-horizontal) {
  margin: 12px 0;
}

.formModelVertical {
  // 向左偏移1px
  margin-left: -1px;
}

.colorBtn {
  width: 1.5rem;
  height: 1rem;
}
</style>
