/**
 * KRA - 模板配置页面
 * 对应 GVA: view/systemTools/autoPkg/autoPkg.vue
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Table, Button, Drawer, Form, Input, Select, Space, message, Modal } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import WarningBar from '@/components/WarningBar/WarningBar';
import { createPackage, getPackage, deletePackage, getTemplates } from '@/services/kratos/autoCode';

interface PackageItem {
  ID: number;
  packageName: string;
  template: string;
  label: string;
  desc: string;
}

const AutoPkg: React.FC = () => {
  const [form] = Form.useForm();
  const [tableData, setTableData] = useState<PackageItem[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [templatesOptions, setTemplatesOptions] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取模板列表
  const fetchTemplates = async () => {
    const res = await getTemplates();
    if (res.code === 0) {
      setTemplatesOptions(res.data || []);
    }
  };

  // 获取表格数据
  const fetchTableData = async () => {
    setLoading(true);
    const res = await getPackage();
    if (res.code === 0) {
      setTableData(res.data?.pkgs || []);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchTemplates();
    fetchTableData();
  }, []);

  // 打开抽屉
  const openDrawer = () => {
    setDrawerVisible(true);
  };

  // 关闭抽屉
  const closeDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
  };


  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const res = await createPackage(values);
      if (res.code === 0) {
        message.success('添加成功');
        fetchTableData();
        closeDrawer();
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  // 删除
  const handleDelete = (record: PackageItem) => {
    Modal.confirm({
      title: '提示',
      content: '此操作仅删除数据库中的pkg存储，后端相应目录结构请自行删除与数据库保持一致！',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await deletePackage({ packageName: record.packageName });
        if (res.code === 0) {
          message.success('删除成功');
          fetchTableData();
        }
      },
    });
  };

  // 自定义验证器
  const validatePackageName = (_: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入包名');
    }
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      return Promise.reject('不能为中文');
    }
    if (/^\d+$/.test(value[0])) {
      return Promise.reject('不能够以数字开头');
    }
    if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      return Promise.reject('只能包含英文字母、数字和下划线');
    }
    return Promise.resolve();
  };

  const columns = [
    { title: 'ID', dataIndex: 'ID', key: 'ID', width: 120 },
    { title: '包名', dataIndex: 'packageName', key: 'packageName', width: 150 },
    { title: '模板', dataIndex: 'template', key: 'template', width: 150 },
    { title: '展示名', dataIndex: 'label', key: 'label', width: 150 },
    { title: '描述', dataIndex: 'desc', key: 'desc' },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: PackageItem) => (
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record)}
        >
          删除
        </Button>
      ),
    },
  ];

  return (
    <PageContainer>
      <WarningBar
        title="模板package会创建集成于项目本体中的代码包，模板plugin会创建插件包"
        href="https://github.com/flipped-aurora/gin-vue-admin"
      />
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={openDrawer}>
          新增
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="ID"
        loading={loading}
        pagination={false}
      />
      <Drawer
        title="新增模板配置"
        width={500}
        open={drawerVisible}
        onClose={closeDrawer}
        extra={
          <Space>
            <Button onClick={closeDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="包名"
            name="packageName"
            rules={[{ validator: validatePackageName }]}
          >
            <Input placeholder="请输入包名" />
          </Form.Item>
          <Form.Item
            label="模板"
            name="template"
            rules={[{ required: true, message: '请选择模板' }]}
          >
            <Select placeholder="请选择模板">
              {templatesOptions.map((item) => (
                <Select.Option key={item} value={item}>
                  {item}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="展示名"
            name="label"
            rules={[{ required: true, message: '请输入展示名' }]}
          >
            <Input placeholder="请输入展示名" />
          </Form.Item>
          <Form.Item label="描述" name="desc">
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default AutoPkg;
