import {
  ProCard,
  ProForm,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form, Space, Tabs, TabsProps, message } from 'antd';
import { useEffect, useState } from 'react';
import { ConfigurationController } from '../../services';
import { sessionStore } from '../../utils/store';
import ImgForm from './ImgForm';

type ConfigValueProps = Record<string, any>;

interface TabItemProps {
  defaultConfigValue: ConfigValueProps;
  onSubmit: (configs: ConfigValueProps) => void;
}

const Login: React.FC<TabItemProps> = ({ defaultConfigValue, onSubmit }) => {
  const [configValue, setConfigValue] =
    useState<ConfigValueProps>(defaultConfigValue);
  const [form] = ProForm.useForm<ConfigValueProps>();
  useEffect(() => {
    setConfigValue({ ...defaultConfigValue });
    form.setFieldsValue({ ...defaultConfigValue });
  }, [defaultConfigValue, form]);
  return (
    <ProForm<Record<string, any>>
      form={form}
      labelCol={{ flex: '200px' }}
      labelAlign="right"
      layout="horizontal"
      autoFocusFirstInput
      submitter={false}
    >
      <>
        <ProFormText width="lg" name="platformName" label="系统名称" />

        <Form.Item
          name="loginBgImg"
          label="背景图"
          labelAlign="right"
          labelCol={{ flex: '200px' }}
        >
          <ImgForm
            url={configValue.loginBgImg}
            onChange={(loginBgImg = '') => {
              setConfigValue((prev) => ({ ...prev, loginBgImg }));
            }}
          />
        </Form.Item>
        <ProFormRadio.Group
          label="背景图启用状态"
          name="isShowLoginBgImg"
          initialValue="y"
          options={[
            { label: '是', value: 'y' },
            { label: '否', value: 'n' },
          ]}
        />
        <Form.Item
          name="loginImg"
          label="主图"
          labelAlign="right"
          labelCol={{ flex: '200px' }}
        >
          <ImgForm
            url={configValue.loginImg}
            onChange={(loginImg = '') => {
              setConfigValue((prev) => ({ ...prev, loginImg }));
            }}
          />
        </Form.Item>
        <ProFormRadio.Group
          label="主图启用状态"
          name="isShowLoginImg"
          initialValue="y"
          options={[
            { label: '是', value: 'y' },
            { label: '否', value: 'n' },
          ]}
        />
        <Form.Item
          name="loginLogoImg"
          label="logo"
          labelAlign="right"
          labelCol={{ flex: '200px' }}
        >
          <ImgForm
            url={configValue.loginLogoImg}
            onChange={(loginLogoImg = '') => {
              setConfigValue((prev) => ({
                ...prev,
                loginLogoImg,
              }));
            }}
          />
        </Form.Item>

        <ProFormRadio.Group
          label="logo启用状态"
          name="isShowLoginLogoImg"
          initialValue="y"
          options={[
            { label: '是', value: 'y' },
            { label: '否', value: 'n' },
          ]}
        />
      </>
      <Space style={{ marginLeft: '200px' }}>
        <Button
          type="primary"
          onClick={async () => {
            const { loginBgImg, loginImg, loginLogoImg } = configValue;
            const values = await form.validateFields();
            onSubmit({
              ...values,
              loginBgImg,
              loginImg,
              loginLogoImg,
            });
          }}
        >
          保存
        </Button>
        <Button
          onClick={() => {
            setConfigValue({ ...defaultConfigValue });
            form.setFieldsValue({ ...defaultConfigValue });
          }}
        >
          重置
        </Button>
      </Space>
    </ProForm>
  );
};

const CasLogin: React.FC<TabItemProps> = ({ defaultConfigValue, onSubmit }) => {
  const [form] = ProForm.useForm<ConfigValueProps>();
  useEffect(() => {
    form.setFieldsValue({ ...defaultConfigValue });
  }, [defaultConfigValue, form]);
  return (
    <ProForm<Record<string, any>>
      form={form}
      labelCol={{ flex: '200px' }}
      labelAlign="right"
      layout="horizontal"
      autoFocusFirstInput
      submitter={false}
    >
      <>
        <ProFormText width="lg" name="casLoginUrl" label="登录地址" />
        <ProFormText width="lg" name="casLogoutUrl" label="退出登录地址" />
        <ProFormText width="lg" name="casService" label="服务地址" />
        <ProFormText width="lg" name="casSysUuid" label="sys_uuid" />
        <ProFormRadio.Group
          label="单点登录开启状态"
          name="isCasOpen"
          initialValue="n"
          options={[
            { label: '是', value: 'y' },
            { label: '否', value: 'n' },
          ]}
        />
      </>
      <Space style={{ marginLeft: '200px' }}>
        <Button
          type="primary"
          onClick={async () => {
            const values = await form.validateFields();
            onSubmit({
              ...values,
            });
          }}
        >
          保存
        </Button>
        <Button
          onClick={() => {
            form.setFieldsValue({ ...defaultConfigValue });
          }}
        >
          重置
        </Button>
      </Space>
    </ProForm>
  );
};
const Area: React.FC<TabItemProps> = ({ defaultConfigValue, onSubmit }) => {
  const [form] = ProForm.useForm<ConfigValueProps>();
  useEffect(() => {
    form.setFieldsValue({ ...defaultConfigValue });
  }, [defaultConfigValue, form]);

  return (
    <ProForm<Record<string, any>>
      form={form}
      labelCol={{ flex: '200px' }}
      labelAlign="right"
      layout="horizontal"
      autoFocusFirstInput
      submitter={false}
    >
      <>
        <ProFormText width="lg" name="areaCode" label="编码" />
        <ProFormText width="lg" name="areaName" label="名称" />
        <ProFormText width="lg" name="areaNameEN" label="英文名称" />
      </>
      <Space style={{ marginLeft: '200px' }}>
        <Button
          type="primary"
          onClick={async () => {
            const values = await form.validateFields();
            onSubmit({
              ...values,
            });
          }}
        >
          保存
        </Button>
        <Button
          onClick={() => {
            form.setFieldsValue({ ...defaultConfigValue });
          }}
        >
          重置
        </Button>
      </Space>
    </ProForm>
  );
};

const Header: React.FC<TabItemProps> = ({ defaultConfigValue, onSubmit }) => {
  const [configValue, setConfigValue] =
    useState<ConfigValueProps>(defaultConfigValue);
  const [form] = ProForm.useForm<ConfigValueProps>();
  useEffect(() => {
    form.setFieldsValue({ ...defaultConfigValue });
  }, [defaultConfigValue, form]);

  return (
    <ProForm<Record<string, any>>
      form={form}
      labelCol={{ flex: '200px' }}
      labelAlign="right"
      layout="horizontal"
      autoFocusFirstInput
      submitter={false}
    >
      <Form.Item
        name="logoImage"
        label="logo"
        labelAlign="right"
        labelCol={{ flex: '200px' }}
      >
        <ImgForm
          url={configValue.logoImage}
          onChange={(logoImage = '') => {
            setConfigValue((prev) => ({ ...prev, logoImage }));
          }}
        />
      </Form.Item>
      <ProFormRadio.Group
        label="logo显示状态"
        name="logoStatus"
        initialValue="y"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />
      <ProFormText width="lg" name="title" label="标题" />

      <ProFormRadio.Group
        label="显示分组名为标题"
        name="groupTitleStatus"
        initialValue="y"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />

      <ProFormRadio.Group
        label="标题显示状态"
        name="titleStatus"
        initialValue="y"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />

      <ProFormRadio.Group
        label="首页操作显示状态"
        name="homeBtnStatus"
        initialValue="n"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />

      <ProFormRadio.Group
        label="首页操作显示状态"
        name="homeBtnStatus"
        initialValue="n"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />
      <ProFormRadio.Group
        label="消息通知操作显示状态"
        name="messageBtnStatus"
        initialValue="n"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />
      <ProFormRadio.Group
        label="退出登录操作显示状态"
        name="logoutBtnStatus"
        initialValue="y"
        options={[
          { label: '是', value: 'y' },
          { label: '否', value: 'n' },
        ]}
      />
      <Space style={{ marginLeft: '200px' }}>
        <Button
          type="primary"
          onClick={async () => {
            const values = await form.validateFields();
            onSubmit({
              ...values,
            });
          }}
        >
          保存
        </Button>
        <Button
          onClick={() => {
            form.setFieldsValue({ ...defaultConfigValue });
          }}
        >
          重置
        </Button>
      </Space>
    </ProForm>
  );
};

const Watermark: React.FC<TabItemProps> = ({
  defaultConfigValue,
  onSubmit,
}) => {
  const [configValue, setConfigValue] =
    useState<ConfigValueProps>(defaultConfigValue);
  const [form] = ProForm.useForm<ConfigValueProps>();
  useEffect(() => {
    setConfigValue({ ...defaultConfigValue });
    form.setFieldsValue({ ...defaultConfigValue });
  }, [defaultConfigValue, form]);

  return (
    <ProForm<Record<string, any>>
      form={form}
      labelCol={{ flex: '200px' }}
      labelAlign="right"
      layout="horizontal"
      autoFocusFirstInput
      submitter={false}
    >
      <>
        <ProFormTextArea
          width="lg"
          name="waterParams"
          label="水印参数"
          tooltip="水印参数中的content存在有值时则展示该值，否则展示用户名和机构名。"
          fieldProps={{
            style: { height: 200 },
          }}
          placeholder="请输入水印参数，多个参数请每行填写一条，可设置的参数：width、height、rotate、color、size、opacity、content。"
        />
        <ProFormRadio.Group
          label="水印开启状态"
          name="waterStatus"
          initialValue="y"
          options={[
            { label: '是', value: 'y' },
            { label: '否', value: 'n' },
          ]}
        />
      </>
      <Space style={{ marginLeft: '200px' }}>
        <Button
          type="primary"
          onClick={async () => {
            const { logoImg } = configValue;
            const values = await form.validateFields();
            onSubmit({
              ...values,
              logoImg,
            });
          }}
        >
          保存
        </Button>
        <Button
          onClick={() => {
            setConfigValue({ ...defaultConfigValue });
            form.setFieldsValue({ ...defaultConfigValue });
          }}
        >
          重置
        </Button>
      </Space>
    </ProForm>
  );
};

export default () => {
  const systemConfig: ConfigurationController.SystemConfigFields =
    sessionStore.get('system-config') || {};
  const [configSourceValue, setConfigSourceValue] = useState<ConfigValueProps>(
    JSON.parse(systemConfig.configValue || '{}'),
  );

  const onSubmit = async (configs: ConfigValueProps) => {
    const saveConfigs = { ...configSourceValue, ...configs };
    const params = {
      ...systemConfig,
      configValue: JSON.stringify(saveConfigs),
    };
    await ConfigurationController.updateApi(params);
    setConfigSourceValue(saveConfigs);
    sessionStore.set('system-config', params);
    message.success('保存成功！');
  };
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `系统登录`,
      children: (
        <Login defaultConfigValue={configSourceValue} onSubmit={onSubmit} />
      ),
    },
    {
      key: '2',
      label: `单点登录`,
      children: (
        <CasLogin defaultConfigValue={configSourceValue} onSubmit={onSubmit} />
      ),
    },
    {
      key: '3',
      label: `区域信息`,
      children: (
        <Area defaultConfigValue={configSourceValue} onSubmit={onSubmit} />
      ),
    },
    {
      key: '4',
      label: `顶部配置`,
      children: (
        <Header defaultConfigValue={configSourceValue} onSubmit={onSubmit} />
      ),
    },
    {
      key: '9',
      label: `水印配置`,
      children: (
        <Watermark defaultConfigValue={configSourceValue} onSubmit={onSubmit} />
      ),
    },
  ];
  return (
    <ProCard>
      <Tabs defaultActiveKey="1" items={items} destroyInactiveTabPane />
    </ProCard>
  );
};
