import React, { useCallback, useEffect, useState, } from 'react';
import { PageHeaderFoot, Button, message,Modal } from 'kts-xui';
import agent from '../Server';
import { Form, Space, Input, Card, Switch, Select, Radio ,Tooltip} from 'kts-components-antd-x4';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import DidModal from './UI.DIDModal';
/** Props接口 */
interface IProps {

}
export { UIComponents }
const UIComponents = (props: any) => {
    const [form] = Form.useForm();
    const [users, setUser] = useState<any>({});
    const [didModal, setDidModal] = useState(false);
    const [openkey, setOpenkey] = useState(0);
    const [checked, setCheck] = useState(true);
    const [list, setList] = useState<any>([]);
    const [id, setId] = useState(0);
    useEffect(() => {
        getData();
        getConfig();
        getlist();
    }, [])
    const getlist = async () => {
        const res: any = await agent.get('/third/dependency/getParticipantList', {}, this);
        if (res.err) {
            return;
        } else {
            setList(res.res)
        }
    }
    const getData = async (params?) => {
        const res: any = await agent.get('/collector/config/queryConfigList', {}, this);
        if (res.err) {
            return;
        } else {
            if (res.res.length === 0) {
                setUser({ users: [{ verifierName: '' }] })
            } else {
                const list = res.res.map(item => {
                    return {
                        ...item,
                    }
                })
                setUser({ users: list })
            }

        }
    }
    const getConfig = async () => {
        const res: any = await agent.get('/global/config/getCollectorVerifierDefaultConfig', {}, this);
        if (res.err) {
            return;
        } else {
            setCheck(res.res)
        }
    }
    const onSave = () => {
        form.submit();
    }
    const onFinish = async values => {
        console.log(values.users);
        const res: any = await agent.post('/collector/config/saveBatchConfigList', values.users, this);
        if (res.err) {
            return;
        } else {
            message.success('操作成功');
        }
    };
    const showDidModal = (key, name) => {
        setDidModal(true);
        setOpenkey(name);
    }
    const closeDid = () => {
        setDidModal(false);
    }
    const onAdd = () => {
        const values = form.getFieldsValue();
        if(values.users.length<=19){
            itemAdd.current();
        }else{
            message.warn('添加失败！最多添加20个')
            
        }
       
    }
    const onSelectDid = (value: any) => {
        const values = form.getFieldsValue();
        values.users[openkey].verifierName = value.customerName;
        values.users[openkey].verifierPartyId = value.customerDid;
        console.log(values);
        form.setFieldsValue({
            ...values
        })
        form.validateFields();
        closeDid();
    }
    const onSwitchChange = async (checked: boolean) => {
        const res: any = await agent.get('/global/config/updateCollectorVerifierDefaultConfig', { status: checked ? 1 : 0 }, this);
        if (res.err) {
            return;
        } else {
            setCheck(checked)
            if (checked) {
                message.success('开启成功');
            } else {
                message.success('关闭成功')
            }
        }
    }
    const onRadioChange = (e, name) => {
        const values = form.getFieldsValue();
        if (e.target.value === 1) {
            values.users[name].submitPurposeList = ['']
        } else {
            values.users[name].submitPurposeList = null
        }
        form.setFieldsValue({
            ...values
        })
    }
    const defaultValue = list && list.find(item => item.isDefault);
    let itemAdd = React.useRef<any>();
    let itemRemove = React.useRef<any>();
    return (
        <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
            <div style={{ flex: 'none', position: 'relative', zIndex: 3 }}>
                <PageHeaderFoot
                    expandRight={[
                        <Button key='1' type="primary" onClick={onAdd}>添加核验方</Button>,
                        <Button key='0' type="primary" onClick={onSave}>保存</Button>,
                    ]}
                >
                </PageHeaderFoot>
            </div>
            <Card title={<span>默认核验方设置<Tooltip title='配置一个核验方时将会直接提交给该企业，配置多个提交时选择想要提交的核验方'><QuestionCircleOutlined /></Tooltip></span>} extra={<div style={{display:'none'}}><span>是否开启默认提交规则 </span><Switch checked={checked} onChange={onSwitchChange} /></div>}>
                {users.users && users.users.length >= 0 && defaultValue &&
                    <Form layout="horizontal" initialValues={users} form={form} onFinish={onFinish} autoComplete="off">
                        <Form.List name="users" >
                            {(fields, { add, remove }) => {
                                itemAdd.current = add;
                                itemRemove.current = remove;
                                return (
                                    <>
                                        {fields.map(({ key, name, ...restField }) => (
                                            <div key={key}>
                                                <Space key={key} style={{ display: 'flex', marginBottom: 8, justifyContent: 'space-between' }} align="baseline">
                                                    <Form.Item
                                                        {...restField}
                                                        // initialValue=''
                                                        label='核验方名称'
                                                        name={[name, 'verifierName']}
                                                        rules={[{ required: true, message: '请输入必填项' }]}
                                                    >
                                                        <Input placeholder="核验方名称" addonAfter={<a style={{ color: 'inherit' }} onClick={() => { showDidModal(fields, name); }}><PlusCircleOutlined /></a>} />
                                                    </Form.Item>
                                                    <Form.Item
                                                        {...restField}
                                                        label='核验方DID'
                                                        name={[name, 'verifierPartyId']}
                                                        rules={[{ required: true, message: '请输入必填项' }]}
                                                    >
                                                        <Input placeholder="核验方DID" />
                                                    </Form.Item>
                                                    <Form.Item
                                                        {...restField}
                                                        label='我司对应DID'
                                                        initialValue={defaultValue.participantId}
                                                        name={[name, 'collectorPartyId']}
                                                        rules={[{ required: true, message: '请输入必填项' }]}
                                                    >
                                                        <Select style={{ width: 300 }}>
                                                            {list && list.map((item) => {
                                                                return <Select.Option value={item.participantId}>{item.participantId}</Select.Option>
                                                            })}
                                                        </Select>
                                                    </Form.Item>
                                                    <a style={{whiteSpace:'nowrap'}} onClick={() => remove(name)} >删除</a>
                                                </Space>
                                                <div >
                                                    <Form.Item initialValue={1} name={[name, 'submitPurposeRule']} label={<span><Tooltip title='根据核验方要求，在提交发票时是否需要选择提交用途，内容为核验方要求字段。'><QuestionCircleOutlined />是否选择提交用途</Tooltip></span>} rules={[{ required: true, message: '请输入必填项' }]}>
                                                        <Radio.Group onChange={(e) => { onRadioChange(e, name) }}>
                                                            <Radio value={1}> 是 </Radio>
                                                            <Radio value={0}> 否 </Radio>
                                                        </Radio.Group>
                                                    </Form.Item>

                                                    <Form.List
                                                        name={[name, "submitPurposeList"]}
                                                        initialValue={['']}
                                                    >
                                                        {(child, { add, remove }) => {
                                                            return (
                                                                <span style={{ display: 'flex',flexWrap:'wrap' }}>
                                                                    {child.map((field, index) => (
                                                                        <>
                                                                            <Form.Item
                                                                                label={<span>提交用途{index + 1}</span>}
                                                                                name={[index]}
                                                                                key={field.key}
                                                                                rules={[
                                                                                    {
                                                                                        required: true,
                                                                                        whitespace: true,
                                                                                        message: "请输入必填项",
                                                                                    },
                                                                                ]}
                                                                            >
                                                                                <Input maxLength={20} style={{ width: 150 }} addonAfter={child.length > 1 ? (
                                                                                    <div><MinusCircleOutlined onClick={() => remove(index)} /></div>
                                                                                ) : null} />
                                                                            </Form.Item>

                                                                        </>
                                                                    ))}
                                                                    {child.length <= 9 && child.length !== 0 ? (
                                                                        <Button type="link" onClick={() => add()} >
                                                                            添加提交用途
                                                                        </Button>
                                                                    ) : null}
                                                                </span>
                                                            )
                                                        }}
                                                    </Form.List>
                                                </div>
                                            </div>
                                        ))}
                                    </>
                                )
                            }}
                        </Form.List>
                    </Form>
                }
            </Card>
            { didModal && <DidModal onClose={closeDid} onSuccess={onSelectDid} />}
        </div >
    );
}
// class UIComponents extends React.Component<IProps, any> {
//     formRef = React.createRef<FormInstance>();
//     constructor(props) {
//         super(props);
//         this.state = {
//             users: null,
//             didModal: false,
//             openkey: 0,
//             checked: 1,
//             list: []
//         };
//     }



//     componentDidMount() {
//         this.getData();
//         this.getConfig();
//         this.getlist();
//     }
//     onRefresh = () => {
//         const params = {
//             ...this.state.params,
//         };
//         this.getData(params);

//     }
//     getlist = async () => {
//         const res: any = await agent.get('/third/dependency/getParticipantList', {}, this);
//         if (res.err) {
//             return;
//         } else {
//             this.setState({
//                 list: res.res
//             })
//         }
//     }
//     getData = async (params?) => {
//         const res: any = await agent.get('/collector/config/queryConfigList', {}, this);
//         if (res.err) {
//             return;
//         } else {
//             if (res.res.length === 0) {
//                 this.setState({
//                     users: { users: [{ verifierName: '' }] },
//                 });
//             } else {
//                 this.setState({
//                     users: { users: res.res },
//                 });
//             }

//         }
//     }
//     getConfig = async () => {
//         const res: any = await agent.get('/global/config/getCollectorVerifierDefaultConfig', {}, this);
//         if (res.err) {
//             return;
//         } else {
//             this.setState({
//                 checked: res.res
//             });
//         }
//     }
//     onSave = () => {
//         this.formRef.current?.submit();
//     }
//     onFinish = async values => {
//         const res: any = await agent.post('/collector/config/saveBatchConfigList', values.users, this);
//         if (res.err) {
//             return;
//         } else {
//             message.success('操作成功');
//         }
//     };
//     showDidModal = (key, name) => {
//         this.setState({
//             didModal: true,
//             openkey: name
//         })
//     }
//     closeDid = () => {
//         this.setState({
//             didModal: false
//         })
//     }
//     onSelectDid = (value: any) => {
//         const values = this.formRef.current!.getFieldsValue();
//         values.users[this.state.openkey].verifierName = value.customerName;
//         values.users[this.state.openkey].verifierPartyId = value.customerDid;
//         // values.users[this.state.openkey].collectorPartyId = value.companyDid;
//         this.formRef.current!.validateFields();
//         this.closeDid();
//     }
//     onSwitchChange = async (checked: boolean) => {
//         const res: any = await agent.get('/global/config/updateCollectorVerifierDefaultConfig', { status: checked ? 1 : 0 }, this);
//         if (res.err) {
//             return;
//         } else {
//             this.setState({
//                 checked
//             });
//             if (checked) {
//                 message.success('开启成功');
//             } else {
//                 message.success('关闭成功')
//             }
//         }
//     }
//     onAdd=()=>{
//         console.log(this.formRef)
//     }
//     render() {
//         // const users = this.state.users;
//         const { didModal, checked, users, list } = this.state;
//         const defaultValue = list && list.find(item => item.isDefault);
//         return (
//             <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
//                 <div style={{ flex: 'none', position: 'relative', zIndex: 3 }}>
//                     <PageHeaderFoot
//                         expandRight={[
//                             <Button key='1' type="primary" onClick={this.onAdd}>添加核验方</Button>,
//                             <Button key='0' type="primary" onClick={this.onSave}>保存</Button>,
//                         ]}
//                     >
//                     </PageHeaderFoot>
//                 </div>
//                 <Card title='默认核验方设置' extra={<div><span>是否开启默认提交规则 </span><Switch disabled checked={checked} onChange={this.onSwitchChange} /></div>}>
//                     {users && users.users.length >= 0 && defaultValue &&
//                         <Form initialValues={users} ref={this.formRef} onFinish={this.onFinish} autoComplete="off">
//                             <Form.List name="users" >
//                                 {(fields, { add, remove }) => (
//                                     <>
//                                         {fields.map(({ key, name, ...restField }) => (
//                                             <Space key={key} style={{ display: 'flex', marginBottom: 8, justifyContent: 'space-around' }} align="baseline">
//                                                 <Form.Item
//                                                     {...restField}
//                                                     initialValue=''
//                                                     label='核验方名称'
//                                                     name={[name, 'verifierName']}
//                                                     rules={[{ required: true, message: '请输入必填项' }]}
//                                                 >
//                                                     <Input placeholder="核验方名称" addonAfter={<a style={{ color: 'inherit' }} onClick={() => { this.showDidModal(fields, name); }}><PlusCircleOutlined /></a>} />
//                                                 </Form.Item>
//                                                 <Form.Item
//                                                     {...restField}
//                                                     label='核验方DID'
//                                                     name={[name, 'verifierPartyId']}
//                                                     rules={[{ required: true, message: '请输入必填项' }]}
//                                                 >
//                                                     <Input placeholder="核验方DID" />
//                                                 </Form.Item>
//                                                 <Form.Item
//                                                     {...restField}
//                                                     label='我司对应DID'
//                                                     initialValue={defaultValue.participantId}
//                                                     name={[name, 'collectorPartyId']}
//                                                     rules={[{ required: true, message: '请输入必填项' }]}
//                                                 >
//                                                     <Select style={{ width: 300 }}>
//                                                         {list && list.map((item) => {
//                                                             return <Select.Option value={item.participantId}>{item.participantId}</Select.Option>
//                                                         })}
//                                                     </Select>
//                                                 </Form.Item>
//                                                 <MinusCircleOutlined onClick={() => remove(name)} />
//                                             </Space>
//                                         ))}
//                                         <Form.Item>
//                                             <Button type="link" onClick={() => add()} >
//                                                 添加一行
//                                             </Button>
//                                         </Form.Item>
//                                     </>
//                                 )}
//                             </Form.List>
//                         </Form>
//                     }
//                 </Card>
//                 { didModal && <DidModal onClose={this.closeDid} onSuccess={this.onSelectDid} />}
//             </div >
//         );
//     }
// }
// export default UIComponents