/*
 * @Author: liqiang
 * @Date: 2021-03-04 17:19:02
 * @LastEditTime: 2021-04-01 14:05:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ebtp-cloud-frontend\src\utils\IParticipateIn.tsx
 */
import { participationSave, participationSaveOther } from '@/pages/Tender/supplier/LookingForBusinessOpportunities/service';
import ProTable from '@ant-design/pro-table';
import { Button, Card, Checkbox, Form, Input, message, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import { useHistory } from 'umi';
import { getBidMethodDictTypeCode, getProTypeCodeByBidMethodDict, isNotEmpty } from './CommonUtils';
import { queryingPagingData } from './PageUtils';

interface IParticipateInItem {
    projectData: any,
    visible: boolean,
    setVisible: (value: boolean) => void
}

/**
 * 获取标段名称
 * @param bidMethodDict 
 */
function getBsName(bidMethodDict: string) {
    if (bidMethodDict.indexOf("procurement_mode_4") !== -1) {
        return '包件';
    }
    if (bidMethodDict.indexOf("procurement_mode_3") !== -1 || bidMethodDict.indexOf("procurement_mode_5") !== -1) {
        return '采购包';
    }
    return '标段';
}

function getSectionCheckbox(data: any) {
    let value = [];
    let flag = true;
    for (const item of data) {
        if (flag) {
            value.push(
                <Checkbox key={item.bsId} style={{ marginLeft: '8px' }} value={item.bsId}>
                    {item.bsName}
                </Checkbox>
            )
            flag = false;
        } else {
            value.push(
                <Checkbox key={item.bsId} value={item.bsId}>
                    {item.bsName}
                </Checkbox>
            )
        }

    }
    return value;
}
const modalHeight = innerHeight * 96 / 100;
/**
 * 我要参与
 * @param props 
 */
const IParticipateIn: React.FC<IParticipateInItem> = (props) => {
    const { projectData, visible, setVisible } = props;
    const [form] = Form.useForm();
    //保存遮罩
    const [spinningLoading, setSpinningLoading] = useState<boolean>(false);
    //常用联系人模态框
    const [contactsVisible, setContactsVisible] = useState<boolean>(false);
    //标段名称
    const [bsName, setBsName] = useState<string>('');
    //标段多选
    const [sectionCheckbox, setSectionCheckbox] = useState<any[]>();
    //采购方式
    const [bidMethodDict, setBidMethodDict] = useState<string>('');
    const history = useHistory();
    //联系人数据
    const [contactsItem, setContactsItem] = useState<any>(null);
    useEffect(() => {
        if (isNotEmpty(projectData)) {
            setBsName(getBsName(projectData.bidMethodDict));
            setBidMethodDict(projectData.bidMethodDict);
            //标段信息
            let sectionVOList = projectData.sectionVOList;
            if (sectionVOList.length === 0) {
                // 当前项目报名截止！
                message.warning('当前项目报名截止！');
                return;
            }
            setSectionCheckbox(getSectionCheckbox(sectionVOList));
            form.resetFields();
            setContactsItem(null);
            let examinationMethodDict = "";
            if (bidMethodDict.indexOf("procurement_mode_4") > -1) {
                examinationMethodDict = projectData?.examinationMethodDict.replace("recruitment_method_", "")
            }
            form.setFieldsValue({
                recruitType: examinationMethodDict,
                projectId: projectData.id,
                roomType: projectData.roomType
            })
        }
    }, [projectData]);

    /**
   * 表单提交
   * @param value
   */
    const formOnFinish = (value: any) => {
        setSpinningLoading(true);
        // value.bizSupplierContact = contactsItem === null ? {
        //     contactName: value.contactName,
        //     contactTelephone: value.contactTelephone,
        //     contactEmail: value.contactEmail,
        //     contactAddress: value.contactAddress,
        //     fixedLine: value.fixedLine,
        //     contactFax: value.contactFax
        // } : contactsItem;
        value.bizSupplierContact = form.getFieldsValue();
        delete value['id'];
        /*招募方式 调用特殊接口 2021 02 08 dqh*/
        if (bidMethodDict.indexOf("procurement_mode_4") > -1) {
            participationSaveOther(value).then(res => {
                if (res.data) {
                    message.success('操作成功！', 2, () => {
                        history.push(`${getBidMethodDictTypeCode(bidMethodDict)}/Involved`);
                        setSpinningLoading(false);
                    });
                } else {
                    setSpinningLoading(false);
                    message.error('操作失败！');
                }
            })
        } else {
            participationSave(value).then(res => {
                if (res.data) {
                    message.success('操作成功！', 2, () => {
                        history.push(`${getBidMethodDictTypeCode(bidMethodDict)}/Involved`);
                        setSpinningLoading(false);
                    });
                } else {
                    setSpinningLoading(false);
                    message.error('操作失败！');
                }
            })
        }
    }

    /**
   * 常用联系人
   */
    const contacts = () => {
        const onCancel = () => setContactsVisible(false);
        const select = (data: any) => {
            form.setFieldsValue(data);
            setContactsItem(data);
            setContactsVisible(false);
        }

        const columns: any[] = [
            {
                title: '序号',
                valueType: 'index',
                width: '7%'
            },
            {
                title: '姓名',
                dataIndex: 'contactName',
                width: '15%'
            },
            {
                title: 'id',
                dataIndex: 'id',
                hideInTable: true,
            },
            {
                title: '手机号码',
                dataIndex: 'contactTelephone',
                search: false,
                width: '15%'
            },
            {
                title: '地址',
                dataIndex: 'contactAddress',
                search: false,
                width: '25%'
            },
            {
                title: '电子邮箱',
                dataIndex: 'contactEmail',
                search: false,
                width: '13%'
            },
            {
                title: '操作',
                valueType: 'option',
                width: '5%',
                render: (_: any, record: any) => [
                    <a key="select" onClick={() => select(record)}>选择</a>
                ]
            },
        ]
        return (
            <>
                <Modal visible={contactsVisible}
                    title="选择常用联系人"
                    onCancel={onCancel}
                    width={900}
                    style={{ maxHeight: modalHeight }}
                    bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
                    maskClosable={false}
                    footer={null}
                    centered
                >
                    <Card>
                        <ProTable
                            rowKey="id"
                            pagination={{ defaultPageSize: 10 }}
                            size="small"
                            columns={columns}
                            options={false}
                            request={params => queryingPagingData('/api/biz-service-ebtp-tender/v1/bizsuppliercontact/getSupplierContactByParam', 'post', params)}
                        />
                    </Card>
                </Modal>
            </>
        )
    }


    const createForm = () => {
        return (<Form
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 13 }}
            form={form}
            onFinish={formOnFinish}
        >
            <h2 style={{ margin: '0px 0px 20px 0px' }}>
                您即将参与 {projectData?.projectName}，请填写下列信息：
            </h2>
            <Form.Item
                name="projectId"
                hidden
            >
                <Input />
            </Form.Item>
            <Form.Item
                name="recruitType"
                hidden
            >
                <Input />
            </Form.Item>
            <Form.Item
                name="id"
                hidden
            >
                <Input />
            </Form.Item>
            <Form.Item
                name="roomType"
                hidden
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="联系人"
                name="contactName"
                rules={[{ required: true }]}
            >
                <Input maxLength={32} addonAfter={(<a onClick={() => setContactsVisible(true)}>常用联系人</a>)} />
            </Form.Item>

            <Form.Item
                label="联系电话"
                name="contactTelephone"
                rules={[{ required: true },
                { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: '请输入正确的电话号码' }
                ]}
                extra={<span style={{ color: '#b30000' }}>平台短信提醒功能仅支持联通号段，其他运营商号段暂不支持</span>}
            >
                <Input maxLength={14} />
            </Form.Item>


            <Form.Item
                label="邮箱"
                name="contactEmail"
                rules={[{ required: true }, { type: 'email', message: '请输入正确的邮箱格式' }]}
            >
                <Input maxLength={32} />
            </Form.Item>

            <Form.Item
                label="地址"
                name="contactAddress"
            >
                <Input maxLength={100} />
            </Form.Item>

            <Form.Item
                label="固定电话"
                name="fixedLine"
                rules={[
                    { pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/, message: '请输入正确的固定电话号码' }
                ]}
            >
                <Input maxLength={32} />
            </Form.Item>

            <Form.Item
                label="传真"
                name="contactFax"
                rules={[{ pattern: /^(\d{3,4}-)?\d{7,8}$/, message: '请输入正确的传真格式' }]}
            >
                <Input maxLength={32} />
            </Form.Item>

            <Form.Item
                label={`选择${bsName}`}
                name="packageIdList"
                rules={[{ required: true }]}
            >
                <Checkbox.Group>
                    {sectionCheckbox}
                </Checkbox.Group>
            </Form.Item>

        </Form>
        )
    }
    /**
 * 我要参与
 */
    const modalBox = () => {
        const OnOk = (): void => form.submit();
        const onCancel = (): void => setVisible(false);
        return (
            <>
                <Modal visible={visible}
                    title="我要参与"
                    onOk={OnOk}
                    onCancel={onCancel}
                    width="40%"
                    maskClosable={false}
                    centered
                    style={{ maxHeight: modalHeight }}
                    bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
                    footer={[
                        <Button key="back" onClick={onCancel}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={spinningLoading} onClick={OnOk}>
                            保存
                        </Button>,
                    ]}
                >
                    {createForm()}
                </Modal>
                {contacts()}
            </>
        )
    }

    return modalBox();
}

export default IParticipateIn;