import React, { Fragment, useState, useEffect, useLayoutEffect, useContext,useRef } from 'react';
import { ActivityIndicator, Text } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { filterValue } from '~/Components/Listing/Search';
import { useAuth } from '~/Components/Hooks';
import { usePhone } from '~/Components/UIControls/Phone';

const titleWidth = 130;

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const setEditable = (value) => { navigation.setParams({editable: value}) };
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const userId = navigation.getParam('userId', '');
    const { auth } = useAuth(navigation);
    const { showMessage } = useToast();

    const [ready, setReady] = useState(false);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [companyId,setCompanyId] = useState('');
    //고용형태
    const employmentType = useRef([ 
        {label:'정규직', value:'1'}, 
        {label:'비정규직', value:'2'}
    ]);
    //근무상태
    const employmentStatus = useRef([ 
        {label:'재직', value:'1'}, 
        {label:'휴직', value:'2'},
        {label:'퇴직', value:'3'}
    ]);
    //console.log(data);
    // mount
    useEffect(() => {
        fetch();
    }, [editable]);

    // unmount
    useEffect(() => () => {
    }, []);

    // popup
    const { openPopup } = usePopup();
    
    // phone
    const { showCallOrMessageSelector } = usePhone();

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const fetch = async () => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                console.log('get - ', `api/app/users/GetByUserId?siteId=${siteId}&userId=${userId}`);
                const result = await fetchGet(`api/app/users/GetByUserId?siteId=${siteId}&userId=${userId}`);
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setReady(false);
        setReady(true);
        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        await fetch();
        setEditable(true);
    }

    // cancel edit
    const onCancelEdit = async () => {
        await fetch();
        setEditable(false);
    }
 
    // save
    const onSave = async form => {
        console.log("onSave");
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            const submit = {...form,
                SiteId: siteId
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/users/Save', submit);

                showMessage('저장되었습니다.');
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    setEditable(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    // delete
    const onDelete = async () => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제','삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/app/users/${siteId}/${userId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }
    return (  
        <BottomTabBarLayout>
        {ready ? (
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <Form.Field>
                    <Form.TitleTop style={{width:titleWidth}}><Form.Label>사진</Form.Label></Form.TitleTop>
                    <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.CmFile}
                    onUpload={(isUpload, result) => {
                        Form.uploadFile("CmFile", isUpload, result);
                    }} onDelete={() => {
                        Form.deleteFile("CmFile");
                    }} />
                </Form.Field>
                <Form.RegistFile editable={editable} name="CmFile" value={data.CmFile} />

                <Form.Field> 
                <Form.Require style={{width:titleWidth}}><Form.Label>아이디</Form.Label></Form.Require>
                    <Form.Input placeholder="아이디" defaultValue={data.UserId} 
                                onChangeText={text => setValue('UserId', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="UserId" rule={{required:'아이디를 입력하세요.'}} error={errors.UserId} />
                {action != Form.CREATE && editable && (
                    <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>비밀번호</Form.Label></Form.Title>
                    <Form.Input placeholder="입력 안할경우 변경 안됨" defaultValue={""} secureTextEntry={true}
                                onChangeText={text => setValue('Passwd', text, true)} 
                                editable={editable} returnKeyType="next" />
                    <Form.Regist editable={editable} name="Passwd" />
                    </Form.Field>
                )}
                {action == Form.CREATE && (
                    <Fragment>
                    <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>비밀번호</Form.Label></Form.Require>
                    <Form.Input placeholder="비밀번호" defaultValue={""} secureTextEntry={true}
                                onChangeText={text => setValue('Passwd', text, true)} 
                                editable={editable} returnKeyType="next" />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Passwd" rule={{required:'비밀번호를 입력하세요.'}} error={errors.Passwd} />    
                    </Fragment>
                )}                
                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>이름</Form.Label></Form.Require>
                    <Form.Input placeholder="이름" defaultValue={data.Name} 
                                onChangeText={text => setValue('Name', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Name" rule={{required:'이름을 입력하세요.'}} error={errors.Name} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>직위</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmPosition" defaultLabel="직위"
                        selectedValue={data.PositionId} selectedText={data.PositionName} editable={editable} useCheck={true}
                        onChange={(item) => { setValue('PositionId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='PositionId' rule={{required:'직위를 선택하세요.'}} error={errors.PositionId} />
                
                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>회사</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmCompany" defaultLabel="회사"  siteId={session.getSiteId()} 
                        selectedValue={data.CompanyId} selectedText={data.CompanyName} editable={editable} useCheck={true}
                        onChange={(item) => { 
                            setValue('CompanyId', item.value, true);
                            setCompanyId(item.value);
                            //this.setState(companyId:item.value);
                            
                        }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="CompanyId" rule={{required:'회사를 선택하세요.'}} error={errors.CompanyId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>부서</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmDepartment" defaultLabel="부서" siteId={session.getSiteId()} 
                        selectedValue={data.DepartmentId} editable={editable} where={companyId != '' ? `CompanyId=${companyId}`:'' }
                        selectedText={data.DepartmentName} useCheck={true}
                        onChange={(item) => { setValue('DepartmentId', item.value, true) }}  />                        
                </Form.Field>
                <Form.Regist editable={editable} name="DepartmentId" rule={{required:'부서를 선택하세요.'}} error={errors.DepartmentId} />
                
                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>업무분야</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmBusinessField" defaultLabel="업무분야" auth={auth}
                        selectedValue={data.BusinessFieldId} selectedText={data.BusinessFieldName} editable={editable} useCheck={true}
                        onChange={(item) => { setValue('BusinessFieldId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="BusinessFieldId" rule={{required:'업무분야를 선택하세요.'}} error={errors.BusinessFieldId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>권한그룹</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmUserGroup" defaultLabel="권한그룹" siteId={session.getSiteId()} 
                        selectedValue={data.UserGroupId} editable={editable}
                        onChange={(item) => { setValue('UserGroupId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="UserGroupId" rule={{required:'권한그룹을 선택하세요.'}} error={errors.UserGroupId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>고용형태</Form.Label></Form.Require>
                    <Selectbox style={{flex : 1}} initialValue={true} defaultLabel="고용형태"
                        items={employmentType.current}  editable={editable} selectedValue={data.EmploymentType}
                        onChange={item => {
                            setValue('EmploymentType', item.value, true);
                        }} />
                </Form.Field>
                <Form.Regist editable={editable} name="EmploymentType"  />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>근무상태</Form.Label></Form.Require>
                    <Selectbox style={{flex : 1}} initialValue={true} defaultLabel="근무상태"
                        items={employmentStatus.current}  editable={editable} selectedValue={data.EmploymentStatus}
                        onChange={item => {
                            setValue('EmploymentStatus', item.value, true);
                        }} />
                </Form.Field>
                <Form.Regist editable={editable} name="EmploymentStatus" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>이동전화</Form.Label></Form.Title>
                    <Form.Input placeholder="이동전화" defaultValue={data.MobilePhoneNo} 
                                onChangeText={text => setValue('MobilePhoneNo', text, true)} 
                                onPress={text => { 
                                    showCallOrMessageSelector(text);
                                }}
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="MobilePhoneNo" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>사무실전화</Form.Label></Form.Title>
                    <Form.Input placeholder="사무실전화" defaultValue={data.OfficePhoneNo} 
                                onChangeText={text => setValue('OfficePhoneNo', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="OfficePhoneNo" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>이메일</Form.Label></Form.Title>
                    <Form.Input placeholder="이메일" defaultValue={data.Email} 
                                onChangeText={text => setValue('Email', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Email" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>입사일</Form.Label></Form.Title>
                    <Form.DatePicker date={data.EnterDate} onChange={(newDate) => setValue('EnterDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="EnterDate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>퇴사일</Form.Label></Form.Title>
                    <Form.DatePicker date={data.RetireDate} onChange={(newDate) => setValue('RetireDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="RetireDate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>자격증</Form.Label></Form.Title>
                    <Form.Input placeholder="자격증" defaultValue={data.Certificated} 
                                onChangeText={text => setValue('Certificated', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Certificated" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>모바일접근권한</Form.Label></Form.Title>
                    <Form.Switch initialValue={data.IsMobile} onValueChange={(newValue) => { setValue('IsMobile', newValue) }} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="IsMobile" />

                <Form.Field>
                    <Form.TitleTop style={{width:titleWidth}}><Form.Label>결제싸인이미지</Form.Label></Form.TitleTop>
                    <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.CmFile1}
                    onUpload={(isUpload, result) => {
                        Form.uploadFile("CmFile1", isUpload, result);
                    }} onDelete={() => {
                        Form.deleteFile("CmFile1");
                    }} />
                </Form.Field>
                <Form.RegistFile editable={editable} name="CmFile1" value={data.CmFile1} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>비고</Form.Label></Form.Title>
                    <Form.Input placeholder="비고" defaultValue={data.Comment} 
                                onChangeText={text => setValue('Comment', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Comment" />

                <Form.Field style={{ height:30 }}>
                </Form.Field>
                
            </Form.Container>
        ) : (
            <Form.Loading />
        )}
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);
    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`사용자관리`}
                main={false}
                buttons={
                    <Fragment>
                    {!editable && (
                        <Fragment>
                            {auth.Update && <Form.EditButton navigation={navigation} type="primary" onPress={()=>{
                                navigation.setParams({action:Form.EDIT})                                                                
                            }} />}
                            {auth.Delete &&  <Form.DeleteButton />}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && <Form.SaveButton type="primary" />}
                            {action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;