<template>
  <Form
    size="small"
    layout="horizontal"
    :model="formModel"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
  >
    <Form.Item label="数据源" name="sourceType">
      <Select v-model:value="formModel.sourceType">
        <SelectOption :value="DataSourceType.STATIC">静态数据</SelectOption>
        <SelectOption :value="DataSourceType.API">API</SelectOption>
        <SelectOption :value="DataSourceType.BASIC_PATH">基础数据源</SelectOption>
        <SelectOption :value="DataSourceType.VIEW_CODE">视图源</SelectOption>
      </Select>
    </Form.Item>
    <!-- 静态数据 -->
    <template v-if="formModel.sourceType === DataSourceType.STATIC">
      <Form.Item label="数据" name="data">
        <Button type="default" size="small" @click="handleEditData('data')"
          >编辑</Button
        >
      </Form.Item>
    </template>
    <!-- 接口 -->
    <template v-else-if="formModel.sourceType === DataSourceType.API">
      <Form.Item label="接口地址" name="url">
        <Input.TextArea
          :auto-size="{ minRows: 5 }"
          placeholder="请输入接口地址"
          v-model:value="formModel.url"
        ></Input.TextArea>
      </Form.Item>
      <Form.Item label="请求方式" name="method">
        <RadioGroup v-model:value="formModel.method">
          <Radio value="GET">GET</Radio>
          <Radio value="POST">POST</Radio>
        </RadioGroup>
      </Form.Item>
      <Form.Item label="刷新时间" name="refreshTime">
        <InputNumber
          v-model:value="formModel.refreshTime"
          :step="1"
          style="width: 100%"
          @change="handleRefreshTimeChange"
        >
          <template #addonAfter>
            <span class="text-gray-500">秒</span>
          </template>
        </InputNumber>
      </Form.Item>
      <Form.Item label="请求参数" name="params">
        <Button type="default" size="small" @click="handleEditData('params')"
          >编辑</Button
        >
      </Form.Item>
      <Form.Item label="请求头" name="headers">
        <Button type="default" size="small" @click="handleEditData('headers')"
          >编辑</Button
        >
      </Form.Item>
      <Form.Item label="数据处理" name="dataProcess">
        <Button
          type="default"
          size="small"
          @click="handleEditData('dataProcess')"
          >编辑</Button
        >
      </Form.Item>
    </template>
    <!-- 基础数据 -->
     <template v-else-if="formModel.sourceType === DataSourceType.BASIC_PATH">
      <Form.Item label="基础数据源" name="basicPath">
        <Input placeholder="请输入或选择" v-model:value="formModel.basicPath">
          <template #addonAfter>
            <SettingOutlined @click="handleSetOrigin('table')" />
          </template>
        </Input>
      </Form.Item>
    </template>
    <!-- 视图源 -->
    <template v-else-if="formModel.sourceType === DataSourceType.VIEW_CODE">
      <Form.Item label="视图源" name="viewCode">
        <Input placeholder="请输入或选择" v-model:value="formModel.viewCode">
          <template #addonAfter>
            <SettingOutlined @click="handleSetOrigin('view')"/>
          </template>
        </Input>
      </Form.Item>
    </template>
  </Form>
  <CodeEditorModal ref="codeEditorRef" title="编辑" @ok="handleCodeSave" language="json" />
</template>

<script setup lang="ts">
import type { DataSource } from "./types";
import type { Ref } from "vue";
import { ref, defineProps, watch, defineEmits } from "vue";
import {
  Form,
  Input,
  Button,
  InputNumber,
  Select,
  SelectOption,
  RadioGroup,
  Radio,
} from "ant-design-vue";
import { DataSourceType } from "./chartEnum";
import { CodeEditorModal, type CodeEditorModalInstance } from "../codeEditor";
import { SettingOutlined } from "@ant-design/icons-vue";
import { getDataOrigin } from "@shalu/utils";

/**
 * 通用数据data约定内容结构
 * {
 *  xData: ['x轴标签A', 'x轴标签B', 'x轴标签C', 'x轴标签D'],
 *  yData: ['y轴数据A', 'y轴数据B', 'y轴数据C', 'y轴数据D'],
 *  // 根据不同类型的图表配置不同的series
 *  series: [
 *    {
 *      name: '系列A',
 *      data: [10, 20, 30, 40]
 *    },
 *    {
 *      name: '系列B',
 *      data: [10, 20, 30, 40]
 *    }
 *  ]
 * }
 */
const emit = defineEmits(["change"]);
const props = defineProps<{
  dataSource: DataSource;
}>();
const formModel = ref({
  sourceType: DataSourceType.STATIC,
  // 静态数据相关
  data: "",
  // 接口相关
  url: "",
  method: "",
  params: {},
  headers: {},
  refreshTime: 0,
  // 数据处理
  dataProcess: "",
  // 基础数据源
  basicPath: "",
  // 视图源
  viewCode: "",
});

const handleRefreshTimeChange = (val: unknown) => {
  formModel.value.refreshTime =
    val === 0 || (val as number) >= 60 ? (val as number) : 60;
};

/* =====================编辑代码======================= */
let pathKey: "data" | "params" | "headers" | "dataProcess";
const codeEditorRef = ref<Ref<CodeEditorModalInstance> | null>(null);
const handleEditData = (key: "data" | "params" | "headers" | "dataProcess") => {
  pathKey = key;
  codeEditorRef.value?.open(
    typeof formModel.value[key] === "string"
      ? formModel.value[key]
      : JSON.stringify(formModel.value[key])
  );
};
const handleCodeSave = (code: string) => {
  try {
    formModel.value[pathKey] = JSON.parse(code);
  } catch (error) {
    formModel.value[pathKey] = code;
  }
};

// 设置数据源
const handleSetOrigin = async (key: 'table' | 'view') => {
  const res = await getDataOrigin(key);
  console.log(res)
  if(key === 'table') {
    formModel.value.basicPath = res.value;
    formModel.value.viewCode = "";
  } else {
    formModel.value.viewCode = res.value;
    formModel.value.basicPath = "";
  }
}

watch(
  () => props.dataSource,
  (val) => {
    Object.assign(formModel.value, val || {});
  },
  { immediate: true }
);

watch(
  () => formModel.value,
  (val) => {
    emit("change", val);
  },
  { deep: true }
);
</script>

<style scoped></style>
