import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator } 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, Controller } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';

const titleWidth = 120;

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 facilityCode = navigation.getParam('facilityCode', 0);
    const { auth } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ IsUse: true });
    const [variable, setVariable] = useState({
        FacilityTypeId: ''
    });

    // mount
    useEffect(() => {
        fetch(false);
    }, []);

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

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

    // popup
    const { openPopup } = usePopup();

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

        if(action != Form.CREATE) {
            try {
                console.log('get - ', `api/app/Facility/Get?siteId=${siteId}&facilityCode=${facilityCode}`);
                const result = await fetchGet(`api/app/Facility/Get?siteId=${siteId}&facilityCode=${facilityCode}`);
                setData(result);
                setVariable({ FacilityTypeId: result.FacilityTypeId });
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            Form.setFormData(data);
        }

        setLoading(false);
    }

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

    // cancel edit
    const onCancelEdit = async () => {
        setEditable(false);
    }

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            const submit = {...form,
                SiteId: siteId,
                FacilityCode: facilityCode,
                CmFile: !form.CmFile.IsUpload && !form.CmFile.IsDelete ? null : form.CmFile,
            };
            if([80,81,82].indexOf(variable.FacilityTypeId) == -1) {
                submit.Multiple = 1;
            }
            console.log('submit data', submit);

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

                showMessage('저장되었습니다.');
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    fetch(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/facility/${siteId}/${facilityCode}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <BottomTabBarLayout>
            <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.EntitySelect entity="BemsFacilityType" defaultLabel="시설유형" 
                        selectedValue={data.FacilityTypeId} editable={editable}
                        where={`FacilityTypeId NOT IN (99, 100, 101, 102, 103)`}
                        onChange={(item) => { 
                            setValue('FacilityTypeId', item.value, true);
                            setVariable({...variable, FacilityTypeId: item.value});
                        }}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="FacilityTypeId" rule={{required:'시설유형을 선택하세요.'}} error={errors.FacilityTypeId} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>종류</Form.Label></Form.Title>
                    <Form.Input placeholder="종류" defaultValue={data.DeviceType} onChangeText={text => setValue('DeviceType', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="DeviceType" />

                <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} />
                </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.Input placeholder="시설용도" defaultValue={data.FacilityUsage} onChangeText={text => setValue('FacilityUsage', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="FacilityUsage" rule={{required:'시설용도를 입력하세요.'}} error={errors.FacilityUsage} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>제조업체</Form.Label></Form.Title>
                    <Form.Input placeholder="제조업체" defaultValue={data.Manufacturer} onChangeText={text => setValue('Manufacturer', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Manufacturer" />

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

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>사용여부</Form.Label></Form.Title>
                    <Form.Switch initialValue={data.IsUse} onValueChange={(newValue) => { setValue('IsUse', newValue) }} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="IsUse" />

                <Form.Field>
                    <Form.RequireTop style={{width:titleWidth}}><Form.Label>시설분류</Form.Label></Form.RequireTop>
                    <Form.Group>
                        <Form.EntitySelect entity="FmsFacilityCodeClass" useCheck={true} defaultLabel="분류1"
                            where={"ParentFacilityClassId IS NULL"} id="FacilityClassId" name="Name"
                            selectedValue={data.FirstClassId} selectedText={Util.get(data, "FirstClass.Name")}
                            editable={editable} style={{marginBottom:5}}
                            onChange={(item) => { 
                                console.log('onchange category 1 - ' + item.value); 
                                setData({...data, FirstClassId : item.value, SecondClassId: '', ThirdClassId: ''});
                                setValue('FirstClassId', item.value, true);
                                setValue('SecondClassId', '', true);
                                setValue('ThirdClassId', '', true);
                            }}  />
                        <Form.Regist editable={editable} name="FirstClassId" rule={{required:'시설분류를 선택하세요.'}} error={errors.FirstClassId}/>

                        <Form.EntitySelect entity="FmsFacilityCodeClass" useCheck={true} defaultLabel="분류2"
                            where={`ParentFacilityClassId = '${data.FirstClassId}'`} id="FacilityClassId" name="Name" 
                            selectedValue={data.SecondClassId} selectedText={Util.get(data, "SecondClass.Name")}
                            editable={editable} style={{marginBottom:5}}
                            onChange={(item) => { 
                                console.log('onchange category 2 - ' + item.value); 
                                setData({...data, SecondClassId : item.value, ThirdClassId: ''});
                                setValue('SecondClassId', item.value, true); 
                                setValue('ThirdClassId', '', true);
                            }}  />
                        <Form.Regist editable={editable} name="SecondClassId" />

                        <Form.EntitySelect entity="FmsFacilityCodeClass" useCheck={true} defaultLabel="분류3"
                            where={`ParentFacilityClassId = '${data.SecondClassId}'`} id="FacilityClassId" name="Name"
                            selectedValue={data.ThirdClassId} selectedText={Util.get(data, "ThirdClass.Name")}
                            editable={editable} style={{marginBottom:5}}
                            onChange={(item) => { 
                                console.log('onchange category 3 - ' + item.value); 
                                setData({...data, ThirdClassId : item.value});
                                setValue('ThirdClassId', item.value, true);
                            }}  />
                        <Form.Regist editable={editable} name="ThirdClassId"/>
                    </Form.Group>
                </Form.Field>

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>시설용량</Form.Label></Form.Title>
                    <Form.Input placeholder="시설용량" defaultValue={data.FacilityCapacity} 
                        onChangeText={text => setValue('FacilityCapacity', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="FacilityCapacity" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>QR코드</Form.Label></Form.Title>
                    <Form.Input placeholder="QR코드" defaultValue={data.Rfid} 
                        onChangeText={text => setValue('Rfid', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Rfid" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>정격전력소비량</Form.Label></Form.Title>
                    <Form.Input placeholder="전력소비량" defaultValue={data.RatedPowerConsumption} 
                        onChangeText={text => setValue('RatedPowerConsumption', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="RatedPowerConsumption" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>정격COP</Form.Label></Form.Title>
                    <Form.Input placeholder="정격COP" defaultValue={data.RatedCop} 
                        onChangeText={text => setValue('RatedCop', text, true)} 
                        editable={editable} keyboardType="numeric" />
                </Form.Field>
                <Form.Regist editable={editable} name="RatedCop" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>제조번호</Form.Label></Form.Title>
                    <Form.Input placeholder="제조번호" defaultValue={data.ManufactureSerial} 
                        onChangeText={text => setValue('ManufactureSerial', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="ManufactureSerial" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>제조모델</Form.Label></Form.Title>
                    <Form.Input placeholder="제조모델" defaultValue={data.ManufactureModel} 
                        onChangeText={text => setValue('ManufactureModel', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="ManufactureModel" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>납품업체</Form.Label></Form.Title>
                    <Form.Input placeholder="납품업체" defaultValue={data.Supplier} 
                        onChangeText={text => setValue('Supplier', text, true)} 
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Supplier" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>업체전화</Form.Label></Form.Title>
                    <Form.Input placeholder="업체전화" defaultValue={data.SupplierPhoneNo} 
                        onChangeText={text => setValue('SupplierPhoneNo', text, true)} 
                        editable={editable} keyboardType="phone-pad" autoCompleteType="tel" />
                </Form.Field>
                <Form.Regist editable={editable} name="SupplierPhoneNo" />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>설치위치</Form.Label></Form.Title>
                    <Form.EntitySelect entity="CmBuilding" useCheck={true} defaultLabel="빌딩" siteId={session.getSiteId()}
                                selectedValue={data.BuildingId} selectedText={Util.get(data, "Building.Name")} editable={editable}
                                onChange={(item) => { 
                                    setData({...data, BuildingId : item.value, FloorId: '', ZoneId: ''});
                                    setValue('BuildingId', item.value, true);
                                    setValue('FloorId', '', true);
                                    setValue('ZoneId', '', true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="BuildingId" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label></Form.Label></Form.Title>
                    <Form.EntitySelect entity="CmFloor" defaultLabel="층" siteId={session.getSiteId()}
                                where={`BuildingId = '${data.BuildingId}'`} 
                                selectedValue={data.FloorId} editable={editable}
                                onChange={(item) => { 
                                    setData({...data, FloorId: item.value, ZoneId: ''});
                                    setValue('FloorId', item.value, true);
                                    setValue('ZoneId', '', true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="FloorId" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label></Form.Label></Form.Title>
                    <Form.EntitySelect entity="CmZone" defaultLabel="구역" siteId={session.getSiteId()}
                                where={`BuildingId = '${data.BuildingId}' AND FloorId = '${data.FloorId}'`} 
                                selectedValue={data.ZoneId} editable={editable}
                                onChange={(item) => { 
                                    setData({...data, ZoneId: item.value});
                                    setValue('ZoneId', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="ZoneId" />

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

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>운전시작일</Form.Label></Form.Title>
                    <Form.DatePicker date={data.OperationStartDate} onChange={(newDate) => setValue('OperationStartDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="OperationStartDate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>정담당자</Form.Label></Form.Title>
                    <Form.PopupSelect 
                        path="/Popup/User/Index" popupProps={{siteId}} 
                        emptyLabel="정담당자" defaultLabel={Util.get(data, 'MainContactor.Name')} editable={editable}
                        onSelect={(result) => {
                            setValue('MainContactorUserId', result.UserId, true);
                        }}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="MainContactorUserId" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>부담당자</Form.Label></Form.Title>
                    <Form.PopupSelect 
                        path="/Popup/User/Index" popupProps={{siteId}} 
                        emptyLabel="부담당자" defaultLabel={Util.get(data, 'SubContactor.Name')} editable={editable}
                        onSelect={(result) => {
                            setValue('SubContactorUserId', result.UserId, true);
                        }}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="SubContactorUserId" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>시설비용</Form.Label></Form.Title>
                    <Form.Input placeholder="시설비용" defaultValue={data.FacilityCost} 
                        onChangeText={text => setValue('FacilityCost', text, true)} 
                        editable={editable} keyboardType="number-pad" />
                </Form.Field>
                <Form.Regist editable={editable} name="FacilityCost" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>시설수량</Form.Label></Form.Title>
                    <Form.Input placeholder="시설수량" defaultValue={data.FacilityCount} 
                        onChangeText={text => setValue('FacilityCount', text, true)} 
                        editable={editable} keyboardType="number-pad" />
                </Form.Field>
                <Form.Regist editable={editable} name="FacilityCount" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>연료종류</Form.Label></Form.Title>
                    <Form.EntitySelect entity="BemsFuelType" defaultLabel="연료종류"
                                selectedValue={data.FuelTypeId} editable={editable}
                                onChange={(item) => { 
                                    setValue('FuelTypeId', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="FuelTypeId" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>계약종류</Form.Label></Form.Title>
                    <Form.EntitySelect entity="FmsContractType" defaultLabel="계약종류"
                                selectedValue={data.ContractType} selectedText={data.ContractTypeName} editable={editable} useCheck={true}
                                onChange={(item) => { 
                                    setValue('ContractType', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="ContractType" />

                {([80,81,82].indexOf(variable.FacilityTypeId) != -1) && (
                    <Fragment>
                        <Form.Field>
                            <Form.Title style={{width:titleWidth}}><Form.Label>검침배수</Form.Label></Form.Title>
                            <Form.Input placeholder="검침배수" defaultValue={data.Multiple} 
                                onChangeText={text => setValue('Multiple', text, true)} 
                                editable={editable} keyboardType="number-pad" />
                        </Form.Field>
                        <Form.Regist 
                            editable={editable} 
                            name="Multiple"
                            rule={{
                                required: '검침배수를 입력하세요.',
                                pattern: {
                                    value: /^[0-9]+[\.]?[0-9]*$/,
                                    message: '검침배수는 숫자만 입력 가능합니다.',
                                }
                            }} 
                            error={errors.PrevPinValue} 
                        />
                    </Fragment>
                )}

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

                <Form.Field style={{ height:30 }}>
                </Form.Field>

            </Form.Container>
        </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" />)}
                            {auth.Delete && (<Form.DeleteButton />)}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && (<Form.SaveButton type="primary" />)}
                            {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;