/** @format */

import * as React from 'react'
import { Form, Col, Row, Spin, InputNumber, Switch } from 'antd'
import message from '../../../components/message'
import { SelectValue } from 'antd/es/select'
import { FormComponentProps } from 'antd/es/form'
import Permission from '../../../components/AccessControl'
import Button from '../../../components/button'
import { decodeBase64 } from '../../../utils/base64'
import Filter from '../../../components/filters'
import {
  useMerchantDataApiToBaseApiList,
  useMerchantDataApiToBaseApiInfo,
  useUpdateMerchantDataApiToBaseApiinfo,
} from '../../../service/dataApi'
import Params from '../../../components/params'
import SourceSetUp from './components'
import Select from '../../../components/select/select'

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

interface Istate {
  baseApi?: number;
}

const interfaceSet: React.FC<FormComponentProps> = props => {
  const { form } = props

  const { getFieldDecorator, validateFieldsAndScroll, setFieldsValue, getFieldValue } = form
  const requestRef: any = React.useRef(null)
  const responseRef: any = React.useRef(null)
  const searchParams = new URLSearchParams(decodeBase64(location.search.substring(1)))
  const id = Number(searchParams.get('id'))
  const merchantId = Number(searchParams.get('merchantId'))
  const [state, setState] = React.useState<Istate>({})

  const [interfaceState, requestList] = useMerchantDataApiToBaseApiList(id)
  const [infoState, requestInfo] = useMerchantDataApiToBaseApiInfo()
  const [updateState, requestUpdate] = useUpdateMerchantDataApiToBaseApiinfo()
  React.useEffect(() => {
    if (interfaceState.dataSource.length > 0) {
      setState(preState => ({ ...preState, baseApi: interfaceState.dataSource[0].value }))
    }
  }, [interfaceState.dataSource])
  const handleChange = (value: SelectValue) => {
    setState(preState => ({ ...preState, baseApi: value as number }))
  }
  React.useEffect(() => {
    if (state.baseApi) {
      requestInfo(state.baseApi)
    }
  }, [state.baseApi])
  React.useEffect(() => {
    setFieldsValue({
      is_crypto: infoState.dataSource.is_crypto,
      reuse_time: infoState.dataSource.reuse_time,
      force_update: infoState.dataSource.force_update,
      is_raw_error_code: infoState.dataSource.is_raw_error_code,
      timeout: infoState.dataSource.timeout,
      rate_limit:infoState.dataSource.rate_limit,
      minimal_time_consuming: infoState.dataSource.minimal_time_consuming,
      random_percentage: infoState.dataSource.random_percentage,
      permission: {
        count_type: infoState.dataSource.count_type,
        count_code: infoState.dataSource.count_code,
      },
      request_param: infoState.dataSource.request_param || [],
      response_param: infoState.dataSource.response_param || [],
      filters: infoState.dataSource.filters,
      merchant_provider_group_list: infoState.dataSource.merchant_provider_group_list,
    })
  }, [infoState.dataSource])
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    validateFieldsAndScroll((error, values) => {
      if (error) return
      const request_param = requestRef.current.getParams()
      const response_param = responseRef.current.getParams()
      const {
        permission,
        is_crypto,
        reuse_time,
        force_update,
        timeout,
        filters,
        merchant_provider_group_list,
        minimal_time_consuming,
        random_percentage,
        is_raw_error_code,
        rate_limit,
      } = values
      requestUpdate({
        ...permission,
        merchant_provider_group_list,
        response_param,
        request_param,
        filters,
        timeout,
        is_raw_error_code: is_raw_error_code ? 1 : 0,
        reuse_time,
        is_crypto,
        rate_limit,
        force_update,
        merchant_child_api_id: state.baseApi,
        merchantId: merchantId,
        minimal_time_consuming,
        random_percentage
      }).then(error => {
        if (error) return message.error(error)
        message.success('更新成功!')
      })
    })
  }
  getFieldDecorator('filters', { initialValue: [] })

  const handleAddFilter = () => {
    const filters = getFieldValue('filters')
    setFieldsValue({
      filters: filters.concat({
        name: '',
        value: '',
        id: Date.now(),
      }),
    })
  }
  const handleChangeFilters = (values: any[]) => {
    setFieldsValue({
      filters: values,
    })
  }
  getFieldDecorator('response_param', { initialValue: [] })
  getFieldDecorator('request_param', { initialValue: [] })
  return (
    <Spin spinning={infoState.loading || updateState.loading}>
      <h3>接口信息</h3>
      <Select
        value={state.baseApi}
        loading={interfaceState.loading}
        placeholder="请选择接口"
        options={interfaceState.dataSource}
        onChange={handleChange}
        style={{ width: 300 }}
      />
      <Form {...formItemLayout} layout="horizontal" onSubmit={handleSubmit}>
        <Row>
          <h3>基本设置</h3>
          <Row>
            <Col span={8}>
              <Form.Item label="是否加密">
                {getFieldDecorator('is_crypto', {
                  initialValue: true,
                  valuePropName: 'checked',
                  rules: [
                    {
                      required: true,
                      message: 'Please input your E-mail!',
                    },
                  ],
                })(<Switch />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="复用时效(天)">
                {getFieldDecorator('reuse_time', {
                  initialValue: 0,
                  rules: [
                    {
                      required: true,
                      message: '请输入复用时效!',
                    },
                  ],
                })(<InputNumber placeholder="请输入复用时效" min={0} />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="最小耗时">
                {getFieldDecorator('minimal_time_consuming', {
                  initialValue: 0,
                  rules: [
                    {
                      required: true,
                      message: '请输入最小耗时!',
                    },
                    {
                      validator: (rule, value, cb) => {
                        if (value < 0) {
                          return cb("最小值为0")
                        }
                        cb()
                      }
                    }
                  ],
                })(<InputNumber placeholder="请输入最小耗时" min={0} />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <Form.Item label="是否强制更新">
                {getFieldDecorator('force_update', {
                  initialValue: true,
                  valuePropName: 'checked',

                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<Switch />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="超长时效(毫秒)">
                {getFieldDecorator('timeout', {
                  initialValue: 0,
                  rules: [
                    {
                      required: true,
                      message: '请输入超长时效!',
                    },
                  ],
                })(<InputNumber min={0} placeholder="请输入超长时效" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="随机百分比">
                {getFieldDecorator('random_percentage', {
                  initialValue: 0,
                  rules: [
                    {
                      required: true,
                      message: '请输入随机百分比!',
                    },
                    {
                      validator: (rule, value, cb) => {
                        if (value > 100) {
                          return cb("最大值为100")
                        }
                        if (value < 0) {
                          return cb("最小值为0")
                        }
                        cb()
                      }
                    }
                  ],
                })(<InputNumber placeholder="请输入随机百分比" min={0} />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="并发限制">
                {getFieldDecorator('rate_limit', {
                  initialValue: 0,
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<InputNumber min={0} placeholder="请输入并发限制" precision={0}/>)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="是否返回原始错误码">
                {getFieldDecorator('is_raw_error_code', {
                  valuePropName: 'checked',
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<Switch />)}
              </Form.Item>
            </Col>
            
          </Row>
          <Col span={22}>
            <Form.Item label="权限控制" labelCol={{ sm: { span: 3 } }} wrapperCol={{ sm: { span: 18 } }}>
              {getFieldDecorator('permission', {
                initialValue: { count_type: 0, count_code: '' },
                rules: [
                  {
                    required: true,
                    message: 'Please input your E-mail!',
                  },
                ],
              })(<Permission form={form} />)}
            </Form.Item>
          </Col>
        </Row>
        <h3>参数设置</h3>
        <h4>请求参数</h4>
        <Form.Item wrapperCol={{ sm: { span: 24 } }}>
          <Params
            ref={requestRef}
            value={getFieldValue('request_param')}
            isEditable={false}
            chooseAll
            requestType="request"
          />
        </Form.Item>
        {getFieldValue('request_param').length ? (
          <>
            <Button type="primary" onClick={handleAddFilter}>
              添加过滤规则
            </Button>
            <Form.Item labelCol={{ sm: { span: 0 } }} wrapperCol={{ sm: { span: 24 } }}>
              <Filter
                form={form}
                value={getFieldValue('filters')}
                onChange={handleChangeFilters}
                options={infoState.dataSource.request_param.map(element => {
                  return {
                    key: element.id,
                    label: element.name,
                    value: element.name,
                  }
                })}
              />
            </Form.Item>
          </>
        ) : null}
        <h4>响应参数</h4>
        <Form.Item wrapperCol={{ sm: { span: 24 } }}>
          <Params
            ref={responseRef}
            value={getFieldValue('response_param')}
            chooseAll
            isEditable={false}
            requestType="response"
          />
        </Form.Item>
        <h3>数据源设置</h3>
        <Form.Item wrapperCol={{ sm: { span: 24 } }}>
          {getFieldDecorator('merchant_provider_group_list')(<SourceSetUp isMove={false} />)}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </Form>
    </Spin>
  )
}

export default Form.create<FormComponentProps>({ name: 'interfaceSet' })(interfaceSet)
