/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2022-05-06 15:57:06
 * @LastEditors: cclu lkrnchocolateaaron@gmail.com
 * @Description: 商家信息完善组件
 * @FilePath: \cloud-platform\src\pages\account\company\components\CompanyInfo.tsx
 */
import ProForm, { ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import { FooterToolbar } from "@ant-design/pro-layout";
import { Alert, Card, Col, Result, Row, Typography, Modal, Image, message, Form, Upload, Button, } from "antd";
import { connect, history } from "umi";
import { useRef, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { deleteAHYDPicture, deletePicture, SavePicture } from '@/services/picture';
import { getBase64 } from "@/utils/utils";
import { createPermissionProInst } from "../../center/sevice";

import type { PermissionApplyModel, PermissionProinstModel } from "../../center/data";
import type { FormInstance, } from "antd";
import type { UploadFile } from 'antd/lib/upload/interface';
import type { CurrentUser, Dispatch } from "umi";
import type { ConnectState } from "@/models/connect";

import { getFieldEnum, getServerpartOption } from "@/services/options";
import './companyInfo.less'

const { confirm } = Modal;

interface MyUploadFile<T = any> extends UploadFile<T> {
    ImageType: 1000 | 2000 | 3000 | 4000 // 1000【营业执照】、2000【合同图片】, 3000 身份证人像面 4000 身份证国徽面
    path: string // 图片相对路径
}
// 提交信息
const handleSubmit = async (values: PermissionProinstModel) => {
    const hide = message.loading('正在提交')
    const result = await createPermissionProInst(values as PermissionProinstModel)
    hide();
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}`);
        return false;
    }
    // message.success('提交成功！请等待管理员完成审批。', 3).then(() => history.push('/user/login'));
    return true;
};
// 手动上传图片
const customRequest = async (info: any) => {

    const formData = new FormData();

    formData.append('files', info.file);
    formData.append('TableName', 'PERMISSIONAPPLY');
    formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
    if (info.filename) {
        const data = await SavePicture(formData)
        if (data.Result_Code !== 100) {
            message.error(`${data.Result_Desc}`);
            return false
        }
        return data.Result_Data
    }
    message.error("您上传的图片不存在.")
}

// 图片上传前验证
const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
        message.error('请选择图片格式为 JPG/PNG 的文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 4;
    if (!isLt2M) {
        message.error('图片大小不超过 4MB!');
    }
    return isJpgOrPng && isLt2M;
}

/**
 * @description: 商家信息完善组件主体
 * @param {currentUser} 用户信息
 * @param {dispatch} dispatch方法
 * @return {*}
 */
const CompanyInfo: React.FC<{ currentUser?: CurrentUser, dispatch: Dispatch }> = ({ currentUser, dispatch }) => {
    const { location } = history
    const formRef = useRef<FormInstance>()
    const [step, setStep] = useState<1 | 2 | 3>(1) // 当前步骤
    const [priviewImage, setPriviewImage] = useState<string>(); // 预览的图片地址
    const [fileList, setFileList] = useState<MyUploadFile[]>([]); // 需要上传的资质图片或文件列表
    const [selectName, setSelectName] = useState<string[]>(); // 选择的服务区名称
    return (
        <div>
            {step === 1 && (<><Alert message={<Typography.Text type="warning">完善公司基本资料，审批通过后可使用更多功能。</Typography.Text>} banner />

                <ProForm
                    formRef={formRef}
                    layout={'horizontal'}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    submitter={{
                        render: (_, dom) => (
                            <FooterToolbar
                            >
                                {dom}
                            </FooterToolbar>
                        ),
                    }}
                    onReset={() => {
                        setFileList([])

                    }}
                    onFinish={async (values) => {

                        const newValue = {
                            ...values,
                            SERVERPART_NAME: selectName?.toString(),
                            SERVERPART_IDS: values.SERVERPART_IDS?.toString(),
                            STAFF_ID: currentUser?.ID, // 操作人内码
                            STAFF_NAME: currentUser?.Name || values?.USER_NAME, // 操作人员
                            USER_MOBILEPHONE: currentUser?.UserMobilephone || '', // 手机号
                            PERMISSIONAPPLY_STATE: 2000,
                            PERMISSIONAPPLY_TYPE: 8000,
                            PERMISSIONAPPLY_DATE: new Date(),
                            SOURCE_PLATFORM: 0
                        }

                        const result = await handleSubmit({
                            PermissionApplyModel: newValue as PermissionApplyModel,
                            PictureList: fileList
                        })
                        if (result) {
                            setStep(2)
                            setFileList([])
                            return true
                        }
                        return false
                    }}
                >
                    <Card title="基础信息" bordered={false} bodyStyle={{ padding: 0, paddingTop: 24, paddingRight: 24 }} style={{ marginTop: 24 }}>
                        <Row gutter={24}>
                            <Col span={12}>
                                <ProFormText name="USER_NAME" label="申请人" rules={[{ required: true, message: '请输入您的姓名' }]}></ProFormText>
                            </Col>
                            <Col span={12}>
                                <ProFormSelect name="OWNERUNIT_ID" label="选择省份"
                                    request={async () => {
                                        return await getFieldEnum({ FieldExplainField: "PROVINCE_CODE", FieldEnumStatus: '1' })
                                    }}
                                    showSearch
                                    rules={[{ required: true, message: '请选择省份' }]}
                                    fieldProps={{
                                        onChange: () => {
                                            formRef?.current?.setFieldsValue({ SERVERPART_IDS: [] })
                                        }
                                    }}
                                ></ProFormSelect>
                            </Col>
                            <Col span={12}>
                                <ProFormText name="USER_IDCARD" label="身份证号"
                                    validateTrigger="onBlur"
                                    rules={[{ required: true, message: '请输入您的身份证号' }, {
                                        pattern: /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|30|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/,
                                        message: '身份证号不合法'
                                    }]}></ProFormText>
                            </Col>
                            <Col span={12}>
                                <ProFormSelect
                                    name="SERVERPART_IDS"
                                    label="服务区"
                                    placeholder={"例：满江服务区,开元服务区"}
                                    rules={[{ required: true, message: '请输入服务区' }]}
                                    dependencies={['OWNERUNIT_ID']}
                                    request={async (params) => {
                                        if (params?.OWNERUNIT_ID) {

                                            return await getServerpartOption(params?.OWNERUNIT_ID)
                                        }
                                        return []
                                    }}
                                    mode="multiple"
                                    fieldProps={
                                        {
                                            showSearch: true,
                                            onChange: (_, option) => {

                                                setSelectName(option ? option.map((n: { label: any; }) => n.label) : [])
                                            }
                                        }

                                    }
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormTextArea name="PERMISSIONAPPLY_REASON" label="申请原因" placeholder="请输入您的申请原因，以加快您的信息审核进度。" fieldProps={{ autoSize: { minRows: 1 } }} rules={[{ required: true, message: '请输入申请原因' }]} />
                            </Col>
                            <Col span={12}>
                                <ProFormTextArea name="APPLYSHOP_NAME" label="经营门店" placeholder="eg: A区奶茶店,B区小吃店" fieldProps={{ autoSize: { minRows: 1 } }} rules={[{ required: true, message: '请输入您的经营门店' }]} />
                            </Col>
                            <Col span={12}>

                                <Form.Item label="身份证照"
                                    name="personphoto"
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 20 }}
                                    rules={[{ required: true, message: '请上传身份证照片' }]}
                                >
                                    <div style={{ display: 'flex' }}>
                                        <div style={{ width: 108, display: 'inline-block' }}>
                                            <Upload
                                                accept="image/*"
                                                listType="picture-card"
                                                maxCount={1}
                                                fileList={fileList.filter(n => n.ImageType === 3000)}
                                                onChange={async (info: any) => {
                                                    if (info.file.status === 'removed') {
                                                        const index = fileList.findIndex(n => n.uid === info.file.uid); // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                                        confirm({
                                                            title: '确认删除该文件吗？',
                                                            icon: <ExclamationCircleOutlined />,
                                                            async onOk() {
                                                                const deleteLoading = message.loading('正在删除...')
                                                                // const success = await deletePicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                                const success = await deleteAHYDPicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                                deleteLoading()
                                                                if (success) {
                                                                    const files = [...fileList]
                                                                    files.splice(index, 1)
                                                                    setFileList(files)

                                                                }
                                                                else {
                                                                    message.error("删除失败")
                                                                }
                                                            },
                                                            onCancel() { },
                                                        });
                                                    } else {
                                                        setFileList([...fileList, info.file])
                                                    }
                                                }}
                                                customRequest={async (info) => {
                                                    const success = await customRequest(info)
                                                    if (success) {

                                                        const newFiles: MyUploadFile[] = fileList.slice()
                                                        const index = newFiles.findIndex(n => n.uid === info.file?.uid)
                                                        if (index > -1) {

                                                            newFiles[index] = {
                                                                //  uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                                name: success.ImageName,
                                                                status: 'done',
                                                                url: success.ImageUrl, // url 是展示在页面上的绝对链接
                                                                path: success.ImagePath,  // + success.ImageUrl,
                                                                type: typeof info.file !== 'string' ? info.file?.type : null,
                                                                ...success,
                                                                ImageType: 3000,
                                                            }
                                                        }
                                                        setFileList([...newFiles])
                                                    }
                                                }}
                                            >
                                                {(fileList.filter(n => n.ImageType === 3000)).length > 0 ? '' : `+ 人像面`}
                                            </Upload>

                                        </div>
                                        <div style={{ width: 108, display: 'inline-block' }}>
                                            <Upload
                                                accept="image/*"
                                                listType="picture-card"
                                                maxCount={1}
                                                fileList={fileList.filter(n => n.ImageType === 4000)}
                                                onChange={async (info: any) => {
                                                    if (info.file.status === 'removed') {
                                                        const index = fileList.findIndex(n => n.uid === info.file.uid); // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                                        confirm({
                                                            title: '确认删除该文件吗？',
                                                            icon: <ExclamationCircleOutlined />,
                                                            async onOk() {
                                                                const deleteLoading = message.loading('正在删除...')
                                                                // const success = await deletePicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                                const success = await deleteAHYDPicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                                deleteLoading()
                                                                if (success) {
                                                                    const files = [...fileList]
                                                                    files.splice(index, 1)
                                                                    setFileList(files)

                                                                }
                                                                else {
                                                                    message.error("删除失败")
                                                                }
                                                            },
                                                            onCancel() { },
                                                        });
                                                    } else {
                                                        setFileList([...fileList, info.file])
                                                    }
                                                }}
                                                customRequest={async (info) => {
                                                    const success = await customRequest(info)
                                                    if (success) {

                                                        const newFiles: MyUploadFile[] = fileList.slice()
                                                        const index = newFiles.findIndex(n => n.uid === info.file?.uid)
                                                        if (index > -1) {

                                                            newFiles[index] = {
                                                                //  uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                                name: success.ImageName,
                                                                status: 'done',
                                                                url: success.ImageUrl, // url 是展示在页面上的绝对链接
                                                                path: success.ImagePath,  // + success.ImageUrl,
                                                                type: typeof info.file !== 'string' ? info.file?.type : null,
                                                                ...success,
                                                                ImageType: 4000,
                                                            }
                                                        }
                                                        setFileList([...newFiles])
                                                    }
                                                }}
                                            >
                                                {(fileList.filter(n => n.ImageType === 4000)).length > 0 ? '' : `+ 国徽面`}
                                            </Upload>
                                        </div>
                                    </div>
                                </Form.Item>

                            </Col>
                        </Row>
                    </Card>
                    <Card title="营业资质" bordered={false} bodyStyle={{ padding: 0, paddingTop: 24, paddingRight: 24 }} style={{ marginTop: 24 }}>
                        <Row gutter={24}>
                            <Col span={12}>
                                <ProFormText name="BANK_NAME" label="开户行名称" rules={[{ required: true, message: '请输入开户行' }]}></ProFormText>
                            </Col>
                            <Col span={12}>
                                <ProFormText name="BANK_ACCOUNT" label="结算卡号" rules={[{ required: true, message: '请输入结算卡号' }]}></ProFormText>
                            </Col>
                            <Col span={12}>
                                <ProFormText name="TAXPAYER_IDENTIFYCODE" label="统一信用代码" rules={[{ required: true, message: '请输入统一信用代码' }]}></ProFormText>
                            </Col>
                            <Col span={12}>
                                <ProFormText name="BUSINESSMAN_NAME" label="经营商户名称" placeholder="请输入营业执照上的经营商户名称" rules={[{ required: true, message: '请输入营业执照上的经营商户名称' }]}></ProFormText>
                            </Col>
                            <Col span={24}>
                                <ProFormUploadButton
                                    name="ImgList"
                                    title="选择图片"
                                    label="营业执照"
                                    accept="image/*"
                                    wrapperCol={{ span: 22 }}
                                    labelCol={{ span: 2 }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择营业执照图片',
                                        }
                                    ]}
                                    fieldProps={{
                                        name: 'files',
                                        accept: "image/*",
                                        listType: 'picture-card',
                                        fileList: fileList.filter(n => n.ImageType && n.ImageType === 1000), // : fileList,
                                        onPreview: async (file) => {
                                            if (!file.url && !file.preview) {
                                                setPriviewImage(await getBase64(file.originFileObj))
                                            } else {
                                                setPriviewImage(file?.url)
                                            }
                                        },
                                        beforeUpload,
                                        onChange: async (info: any) => {
                                            if (info.file.status === 'removed') {
                                                const index = fileList.findIndex(n => n.uid === info.file.uid); // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                                if (!info.file?.deletepath) {

                                                    const newFileList = fileList.slice();
                                                    newFileList.splice(index, 1);
                                                    setFileList(newFileList)
                                                    return
                                                }
                                                confirm({
                                                    title: '确认删除该图片吗？',
                                                    icon: <ExclamationCircleOutlined />,
                                                    // content: 'When clicked the OK button, this dialog will be closed after 1 second',
                                                    async onOk() {
                                                        const deleteLoading = message.loading('正在删除...')

                                                        const success = await deleteAHYDPicture(info.file?.deletepath, info.file?.uid, 'PERMISSIONAPPLY')
                                                        // const success = await deletePicture(info.file?.deletepath, info.file?.uid, 'PERMISSIONAPPLY')
                                                        deleteLoading()

                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)

                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }

                                                    },
                                                    onCancel() { },
                                                });
                                            } else {

                                                setFileList([...fileList, info.file])
                                            }

                                        },
                                        customRequest: async (info) => {
                                            const success = await customRequest(info)

                                            if (success) {

                                                const newFiles: MyUploadFile[] = fileList.slice()
                                                const index = newFiles.findIndex(n => n.uid === info.file?.uid)
                                                if (index > -1) {

                                                    newFiles[index] = {
                                                        //  uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                        name: success.ImageName,
                                                        status: 'done',
                                                        url: success.ImageUrl, // url 是展示在页面上的绝对链接
                                                        path: success.ImagePath,  // + success.ImageUrl,
                                                        ...success,
                                                        ImageType: 1000,
                                                    }
                                                }

                                                setFileList([...newFiles])
                                            }


                                        }
                                    }}
                                />

                            </Col>
                            <Col span={24}>
                                <ProFormUploadButton
                                    name="ImgList2"
                                    title="选择合同"
                                    label="经营合同"
                                    wrapperCol={{ span: 22 }}
                                    labelCol={{ span: 2 }}
                                    // accept= "image/*"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择经营合同',
                                        }
                                    ]}
                                    fieldProps={{
                                        name: 'files',
                                        // accept: "image/*",
                                        // listType: 'card',
                                        className: 'upload-list-inline',
                                        fileList: fileList.filter(n => n.ImageType === 2000),
                                        multiple: true,
                                        onPreview: async (file) => {
                                            if (file.type && file.type?.indexOf('image/') > -1) {

                                                if (!file.url && !file.preview) {
                                                    setPriviewImage(await getBase64(file.originFileObj))
                                                } else {
                                                    setPriviewImage(file?.url)
                                                }
                                            } else {
                                                window.open(file?.url)
                                            }

                                        },
                                        // beforeUpload,
                                        onChange: async (info: any) => {
                                            if (info.file.status === 'removed') {
                                                const index = fileList.findIndex(n => n.uid === info.file.uid); // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                                confirm({
                                                    title: '确认删除该文件吗？',
                                                    icon: <ExclamationCircleOutlined />,
                                                    async onOk() {
                                                        const deleteLoading = message.loading('正在删除...')
                                                        // const success = await deletePicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                        const success = await deleteAHYDPicture(info.file?.ImagePath, info.file?.ImageId, 'PERMISSIONAPPLY')
                                                        deleteLoading()
                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)

                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    },
                                                    onCancel() { },
                                                });
                                            } else {
                                                setFileList([...fileList, info.file])
                                            }
                                        },
                                        customRequest: async (info) => {
                                            const success = await customRequest(info)
                                            if (success) {

                                                const newFiles: MyUploadFile[] = fileList.slice()
                                                const index = newFiles.findIndex(n => n.uid === info.file?.uid)
                                                if (index > -1) {

                                                    newFiles[index] = {
                                                        //  uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                        name: success.ImageName,
                                                        status: 'done',
                                                        url: success.ImageUrl, // url 是展示在页面上的绝对链接
                                                        path: success.ImagePath,  // + success.ImageUrl,
                                                        type: typeof info.file !== 'string' ? info.file?.type : null,
                                                        ...success,
                                                        ImageType: 2000,
                                                    }
                                                }

                                                setFileList([...newFiles])

                                            }


                                        }
                                    }}
                                />
                            </Col>
                        </Row>
                        <div style={{ display: 'none' }}>

                            <Image width={100} height={100} src={priviewImage} style={{ objectFit: "contain", display: 'none' }}
                                preview={{
                                    visible: !!priviewImage,
                                    onVisibleChange: value => {
                                        if (!value) {

                                            setPriviewImage('');
                                        }
                                    },
                                }} />
                        </div>
                    </Card>
                </ProForm>
            </>)}
            {/* 步骤2 成功 */}
            {step === 2 && <Result
                status="success"
                title="信息提交成功"
                subTitle="系统已为您提交资料完善申请，请耐心等待管理员审核。审核时间：1-2个工作日。"
                extra={[
                    <Button type="default" onClick={() => {

                        if (dispatch) {
                            dispatch({
                                type: 'global/changeTabsRoutes',
                                payload: { data: location?.pathname, action: 'remove' },
                            })
                        }
                        history.push('/account/center')
                    }
                    }>返回</Button>,
                    <Button type="primary" onClick={() => {

                        if (dispatch) {
                            dispatch({
                                type: 'global/changeTabsRoutes',
                                payload: { data: location?.pathname, action: 'remove' },
                            })
                        }
                        history.push('/merchantManagement/busniessproinst')
                    }
                    }>查看进度</Button>
                ]}
            />
            }
            {/* </PageContainer> */}
        </div>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(CompanyInfo);
