import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ProFormInstance } from '@ant-design/pro-components';
import { StepsForm, ProCard, ProFormDatePicker, ProFormDependency, ProFormText, ProFormCascader, ProFormRadio, FormControlRender, ProFormSelect } from '@ant-design/pro-components';
import { Row, Col, Image, ConfigProvider, Modal, Space, Form, message, Button } from 'antd';
import { selectfieldNames, cascaderfieldNames, Imageprefix } from '@/constants'
import { findAncestors } from '@/utils/dataHelper'
import { disAfterData } from '@/utils/format'

import MapComponent from '@/components/Common/map';
import RichComponent from '@/components/Common/rich';
import UploadModel from '@/components/Common/upload';

import { addCompany, PostCompanyEdit, GetCompanyInfo } from '@/apis/api';

interface PagesMainCompanyListCreateProps {
    id: any
}
const PagesMainCompanyListCreate: React.FC<PagesMainCompanyListCreateProps> = ({ dispatch, dictModel, openModel, id }: any) => {
    const formRef = useRef<ProFormInstance>();
    const formMapRef = useRef<
        React.MutableRefObject<ProFormInstance<any> | undefined>[]
    >([]); // 编辑模式
    const [openPreview, setOpenPreview] = useState(false);
    const [detail, setDetail] = useState<CompanyType.Basic | null>(null)

    const [richTxt, setRichTxt] = useState<string | number>(''); // 企业简介
    const [mapSwitch, setMapSwitch] = useState<boolean>(false); // 选择地图
    const [lat, setLat] = useState<string | number>('');
    const [lng, setLng] = useState<string | number>('');
    const [uploadedFilephotoName, setUploadedFilephotoName] = useState<string>('');
    const handleFileUploadedphoto = (filename: string) => {
        setUploadedFilephotoName(filename);
    };

    const [uploadedFilelicenseName, setUploadedFilelicenseName] = useState<string>('');
    const handleFileUploadedlicense = (filename: string) => { 
        setUploadedFilelicenseName(filename);
    };

    const [uploadedFilephotosName, setUploadedFilephotosName] = useState<object[]>([]);

    const handleFileUploadedphotos = (filename: string) => { 
        setUploadedFilephotosName([...uploadedFilephotosName, { photo: filename }]);
    };


    useEffect(() => {
        dispatch({ type: 'dictModel/getList', payload: { code: 2000, type: 'setClassificationList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2009, type: 'setAreaList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2002, type: 'setNatureList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2003, type: 'setScaleList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2027, type: 'setIndustryPostList' } })

    }, [])

    useEffect(() => {
        setOpenPreview(openModel.openModal)
    }, [openModel.openModal])


    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                    }
                }}
            >
                <Modal
                    open={openPreview}
                    title={id ? '编辑企业' : '添加企业'}
                    centered
                    maskClosable={false}
                    footer={null}
                    destroyOnClose
                    width={1000}
                    onCancel={() => {
                        dispatch({ type: 'openModel/getOpenModal', payload: false })
                    }}
                    afterOpenChange={(open) => {
                        if (open && id) {
                            GetCompanyInfo({ id: id }).then(res => {
                                formMapRef?.current?.forEach((formInstanceRef) => {
                                    res.data.industry_arr = [res.data.industry];
                                    res.data.nature_arr = findAncestors(dictModel.natureList, res.data.nature).concat([res.data.nature])
                                    res.data.scale_arr = findAncestors(dictModel.scaleList, res.data.scale).concat([res.data.scale])
                                    res.data.location_arr = [
                                        res.data.province ? res.data.province : 0,
                                        res.data.city ? res.data.city : 0,
                                        res.data.district ? res.data.district : 0,
                                        res.data.street ? res.data.street : 0
                                    ];
                                    setUploadedFilephotosName(res.data.company_photos)
                                    formInstanceRef?.current?.setFieldsValue(res.data);
                                });
                                setDetail(res.data)
                            });
                        } else {
                            setDetail(null)
                        }
                    }}
                >
                    <StepsForm<CompanyType.Basic>
                        formMapRef={formMapRef}
                        formRef={formRef}
                        onFinish={async (values: CompanyType.Basic) => {
                            values.industry = values.industry_arr && values.industry_arr.length > 0 && values.industry_arr[0] ? values.industry_arr[0] : 0;
                            values.province = values.location_arr && values.location_arr[0] ? values.location_arr[0] : 0;
                            values.city = values.location_arr && values.location_arr[1] ? values.location_arr[1] : 0;
                            values.district = values.location_arr && values.location_arr[2] ? values.location_arr[2] : 0;
                            values.street = values.location_arr && values.location_arr[3] ? values.location_arr[3] : 0;
                            values.nature = values.nature_arr && values.nature_arr.length > 0 ? values.nature_arr[values.nature_arr.length - 1] : 0;
                            values.scale = values.scale_arr && values.scale_arr.length > 0 ? values.scale_arr[values.scale_arr.length - 1] : 0;
                            delete values.nature_arr;
                            delete values.scale_arr;
                            delete values.location_arr;
                            delete values.industry_arr;

                            values.photo = uploadedFilephotoName ? uploadedFilephotoName : '';
                            values.license_path = uploadedFilelicenseName ? uploadedFilelicenseName : '';
                            values.company_photos = uploadedFilephotosName ? uploadedFilephotosName : [];
                            values.status = 1;
                            console.log(values)
                            if (detail) {
                                values.id = detail.id;
                                values.nature = values.nature_arr && values.nature_arr.length > 0 ? values.nature_arr[values.nature_arr.length - 1] : 0;
                                values.scale = values.scale_arr && values.scale_arr.length > 0 ? values.scale_arr[values.scale_arr.length - 1] : 0;
                                delete values.nature_arr;
                                delete values.scale_arr;
                                let res = await PostCompanyEdit(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            } else {

                                let res = await addCompany(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            }
                            return true;
                        }}
                    >
                        <StepsForm.StepForm
                            title="基本信息"
                            onFinish={async (values) => {
                                return true;
                            }}
                        >
                            <ProCard
                                ghost
                                style={{
                                    minWidth: 800,
                                    maxWidth: '100%',
                                }}
                            >
                                <Row gutter={[16, 16]}>
                                    <Col span={8}>
                                        <ProFormText
                                            label="企业名称"
                                            name="full_name"
                                            placeholder="请输入企业名称"
                                            rules={[{ required: true, message: '请输入企业名称' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="统一社会信用代码"
                                            name="registration_number"
                                            placeholder="请输入统一社会信用代码"
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormDatePicker
                                            width='lg'
                                            name="establishment_date"
                                            label="成立日期"
                                            placeholder='请选择成立日期'
                                            fieldProps={{
                                                disabledDate: disAfterData
                                            }}
                                            rules={[{ required: true, message: '请选择成立日期' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="联系人"
                                            name="contact"
                                            placeholder="请输入联系人"
                                            rules={[{ required: true, message: '请输入联系人' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="联系固话"
                                            name="phone"
                                            placeholder="请输入联系电话"
                                            rules={[{ required: true, message: '请输入联系电话' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="手机号"
                                            name="mobile"
                                            placeholder="请输入手机号"
                                            rules={[{ required: true, message: '请输入手机号' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="联系邮箱"
                                            name="email"
                                            placeholder="请输入联系邮箱"
                                            rules={[{ required: true, message: '请输入联系邮箱' }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="传真"
                                            name="fax"
                                            placeholder="请输入传真"
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="官网"
                                            name="website"
                                            placeholder="请输入官网"
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormCascader
                                            label="所属行业"
                                            name="industry_arr"
                                            fieldProps={{
                                                fieldNames: cascaderfieldNames,
                                                options: dictModel.industryPostList,
                                                changeOnSelect: true
                                            }}
                                            rules={[{ required: true, message: '请选择所属行业' }]}

                                            placeholder="请选择所属行业"
                                        />

                                    </Col>
                                    <Col span={8}>
                                        <ProFormCascader
                                            label="企业性质"
                                            name="nature_arr"
                                            fieldProps={{
                                                fieldNames: cascaderfieldNames,
                                                options: dictModel.natureList,
                                                changeOnSelect: true
                                            }}
                                            rules={[{ required: true, message: '请选择企业性质' }]}

                                            placeholder="请选择企业性质"
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormCascader
                                            label="企业规模"
                                            name="scale_arr"
                                            fieldProps={{
                                                fieldNames: cascaderfieldNames,
                                                options: dictModel.scaleList,
                                                changeOnSelect: true
                                            }}
                                            rules={[{ required: true, message: '请选择企业规模' }]}

                                            placeholder="请选择企业规模"
                                        />
                                    </Col>


                                    <Col span={8}>
                                        <ProFormCascader
                                            label="企业所在地区"
                                            name="location_arr"
                                            fieldProps={{
                                                fieldNames: cascaderfieldNames,
                                                options: dictModel.areaList,
                                                changeOnSelect: true
                                            }}
                                            rules={[{ required: true, message: '请选择企业所在地区' }]}
                                            placeholder="企业所在地区"
                                        />
                                    </Col>
                                </Row>
                            </ProCard>
                        </StepsForm.StepForm>
                        <StepsForm.StepForm
                            title="企业简介"
                            onFinish={async (values) => {
                                return true;
                            }}
                        >
                            <ProCard
                                ghost
                                style={{
                                    minWidth: 800,
                                    maxWidth: '100%',
                                }}
                            >
                                <Row gutter={[16, 16]}>
                                    <Col span={24}>
                                        <Form.Item
                                            name='introduction'
                                            label="企业简介"
                                            rules={[{ required: true }]}
                                        >
                                            <FormControlRender>
                                                {() => {
                                                    return (
                                                        <ProFormDependency name={['introduction']} >
                                                            {({ introduction }, form) => {
                                                                return (
                                                                    <RichComponent placeholder="请输入企业简介" defaultValue={introduction}
                                                                        onChange={(value) => {
                                                                            setRichTxt(value)
                                                                            form.formRef.current.setFieldsValue({
                                                                                introduction: value
                                                                            })
                                                                        }}></RichComponent>
                                                                );
                                                            }}
                                                        </ProFormDependency>
                                                    );
                                                }}
                                            </FormControlRender>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </ProCard>
                        </StepsForm.StepForm>
                        <StepsForm.StepForm
                            title="企业地址"
                            onFinish={async (values) => {
                                return true;
                            }}
                        >
                            <ProCard
                                ghost
                                style={{
                                    minWidth: 800,
                                    maxWidth: '100%',
                                }}
                            >
                                <Row gutter={[16, 16]}>
                                    {/* <Col span={24}>
                                        <Switch checked={mapSwitch} checkedChildren='地图已显示' unCheckedChildren="地图已关闭" onChange={(val) => {
                                            setMapSwitch(val)
                                        }} />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="经度"
                                            name="longitude"
                                            placeholder="请选择打开地图并选择经度"
                                            disabled
                                            rules={[{
                                                required: true, message: '请选择打开地图并选择经度',
                                            }]}
                                        />
                                    </Col>
                                    <Col span={8}>
                                        <ProFormText
                                            label="纬度"
                                            name="latitude"
                                            disabled
                                            placeholder="请选择打开地图并选择纬度"
                                            rules={[{
                                                required: true, message: '请选择打开地图并选择纬度',
                                            }]}
                                        />
                                    </Col> */}
                                    <Col span={8}>
                                        <ProFormText
                                            label="详细地址"
                                            name="address"
                                            placeholder="请输入详细地址"
                                            rules={[{ required: true, message: '请输入详细地址' }]}
                                        />
                                    </Col>

                                    {/* {
                                        mapSwitch && <Col span={24}>
                                            <MapComponent lat={lat} lng={lng} getLoc={(values) => {
                                                formRef.current.setFieldsValue({
                                                    latitude: values.latlng.lat,
                                                    longitude: values.latlng.lng,
                                                    address: values.poiaddress
                                                })
                                                setLat(values.latlng.lat)
                                                setLng(values.latlng.lng)
                                                setMapSwitch(false)
                                            }}></MapComponent>
                                        </Col>
                                    } */}
                                </Row>
                            </ProCard>
                        </StepsForm.StepForm>
                        <StepsForm.StepForm
                            title="相关图片"
                            onFinish={async (values) => {
                                return true;
                            }}
                        >
                            <ProCard
                                ghost
                                style={{
                                    minWidth: 800,
                                    maxWidth: '100%',
                                }}
                            >
                                <Row gutter={[16, 16]}>
                                    <Col span={12}>
                                        <Space direction='vertical'>
                                            <UploadModel multiple={false} form_name="photo" image_length={1} uploadTxt="上传企业照片" image_type={3} imageUrl={detail?.photo} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                            <ProFormRadio.Group
                                                name="photo_status"
                                                label="企业照片审核状态"
                                                fieldProps={{
                                                    buttonStyle: 'solid'
                                                }}
                                                options={[
                                                    {
                                                        label: '待审',
                                                        value: 1,
                                                    },
                                                    {
                                                        label: '通过',
                                                        value: 2,
                                                    },
                                                    {
                                                        label: '不通过',
                                                        value: 3,
                                                    }
                                                ]}
                                            />
                                        </Space>
                                    </Col>
                                    <Col span={12}>
                                        <Space direction='vertical'>
                                            <UploadModel multiple={false} form_name="license_path" image_length={1} uploadTxt="上传营业执照" imageUrl={detail?.license_path} image_type={4} onUploadComplete={handleFileUploadedlicense}></UploadModel>
                                            <ProFormRadio.Group
                                                name="license_status"
                                                label="营业执照审核状态"
                                                fieldProps={{
                                                    buttonStyle: 'solid'
                                                }}
                                                options={[
                                                    {
                                                        label: '待审',
                                                        value: 1,
                                                    },
                                                    {
                                                        label: '通过',
                                                        value: 2,
                                                    },
                                                    {
                                                        label: '不通过',
                                                        value: 3,
                                                    }
                                                ]}
                                            />
                                        </Space>
                                    </Col>
                                    {
                                        detail ?
                                            <Col span={24} style={{ display: 'flex' }}>
                                                <UploadModel multiple={true} form_name="photo" image_length={1} uploadTxt="企业相册" image_type={3} onUploadComplete={handleFileUploadedphotos}></UploadModel>
                                                {uploadedFilephotosName && uploadedFilephotosName.length > 0 ? uploadedFilephotosName.map((item: any, index: number) => (<>
                                                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                        <Button size='small' type='link' onClick={() => {
                                                            uploadedFilephotosName.splice(index, 1)
                                                            setUploadedFilephotosName([...uploadedFilephotosName])
                                                        }}>删除</Button>
                                                        <Image src={`${Imageprefix}${item.photo}`} style={{ marginTop: '8px', marginLeft: '16px', width: '100px', height: '100px' }}></Image>
                                                    </div>
                                                </>)) : ''}
                                            </Col> : <>
                                                <Col span={24} style={{ display: 'flex' }}>
                                                    <UploadModel multiple={true} form_name="license_path" image_length={5} uploadTxt="企业相册" image_type={3} onUploadComplete={handleFileUploadedphotos}></UploadModel>
                                                    {uploadedFilephotosName && uploadedFilephotosName.length > 0 ? uploadedFilephotosName.map((item: any, index: number) => (<>
                                                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                            <Button size='small' type='link' onClick={() => {
                                                                uploadedFilephotosName.splice(index, 1)
                                                                setUploadedFilephotosName([...uploadedFilephotosName])
                                                            }}>删除</Button>
                                                            <Image src={`${Imageprefix}${item.photo}`} style={{ marginTop: '8px', marginLeft: '16px', width: '100px', height: '100px' }}></Image>
                                                        </div>
                                                    </>)) : ''}
                                                </Col>
                                            </>
                                    }
                                </Row>
                            </ProCard>
                        </StepsForm.StepForm>
                        <StepsForm.StepForm
                            title="登录密码"
                            onFinish={async (values) => {
                                return true;
                            }}
                        >
                            <ProCard
                                ghost
                                style={{
                                    minWidth: 800,
                                    maxWidth: '100%',
                                }}
                            >
                                <Row gutter={[16, 16]}>
                                    <Col span={24}>
                                        {id ? <ProFormText.Password
                                            name="login_pwd"
                                            label="登录密码"
                                            fieldProps={{
                                                size: 'large',
                                            }}
                                            placeholder={'请输入登录密码'}

                                        /> : <ProFormText.Password
                                            name="login_pwd"
                                            label="登录密码"
                                            fieldProps={{
                                                size: 'large',
                                            }}
                                            placeholder={'请输入登录密码'}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入登录密码',
                                                },
                                            ]}
                                        />}

                                    </Col>

                                </Row>
                            </ProCard>
                        </StepsForm.StepForm>
                    </StepsForm>

                </Modal>

            </ConfigProvider>

        </>
    );
};


export default connect(({ dictModel, openModel }: any) => ({
    dictModel, openModel
}))(PagesMainCompanyListCreate);
