import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Form, Input, message, Modal, Select, Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import Edit from '@/pages/ParameterConfiguration/edit';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import {
  delParameters,
  disableParameters,
  enableParameters,
  queryParameters,
} from '@/services/ParameterConfiguration';

interface DataType {
  code: string;
  name: string;
  value: string;
  status: number;
  memo: string;
  record_id: string;
}

const ParameterConfiguration: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [dataList, setDataList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [params, setParams] = useState(null);
  const [searchData, setSearchData] = useState<object | null>({});

  const getList = () => {
    const data = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryParameters(data).then((res) => {
      if (res.code === 0) {
        setDataList(res.data.list);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    setLoading(true);
    getList();
  }, []);

  // 查询
  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      setSearchData(data);
    });
  };

  useEffect(() => {
    getList();
  }, [searchData]);

  // 重置
  const onReset = () => {
    form.resetFields();
    setLoading(true);
    setSearchData(null);
  };

  // 切换列表
  const tableChange = () => {
    setLoading(true);
    const data = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryParameters(data).then((res) => {
      if (res.code === 0) {
        setDataList(res.data.list);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 新增
  const onAdd = () => {
    setVisible(true);
  };

  // 编辑
  const toEdit = (record: any) => {
    setVisible(true);
    setParams(record);
  };

  // 删除
  const toDel = (record: DataType) => {
    Modal.confirm({
      title: '删除',
      content: `是否确认删除?`,
      onOk: () => {
        delParameters(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('删除成功');
            } else {
              message.error('删除失败');
            }
            getList();
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  // 弹框回调
  const editCallback = () => {
    setVisible(false);
    getList();
  };

  // 启用
  const toEnable = (record: DataType) => {
    Modal.confirm({
      content: `是否确认启用参数配置?`,
      onOk: () => {
        enableParameters(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('启用成功');
              getList();
            } else {
              message.error('启用失败');
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  // 禁用
  const toDisable = (record: DataType) => {
    Modal.confirm({
      content: `是否确认禁用参数配置?`,
      onOk: () => {
        disableParameters(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('禁用成功');
              getList();
            } else {
              message.error('禁用失败');
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'version',
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v) => v && <span>{{ 1: '启用', 2: '禁用' }[v]}</span>,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      key: 'memo',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              toDel(record);
            }}
          >
            删除
          </a>
          {record.status === 1 && (
            <a
              style={{ color: 'red' }}
              onClick={() => {
                toDisable(record);
              }}
            >
              禁用
            </a>
          )}
          {record.status === 2 && (
            <a
              onClick={() => {
                toEnable(record);
              }}
            >
              启用
            </a>
          )}
        </Space>
      ),
    },
  ];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => {
      return <span> 共 {total}条 </span>;
    },
    ...pagination,
  };

  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="like_name" label="名称">
              <Input placeholder="请输入名称" />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择状态" style={{ width: '175px' }}>
                <Select.Option value={1} key={1}>
                  启用
                </Select.Option>
                <Select.Option value={2} key={2}>
                  禁用
                </Select.Option>
              </Select>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  <ReloadOutlined />
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Button type="primary" onClick={onAdd} style={{ margin: '20px 0' }}>
            新增
          </Button>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            pagination={paginationProps}
            loading={loading}
            onChange={tableChange}
          />
          {visible && <Edit editCallback={editCallback} params={params} visible={visible} />}
        </Card>
      </div>
    </PageContainer>
  );
};
export default ParameterConfiguration;
