/** @format */

import * as React from 'react';
import { Popconfirm, Collapse, Icon, Row, Col, Form, Spin,Empty,notification} from 'antd';

import {decodeBase64} from '../../../../utils/base64';
import Result from '../../../../components/result';
import message from '../../../../components/message';
import CreateSourceForm from './components/createSourceForm';
import Button from '../../../../components/button';
import Input from "../../../../components/input"

import {useInterfaceSourceList, useUpdateInterfaceByProvideApi, ProvideApiRecordProps,GroupProps} from '../../../../service/interface';
import Table from '../../../../components/table';
import {FormComponentProps} from 'antd/lib/form';
const {Panel} = Collapse;


interface ModalState {
    visible: boolean;
    targetKeys?: number[];
    id?: number;
}
const Source: React.FC<FormComponentProps> = props => {
    const search=new URLSearchParams(decodeBase64(location.search.slice(1)))
    const id = search.get("id")
    const name=search.get("name")

    const {form} = props;
    const {getFieldDecorator, validateFieldsAndScroll, getFieldValue,getFieldsValue, setFieldsValue} = form;

    const [modalState, setModalState] = React.useState<ModalState>({
        visible: false,
    });
    const [interfaceSourceListState, requestSourceList] = useInterfaceSourceList(Number(id))
    const [putState, requestPut] = useUpdateInterfaceByProvideApi();
  
    const handleUpdateModalVisible = (visible = false, record?: GroupProps) => {
        setModalState(preState => ({...preState, visible: visible,id:record?.id, targetKeys:record?.provider_api_list.map(element=>{
          return element.id
        })}));
    };
    //新增组
    const handleAddGroup = () => {
        const dataSource = getFieldValue('dataSource');
        setFieldsValue({
            dataSource: dataSource.concat({
                id: Date.now(),
                provider_api_list: [],
                group_name: '',
            }),
        });
    };
    //对某个组新增数据源Api
    const handleCreate = (values:any[]) => {
        const dataSource = getFieldValue('dataSource');
        setFieldsValue({
            dataSource: dataSource.map((element: GroupProps) => {
                if (element.id === modalState.id) {
                    return {
                        ...element,
                        provider_api_list: values.map((item, index) => ({
                            ...item,
                            parentId:modalState.id,
                            priority: index + 1,
                        })),
                    };
                }
                return element;
            }),
        });
        handleUpdateModalVisible(false)
    };
    //删除组
    const handleDeleteGroup=(record:GroupProps)=>{
      const dataSource = getFieldValue('dataSource');
      setFieldsValue({
        dataSource: dataSource.filter((element: GroupProps) => element.id !== record.id),
     });
    }
    //删除组里面的某一项
    const handleDeleteProvideApiRecord=(group:GroupProps,record:ProvideApiRecordProps)=>{
      const dataSource = getFieldValue('dataSource');
      setFieldsValue({
          dataSource: dataSource.map((element: GroupProps) => {
              if (element.id === group.id) {
                  return {
                      ...element,
                      provider_api_list: element.provider_api_list.filter(item=>item.id!==record.id)
                  };
              }
              return element;
          }),
      });
    }
    //提交数据
    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        validateFieldsAndScroll({first: true}, (error, values) => {
            if (error) return;
            const dataSource = getFieldValue('dataSource');
            const data =  dataSource.map((element:GroupProps)=>{
              return {
                group_no:element.group_no,
                group_name:values[element.id],
                provider_api_id_list:element.provider_api_list.map(item=>item.id)
              }
            })
            requestPut({
              data,
              id:Number(id)
          }).then(error => {
              if (error) {
                return notification.error({
                  message:`${name}数据源更新失败`,
                  description:error
                })
              }
              return message.success(`${name}数据源更新成功`)
          });
        });
      
    };
  
    getFieldDecorator('dataSource', {
        initialValue: [],
    });
    React.useEffect(() => {
        setFieldsValue({
            dataSource: interfaceSourceListState.dataSource,
        });
    }, [interfaceSourceListState.dataSource]);
    const dataSource=getFieldValue('dataSource');

    const handleMoveChild=(record:ProvideApiRecordProps,move:"up"|"down")=>{
      setFieldsValue({
        dataSource:dataSource.map((element:GroupProps)=>{
          if(element.id===record.parentId){
            let currentIndex=-1;
            element.provider_api_list.forEach((item,index)=>{
                if(item.id===record.id){
                  currentIndex=index;
                }
            })
            if(move==="up"){
              element.provider_api_list.splice(currentIndex-1,0, ...element.provider_api_list.splice(currentIndex,1))
            }else{
              element.provider_api_list.splice(currentIndex+1,0, ...element.provider_api_list.splice(currentIndex,1))
            }
          }
          return element
        })
      }) 
    }
    const handleMoveGroup=(record:GroupProps,type:"down"|"up")=>{
      let willMoveIndex=-1;
      dataSource.forEach((element:GroupProps,index:number)=>{
        if(element.id===record.id){
          willMoveIndex=index;
        }
      })
      const copyData=dataSource.slice()
      if(type==="down"){
        copyData.splice(willMoveIndex+1,0,...copyData.splice(willMoveIndex,1))
      }else{
        copyData.splice(willMoveIndex,0,...copyData.splice(willMoveIndex-1,1))
      }
      setFieldsValue({
        dataSource:copyData
      })
    }
    return (
        <Spin spinning={interfaceSourceListState.loading}>
            <Result error={interfaceSourceListState.error} onRetry={() => requestSourceList()}>
                <Row style={{textAlign: 'right'}}>
                    <Button type='primary' onClick={handleAddGroup} style={{marginBottom: 15}}>
                        添加组
                    </Button>
                </Row>
                {
                  !dataSource.length
                  ?<Empty></Empty>
                  :
                <Form onSubmit={handleSubmit}>
                    <Collapse
                        accordion
                        expandIcon={({isActive}) => <Icon type='caret-right' rotate={isActive ? 90 : 0} />}
                        expandIconPosition='left'
                        defaultActiveKey={[dataSource[0].id]}
                    >
                        {dataSource.map((element: GroupProps, index: number) => {
                            const disabledMoveUp = index === 0;
                            const disabledMoveDown = index === dataSource.length - 1;
                            return (
                                <Panel
                                    key={element.id}
                                    header={
                                        <Row
                                            type='flex'
                                            justify='space-between'
                                            align='middle'
                                            onClick={event => event.stopPropagation()}
                                        >
                                            <Col xxl={5} lg={7}>
                                                <Form.Item style={{marginBottom: 0}}>
                                                    {getFieldDecorator(element.id.toString(), {
                                                        initialValue: element.group_name,
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '请设置类目别名!',
                                                            },
                                                         
                                                        ],
                                                    })(
                                                        <Input
                                                            size='small'
                                                            style={{width: 200}}
                                                            addonBefore='类目'
                                                            placeholder='请设置类目别名'
                                                        />,
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col  xl={9}  xxl={6} >
                                                <Button
                                                    type='primary'
                                                    icon='plus'
                                                    size='small'
                                                    onClick={() => handleUpdateModalVisible(true, element)}
                                                >
                                                    添加数据源接口
                                                </Button>
                                                <Button
                                                    style={{marginLeft: 15, marginRight: 15}}
                                                    type='primary'
                                                    size='small'
                                                    onClick={()=>handleMoveGroup(element,"up")}
                                                    disabled={disabledMoveUp}
                                                >
                                                    上移
                                                </Button>
                                                <Button
                                                    style={{marginRight: 15}}
                                                    type='primary'
                                                    size='small'
                                                    disabled={disabledMoveDown}
                                                    onClick={()=>handleMoveGroup(element,"down")}

                                                >
                                                    下移
                                                </Button>
                                                <Popconfirm
                                                    title={`确认删除-${element.group_name}!`}
                                                    okText='确认'
                                                    cancelText='取消'
                                                    onConfirm={() => handleDeleteGroup(element)}
                                                >
                                                    <Button type='danger' icon='delete' size='small'>
                                                        删除
                                                    </Button>
                                                </Popconfirm>
                                            </Col>
                                        </Row>
                                    }
                                >
                                    <Table
                                        bordered={false}
                                        size='small'
                                        scroll={{scrollToFirstRowOnChange: true}}
                            
                                        columns={[
                                          {
                                              title: '优先级',
                                              key: 'priority',
                                              dataIndex: 'priority',
                                              render: (text, record,index) => {
                                                  return index+1
                                              },
                                          },
                                          {
                                              title: '接口',
                                              key: 'thirdpart_api_name',
                                              dataIndex: 'thirdpart_api_name',
                                          },
                                          {
                                              title: '接口路径',
                                              key: 'thirdpart_api_router',
                                              dataIndex: 'thirdpart_api_router',
                                          },
                                          {
                                              title: '供应商',
                                              key: 'platform_name',
                                              dataIndex: 'platform_name',
                                          },
                                          {
                                              title: '操作',
                                              key: 'opertion',
                                              render: (_, record,provideApiIndex) => {
                                                  return (
                                                      <>
                                                          <Button type='link' size='small' disabled={provideApiIndex===0} onClick={()=>handleMoveChild(record,"up")}>
                                                              上移
                                                          </Button>
                                                          <Button type='link' size='small' disabled={provideApiIndex===element.provider_api_list.length-1} onClick={()=>handleMoveChild(record,"down")}>
                                                              下移
                                                          </Button>
                                                          <Popconfirm onConfirm={()=>handleDeleteProvideApiRecord(element,record)} title={`确认删除-${record.thirdpart_api_name}!`}>
                                                              <Button type='link' size='small'>
                                                                  删除
                                                              </Button>
                                                          </Popconfirm>
                                                      </>
                                                  );
                                              },
                                          },
                                      ]}
                                        rowKey='id'
                                        pagination={false}
                                        dataSource={element.provider_api_list}
                                    />
                                </Panel>
                            );
                        })}
                    </Collapse>
                    <Button style={{marginTop: 15}} loading={putState.loading} type='primary' htmlType='submit'>
                        提交
                    </Button>
                </Form>
}
                {modalState.visible ? (
                    <CreateSourceForm
                      visible={modalState.visible}
                    targetKeys={modalState.targetKeys}
                     onOk={handleCreate} 
                     onCancel={()=>handleUpdateModalVisible(false)} />
                ) : null}
            </Result>
        </Spin>
    );
};
export default Form.create({name: 'source'})(Source);
