/** @format */

import * as React from 'react';

import {Form, Row,Input as AntdInput, Col, Transfer, Spin} from 'antd';
import {FormComponentProps} from 'antd/es/form';
import {GetFieldDecoratorOptions} from "antd/es/form/Form"
import {pathPattern} from "../../../../const/regular"

import {defaultCheckedErrorCode} from '../../../../const/status';
import Input from "../../../../components/input"
import Params from '../../../../components/params';
import SelectMethod from '../../../../components/select/method';
import SelectInterfaceType from '../../../../components/select/interfaceType';
import Button from '../../../../components/button';
import {useErrorCodeList} from '../../../../service/errorCode';


const formItemLayout = {
    labelCol: {
        sm: {span: 3},
        lg:{span:4},
        xxl:{span:3}
    },
    wrapperCol: {
        sm: {span: 21},
        lg: {span:20},
        xxl:{span:21}

    },
};
interface formColumnsChildProps extends GetFieldDecoratorOptions{
  key:string;
  label:string|null;
  Component:React.ReactNode
}
interface formColumnsProps {
  title:string|null;
  child:formColumnsChildProps[]
}


export interface InterfaceFormData {
    comment?: string;
    error_code?: string[];
    method?: string;
    name?: string;
    request_param?: any[];
    response_param?: any[];
    router?: string;
    type?: number;
}

interface Iprops {
    onSubmit: (values: InterfaceFormData) => void;
    values?: InterfaceFormData;
    loading: boolean;
}

const editInterface: React.FC<Iprops & FormComponentProps> = props => {
    const {form, onSubmit, loading=false, values} = props;
    const requestRef:any=React.useRef(null);
    const responseRef:any=React.useRef(null)
    const {getFieldDecorator, validateFieldsAndScroll} = form;
    const [errorCodeState] = useErrorCodeList();
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        validateFieldsAndScroll((error, values) => {
            if (!error) {
              const request_param =requestRef.current.getParams();
              const response_param=responseRef.current.getParams();
              onSubmit({
                ...values,
                error_code:values.error_code.map(element=>Number(element)),
                request_param,
                response_param
              });
            }
        });
    };
    
    const formColumns=React.useMemo(()=>{
      const columns:formColumnsProps[] = [
        {
            title: '基本信息',
            child: [
                {
                    label: '接口名称',
                    key: 'name',
                    Component: <Input placeholder='请输入接口名称!' />,
                    initialValue:values?.name||"",
                    rules: [
                        {
                            required: true,
                            message: '请输入接口名称!',
                        },
                    ],
                },
                {
                    label: '接口路径',
                    initialValue: values?.router||"",
                    key: 'router',
                    Component: <Input placeholder='请输入接口路径!' />,
                    rules: [
                        {
                            required: true,
                            message: '请输入接口路径!',
                        },
                        {
                          pattern:pathPattern,
                          message:"路径格式应当位'/path'"
                        }
                    ],
                },
                {
                    label: '请求方式',
                    initialValue: values?.method,
                    key: 'method',
                    Component: <SelectMethod placeholder='请选择请求方式!' />,
                    rules: [
                        {
                            required: true,
                            message: '请选择请求方式!',
                        },
                    ],
                },
                {
                    label: '类型',
                    key: 'type',
                    initialValue: values?.type,
                    Component: <SelectInterfaceType placeholder='请选择类型!' />,
                    rules: [
                        {
                            required: true,
                            message: '请选择类型!',
                        },
                    ],
                },
            ],
        },
        {
            title: '错误码设置',
            child: [
                {
                    label: '',
                    key: 'error_code',
                    rules: [],
                    initialValue:( values?.error_code||defaultCheckedErrorCode).map(element=>String(element)),
                    valuePropName: 'targetKeys',
                    Component: (
                        <Transfer
                            render={item => item.title}
                            listStyle={{
                                width: 400,
                                height: 400,
                            }}
                            showSearch
                            locale={{itemUnit: '项', itemsUnit: '项', searchPlaceholder: '请输入搜索内容'}}
                            dataSource={errorCodeState.dataSource.map(element=>({...element,key:String(element.key),title:element.label}))}
                            titles={['未设置', '已设置']}
                        />
                    ),
                },
            ],
        },
    ];
      return columns
    },[values,errorCodeState])
    return (
      <Spin spinning={loading}>     
        <Form {...formItemLayout} style={{padding: '0 15px'}} onSubmit={handleSubmit}>
            {formColumns.map((element, index) => {
                const {child = []} = element;
                return (
                    <Row key={index} gutter={24}>
                        <h3>{element.title}</h3>
                        {child.map((item) => {
                            const {label, key, Component, ...rest} = item;
                            const isOnly = element.child.length === 1;
                            return (
                                <Col span={isOnly ? 24 : 12} key={key}>
                                    <Form.Item label={label} wrapperCol={isOnly ? {sm: 24} : {sm: 21}}>
                                        {getFieldDecorator(key, rest)(Component)}
                                    </Form.Item>
                                </Col>
                            );
                        })}
                    </Row>
                );
            })}
             
             <h3>参数设置</h3>
             <h4>请求参数</h4>
              <Form.Item  wrapperCol={{sm:{span:24}}}>
                 <Params ref={requestRef} isEditable value={values?.request_param||[]} />
              </Form.Item>
              <h4>响应参数</h4>
              <Form.Item  wrapperCol={{sm:{span:24}}}>
                  <Params ref={responseRef}  isEditable value={values?.response_param||[]}  requestType='response' />
              </Form.Item>
            <h3>备注信息</h3>
            <Form.Item  wrapperCol={{sm:{span:24}}}>
              {
                getFieldDecorator("comment",{
                  initialValue: values?.comment||"",
                })(<AntdInput.TextArea rows={4} style={{resize: 'none'}} />)
              }
            </Form.Item>
            <Form.Item>
                <Button type='primary' htmlType='submit' loading={loading}>
                    保存
                </Button>
            </Form.Item>
        </Form>
        </Spin>
    );
};
export default Form.create<Iprops & FormComponentProps>({
    name: 'editInterface',
})(editInterface);
