
import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProFormText,
    ProFormSegmented,
    ProFormSelect,
    ProForm,
    FormControlRender,
    ProFormDependency,
    ProFormCascader
} from '@ant-design/pro-components';
import { ConfigProvider, Flex, Space, Modal, message, Image, Row, Col, Switch, Form, Typography } from 'antd';
import { GetRoleList, addAccount, updateAccount, getUserDetail } from '@/apis/api';
import { Imageprefix } from '@/constants';
import UploadModel from '@/components/Common/upload';


const selectfieldNames = { label: 'name', value: 'id' };
const cascaderfieldNames = { label: 'name', value: 'id', children: 'children' };


const PagesPermissionAccountCreate: React.FC = ({ dispatch, dictModel, openModel, id }: any) => {
    const formRef = useRef<ProFormInstance>();
    const [openPreview, setOpenPreview] = useState(false);
    const [detail, setDetail] = useState<PermissionType.account | null>(null)

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

    const [uploadedFilephotoName, setUploadedFilephotoName] = useState<string>('');
    const handleFileUploadedphoto = (filename: string) => {
        setUploadedFilephotoName(filename);
    };

    useEffect(() => {
        dispatch({ type: 'dictModel/getList', payload: { code: 2009, type: 'setAreaList' } })

    }, [])

    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 })
                    }}
                >
                    <ProForm<PermissionType.account>
                        formRef={formRef}
                        request={async () => {
                            if (id) {
                                let res = await getUserDetail({ id: id })
                                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
                                ];
                                res.data.roleids = res.data.roleids.length > 0 ? res.data.roleids.split(',').map(Number) : []
                                setDetail(res.data)
                                return res.data;
                            } else {
                                return {
                                    mobile: '',
                                    password: '',
                                    repassword: '',
                                    nickname: '',
                                    avatar: '',
                                    email: '',
                                    roleids: [],
                                }
                            }
                        }}
                        submitter={{
                            searchConfig: {
                                resetText: '取消',
                                submitText: '保存',
                            },
                            render: (_, dom) => { return <Flex justify='flex-end'> <Space>{dom}</Space></Flex> },
                            onReset: () => {
                                setDetail(null)
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            }
                        }}
                        onFinish={async (values) => {
                            values.province = values.location_arr && values.location_arr.length > 0 && values.location_arr[0] ? values.location_arr[0] : 0;
                            values.city = values.location_arr && values.location_arr.length > 0 && values.location_arr[1] ? values.location_arr[1] : 0;
                            values.district = values.location_arr && values.location_arr.length > 0 && values.location_arr[2] ? values.location_arr[2] : 0;
                            values.street = values.location_arr && values.location_arr.length > 0 && values.location_arr[3] ? values.location_arr[3] : 0;
                            delete values.location_arr;
                            values.roleids = values.roleids.join(',')
                            console.log(values.roleids)
                            if (id) {
                                values.id = id;
                                let res = await updateAccount(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            } else {
                                let res = await addAccount(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            }
                        }}
                    >
                        <Row gutter={[16, 16]}>
                            {
                                detail ?
                                    <Col span={24} style={{ display: 'flex' }}>
                                        <UploadModel multiple={false} form_name="cover_img" image_length={1} uploadTxt="上传封面图" image_type={3} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                        {uploadedFilephotoName ? <Image src={`${Imageprefix}${uploadedFilephotoName}`} style={{ marginLeft: '16px', marginTop: '32px', width: '100px', height: '100px' }}></Image> : <Image src={`${Imageprefix}${detail?.cover_img}`} style={{ marginLeft: '16px', marginTop: '32px', width: '100px', height: '100px' }}></Image>}
                                    </Col> : <>
                                        <Col span={24} style={{ display: 'flex' }}>
                                            <UploadModel multiple={false} form_name="cover_img" image_length={1} uploadTxt="上传封面图" image_type={3} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                            {uploadedFilephotoName ? <Col span={8}> <Image src={`${Imageprefix}${uploadedFilephotoName}`} style={{ marginTop: '32px', width: '100px', height: '100px' }}></Image> </Col> : ''}
                                        </Col>
                                    </>
                            }
                            <Col span={12}>
                                <ProFormText
                                    label="手机号"
                                    name="mobile"
                                    placeholder="请输入手机号"
                                    rules={[{ required: true, message: '请输入手机号' }]}
                                />
                            </Col>

                            <Col span={12}>
                                <ProFormText.Password
                                    label="密码"
                                    name="password"
                                    placeholder="请输入密码"
                                    rules={[{ required: true, message: '请输入密码' }]}
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormText.Password
                                    label="确认密码"
                                    name="repassword"
                                    placeholder="请输入确认密码"
                                    rules={[{ required: true, message: '请输入确认密码' }]}
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormText
                                    label="昵称"
                                    name="nickname"
                                    placeholder="请输入昵称"
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormText
                                    label="邮箱"
                                    name="email"
                                    placeholder="请输入邮箱"
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormSelect
                                    showSearch
                                    name="roleids"
                                    label="选择角色"
                                    placeholder="请选择角色"
                                    fieldProps={{
                                        fieldNames: selectfieldNames,
                                        mode: 'multiple'
                                    }}
                                    request={(keyword) =>
                                        GetRoleList({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                            return res.data.roles.filter(item => item.id !== 3);
                                        })
                                    }
                                    rules={[{ required: true, message: '请输入确认密码' }]}
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormCascader
                                    label="选择社区"
                                    name="location_arr"
                                    fieldProps={{
                                        fieldNames: cascaderfieldNames,
                                        options: dictModel.areaList,
                                        changeOnSelect: true
                                    }}
                                    placeholder="企业所在地区"
                                />
                            </Col>
                        </Row>









                    </ProForm>
                </Modal>
            </ConfigProvider>
        </>
    );
};



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