import * as React from 'react';
import { Button, Drawer, Form, Radio, message, Checkbox } from 'kts-xui';
import { Space, Modal } from 'kts-components-antd-x4';
import agent from '../Server';
const { confirm } = Modal;
/** Props接口 */
interface IProps {
    config: any;
    record?: any;
    children: any;
    invoiceUuidList?: string[]
}
/**
 * 选择用途面板
 */
export default function Component(props: IProps) {
    const [loading, setLoading] = React.useState(false);
    const [modal, setModal] = React.useState(false);
    /**
     * 公司列表
     */
    const companyList = React.useMemo(() => props.config, [props.config])
    /**
     * 提交用途
     */
    // const list = React.useMemo(() => props.config && props.config.submitPurposeList, [])
    const [form] = Form.useForm();
    const onClose = () => {
        setModal(false)
    }
    const onSubmit = () => {
        form.submit();

    }
    //提交表单
    const onFinish = values => {
        let verifier: any = []
        for (let i in values) {
            const splitArray = i.split('_');
            if (splitArray[0] === 'verifierPartyId') {
                verifier.push(values[i])
            }
        }
        if (props.invoiceUuidList) {
            const data: any = [];
            for (let i = 0; i < companyList.length; i++) {
                if (verifier[i] === true) {
                    data.push({
                        ...companyList[i],
                        collectorPartyId: companyList[i].collectorPartyId,
                        invoiceUuidList: props.invoiceUuidList,
                        submitPurpose:values[`submitPurpose_${i}`],
                        verifierPartyConfigId: companyList[i].id,
                        verifierName:companyList[i].verifierName,
                        verifierPartyId:companyList[i].verifierPartyId,
                    })
                }
            }
            if(data.length===0){
                message.error('请选择数据');
                return false
            }
            submitBatch(data);
        } else {
            const data: any = [];
            for (let i = 0; i < companyList.length; i++) {
                if (verifier[i] === true) {
                    data.push({
                        ...companyList[i],
                        invoiceUuid: props.record?.invoiceUuid,
                        verifierPartyConfigId: companyList[i].id,
                        submitPurpose:values[`submitPurpose_${i}`]
                    })
                }
            }
            if(data.length===0){
                message.error('请选择数据');
                return false
            }
            submitOne(data)
        }
    }
    //批量提交
    const submitBatch = async (data) => {
        if (!loading) {
            setLoading(true)
            const res: any = await agent.post('/collector/asset/submitBatch', data, null);
            setLoading(false)
            if (res.err) {
                return;
            } else {
                //验证通过直接调用提交接口
                if (res.res.checkPass) {
                    const list = res.res.detailList;
                    onFinalSubmit(list);
                } else {
                    //验证部分数据失败，弹框提示
                    const list = res.res.detailList;
                    const total = res.res.totalNo;
                    const failureNo=res.res.failureNo;
                    confirm({
                        title: '重复提交',
                        content: <p>您已勾选的{total}行发票数据，有{failureNo}行已经提交过，无法重复提交，是否提交剩余发票
                            <a href={res.res.downloadUrl} target="_blank">下载重复发票信息</a>
                        </p>,
                        onOk: () => {
                            onFinalSubmit(list);
                        },
                    });
                }
            }
        }
    }
    const onFinalSubmit = async (data) => {
        const res: any = await agent.post('/collector/asset/submitBatchConfirm', data, null);
        if (res.err) {
            return;
        } else {
            message.success('操作成功');
            onClose();
        }
    }
    //单个提交
    const submitOne = async (data) => {
        const res: any = await agent.post('/collector/asset/submitOne', data , null);
        if (res.err) {
            return;
        } else {
            message.success('操作成功');
            onClose();
        }
    }
    //如果用途列表存在那么显示抽屉，如果没有直接提交
    const showModal = async () => {
       
        //多个公司
        if (companyList.length > 1) {
            setModal(true)
            
        } else if (companyList.length === 1 && companyList[0].submitPurposeList.length > 1) {
            //单个公司，但是有超过2个用途
            setModal(true)
        } else {
           
            //单个公司，但是只有0/1个用途
            if (props.invoiceUuidList) {
                let data: any = [{
                    verifierName:companyList[0].verifierName,
                    verifierPartyId: companyList[0].verifierPartyId,
                    collectorPartyId: companyList[0].collectorPartyId,
                    verifierPartyConfigId: companyList[0].id,
                    invoiceUuidList: props.invoiceUuidList,
                }]
                if (companyList[0].submitPurposeList.length === 1) {
                    data[0].submitPurpose = companyList[0].submitPurposeList[0];
                }
                submitBatch(data);
            } else {
                let data: any = [{
                    ...companyList[0],
                    invoiceUuid: props.record?.invoiceUuid,
                    verifierPartyConfigId: companyList[0].id,
                }]
                if (companyList[0].submitPurposeList.length === 1) {
                    data[0].submitPurpose = companyList[0].submitPurposeList[0];
                }
                submitOne(data)
            }
        }
    }
    return (
        <div>
            <div style={{ width: '100%' }} key='1' onClick={showModal}>{props.children}</div>
            <Drawer
                title="提交"
                onClose={onClose}
                visible={modal}
                width={500}
                footer={
                    <div
                        style={{
                            textAlign: 'right',
                        }}
                    >
                        <Button style={{ marginRight: 8 }} key='1' type="primary" onClick={onSubmit}>提交</Button>
                        <Button key='2' onClick={onClose}>取消</Button>
                    </div>}
            >
                <Form
                    form={form}
                    layout='vertical'
                    onFinish={onFinish}
                >
                    {
                        companyList.map((item, index) => {
                            return <>
                                <Form.Item
                                    name={`verifierPartyId_${index}`}
                                    label='核验方名称'
                                    valuePropName="checked"
                                    initialValue={true}
                                >
                                    <Checkbox >{item.verifierName}</Checkbox>

                                </Form.Item>
                                {item.submitPurposeList.length > 0 &&
                                    <Form.Item
                                        name={`submitPurpose_${index}`}
                                        label='请选择提交发票用途'
                                        rules={[{ required: true, message: '请输入必填项' }]}
                                        initialValue={item.submitPurposeList[0]}
                                    >
                                        <Radio.Group>
                                            <Space direction="vertical">
                                                {item.submitPurposeList.map((dd, index) => {
                                                    return <Radio key={dd} value={dd}>{dd}</Radio>
                                                })}
                                            </Space>
                                        </Radio.Group>
                                    </Form.Item>
                                }
                            </>
                        })
                    }
                </Form>
            </Drawer>

        </div>
    );

}
