/** @format */

import * as React from 'react';

import {Form, Input, InputNumber, Row, Col, Switch} from 'antd';
import Button from "../../../../components/button"
import Result from "../../../../components/result"
import {FormComponentProps} from 'antd/es/form';
import AccessControl from './accessControl';
import SourceToMerchant from './merchantInfo';
import ModalForm from '../../../../components/modalForm';
import MethodSelectComponent from '../../../../components/select/method';
import Filters from "../../../../components/filters"
import {useProvideApiMerchant} from '../../../../service/provideApi';

const formItemLayout = {
    labelCol: {
        sm: {span: 5},
    },
    wrapperCol: {
        sm: {span: 18},
    },
};

export interface UpdateAPiProps {
  threshold_timeout: number;
  threshold_fail_rate: number;
  threshold_norecord_rate: number;
  warning_enable: boolean;
  thirdpart_api_name: string;
  provider_api_code: string;
  thirdpart_host: string;
  thirdpart_api_router: string;
  thirdpart_api_method: string;
  count_type: number;
  count_key: string;
  count_value: string;
  cost: String;
  count: number;
  state: number;
  create_time: string;
  provider_api_id: number;
  id:number
  filters:any[]
  timeout:number
}
interface ApiSetProps {
    values?: UpdateAPiProps;
    visible?: boolean;
    title?: string;
    onCancel?: () => void;
    onSubmit?: (values:UpdateAPiProps) => void;
    loading?:boolean
    type?:"insert"|"update"
}
const ApiSet: React.FC<ApiSetProps & FormComponentProps> = props => {
    const {values, visible, loading=false,title, onCancel,type="insert", form,onSubmit} = props;
    const {getFieldDecorator,getFieldValue,validateFieldsAndScroll,setFieldsValue} = form;
    const [merchantState, requestMerchant] = useProvideApiMerchant();
        //获取数据源平台的商户信息

    React.useEffect(()=>{
      handleRetry()
    },[values?.id])

    const handleRetry=()=>{
      if(values&&values.id){
        requestMerchant(values.id)
      }
    }
    //验证 商户配额
    const validateMerchantLimit=(rule:any, value:any[], callback:any)=>{
      const dayTotalLimit =  getFieldValue("count")
      const currentTotal=value.reduce((pre,next)=>{
        return pre+next.inventory
      },0)
      if(currentTotal>dayTotalLimit){
         return callback(`商户总限额不能大于日调用量上限(${dayTotalLimit})`)
      }
      callback()
    }

    const handleSubmit=()=>{
      validateFieldsAndScroll((error,values)=>{
        if(error) return;
        const {permission:{count_code,count_type,count_value},state,...rest}=values
        onSubmit && onSubmit({
          ...rest,
          state:state?1:0,
          count_type,
          count_value,
          count_key:count_code
        })
      })
    }
    const handleAddRule=()=>{
      const filters=getFieldValue("filters")
      setFieldsValue({
        filters:filters.concat({
          name:"",
          value:"",
          id:Date.now()
        })
      })

    }
    React.useEffect(()=>{
      setFieldsValue({
        "provider_merchant_api_list":merchantState.dataSource
      })
    },[merchantState.dataSource])
    
    const formColumns = React.useMemo(() => {
        const columns = [
            {
                title: '基本信息',
                child: [
                    {
                        label: '接口',
                        Component: <Input placeholder="请输入接口名" />,
                        key: 'thirdpart_api_name',
                        initialValue:values?.thirdpart_api_name,
                        rules: [
                            {
                                required: true,
                                message: '请输入接口名!',
                            },
                        ],
                    },
                    {
                        label: '接口代码',
                        Component: <Input placeholder="请输入接口代码" />,
                        key: 'provider_api_code',
                        initialValue:values?.provider_api_code,
                        rules: [
                            {
                                required: true,
                                message: '请输入接口代码!',
                            },
                        ],
                    },
                    {
                        label: '接口域名',
                        Component: <Input placeholder="请输入接口域名" />,
                        key: 'thirdpart_host',
                        initialValue:values?.thirdpart_host,

                        rules: [
                            {
                                required: true,
                                message: '请输入接口域名!',
                            },
                        ],
                    },
                    {
                        label: '接口路径',
                        Component: <Input placeholder="请输入接口路径" />,
                        key: 'thirdpart_api_router',
                        initialValue:values?.thirdpart_api_router,

                        rules: [
                            {
                                required: true,
                                message: '请输入接口路径!',
                            },
                        ],
                    },
                    {
                        label: '接口方法',
                        Component: <MethodSelectComponent placeholder="请选择接口方法" />,
                        key: 'thirdpart_api_method',
                        initialValue:values?.thirdpart_api_method,

                        rules: [
                            {
                                required: true,
                                message: '请选择接口方法!',
                            },
                        ],
                    },
                    {
                        label: '接口单价(￥)',
                        Component: <InputNumber placeholder="请输入接口单价" style={{width: '100%'}} min={0} />,
                        key: 'cost',
                        initialValue:values?.cost,

                    },
                    {
                        label: '日调用上限',
                        Component: <InputNumber placeholder="请输入日调用上限" style={{width: '100%'}} min={0} />,
                        key: 'count',
                        initialValue:values?.count||0,
                      
                    },
                    {
                        label: '是否启用',
                        valuePropName: 'checked',
                        Component: <Switch />,
                        initialValue:values?.state===1?true:false,
                        key: 'state',
                    },
                    {
                      label: '超时时长',
                      Component: <InputNumber style={{width:200}} placeholder="请设置超时时长!" />,
                      initialValue:values?.timeout,
                      key: 'timeout',
                      
                  },
                   
                ],
            },
        ];
        return columns;
    }, [values]);
    
    return (
        <ModalForm
            title={title}
            width={1000}
            onCancel={onCancel}
            loading={loading}
            visible={visible}
            onOk={handleSubmit}
            
        >
            <Form {...formItemLayout}>
                {formColumns.map((item, index) => {
                    return (
                        <div key={index}>
                            <h3>{item.title}</h3>
                            <Row gutter={24}>
                                {item.child.map((element) => {
                                    const {Component, label, key, ...rest} = element;
                                    return (
                                      <Col span={12} key={key}>
                                        <Form.Item label={label}>
                                            {getFieldDecorator(key, rest)(Component)}
                                        </Form.Item>
                                      </Col>
                                    )
                                })}
                            </Row>
                        </div>
                    );
                })}
                {
                  <Form.Item label="权限控制" labelCol={{sm:{span:3}}} wrapperCol={{sm:{span:21}}}>
                    {getFieldDecorator("permission",{
                      initialValue:{
                        count_type: values?.count_type||0,
                        count_code: values?.count_key||"",
                        count_value: values?.count_value||"",
                      }
                    })(<AccessControl  form={form} />)}
                  </Form.Item>
                }
              <Button type="primary" onClick={handleAddRule}>添加过滤规则</Button>
               <Form.Item  wrapperCol={{sm:{span:24}}}>
                    {getFieldDecorator("filters",{
                      initialValue:values?.filters||[]
                    })(<Filters form={form} type="input" rule={false}></Filters>)}
                  </Form.Item>
                
            </Form>
            {
              type==="update" ?
              <Form.Item>
              {
                  getFieldDecorator("provider_merchant_api_list",{
                    initialValue:[],
                    rules:[{
                      validator:validateMerchantLimit
                    }]
                  })(
                    <SourceToMerchant 
                      max={getFieldValue("count")} 
                      loading={merchantState.loading} 
                    />
                  )
              }
              </Form.Item>
              :null
            }
        </ModalForm>
    );
};
export default Form.create<ApiSetProps & FormComponentProps>({name: 'apiSet'})(ApiSet);
