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 } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { LongPressGestureHandler } from 'react-native-gesture-handler';

const Screen = ({ navigation}) => {
  console.log("const Screen = ({ navigation}) => {");
  const action = navigation.getParam('action', Form.VIEW);
  
  const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
  const isCreate = action == Form.CREATE  ? true : false;
  const setEditable = (value) => { navigation.setParams({editable: value}) };
  const setRegisterUserId = (value) => { navigation.setParams({registerUserId: value}) };
  const refreshList = navigation.getParam('refreshList', ()=>{});
  const siteId = navigation.getParam('siteId', '');
  const guidelineId = navigation.getParam('guidelineId', '0');
  const { auth, userinfo } = useAuth(navigation);
  const { showMessage } = useToast();
  
  const [ready, setReady] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({});
  
  
  // mount
  useEffect(() => {
      fetch();
  }, [editable]);

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

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

  // 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/Guideline/Get?siteId=${siteId}&guidelineId=${guidelineId}`);
        const result = await fetchGet(`api/app/Guideline/Get?siteId=${siteId}&guidelineId=${guidelineId}`);
        setData(result);
        setRegisterUserId(result.RegisterUserId);
        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 => {
      if (loading) {
        showMessage('저장중입니다. 잠시만기다려 주세요.');
        return;
      }
      confirm('저장', '저장하시겠습니까?', async () => {    
      setLoading(true);

      const submit = { ...form, 
        SiteId: siteId,
        GuidelineId:guidelineId,
        RegisterUserId: session.getUserInfo("UserId"),
        CmFile: !form.CmFile.IsUpload && !form.CmFile.IsDelete ? null : form.CmFile,
      };
      console.log('submit data', submit);
      try {

        const result = await fetchPost('api/app/Guideline/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/Guideline/${siteId}/${guidelineId}`);

            showMessage('삭제되었습니다.');
            refreshList();
            navigation.pop();
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
    });
  }
  
 console.log('data' +data.IsAllView);
 console.log(userinfo);
//console.log(data);
  return (

    <BottomTabBarLayout>
      {ready ? (
        <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
          <Form.Field>
            <Form.Require><Form.Label>제목</Form.Label></Form.Require>
            <Form.Input defaultValue={data.Title} onChangeText={text => setValue('Title', text, true)} editable={editable} />
          </Form.Field>
          <Form.Regist editable={editable} name="Title" rule={{required:'제목을 입력하세요.'}} error={errors.Title} />

          <Form.Field>
            <Form.Require><Form.Label>업무분야</Form.Label></Form.Require>
            <Form.EntitySelect entity="CmBusinessField" defaultLabel="업무분야"
                        selectedValue={data.BusinessFieldId} selectedText={Util.get(data, "CmBusinessField.Name")} 
                        editable={editable} auth={auth} 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><Form.Label>등록일</Form.Label></Form.Require>          
            <Form.DatePicker date={data.AddDate} onChange={(newDate) => setValue('AddDate', newDate, true)} editable={isCreate} />
          </Form.Field>
          <Form.Regist editable={editable} name="AddDate" rule={{required:'등록일을 입력하세요.'}} error={errors.AddDate} />

          <Form.Field>
            <Form.Require><Form.Label>만료일</Form.Label></Form.Require>
            <Form.DatePicker date={data.UpdateDate} onChange={(newDate) => setValue('UpdateDate', newDate, true)} editable={editable} />
            {editable && (
              <Form.DefaultButton style={[{paddingLeft:10, paddingTop:0}]} buttonStyle={{height:39}} onPress={checked => {
                  setData({...data, UpdateDate:'9999-12-31'});
                  setValue('UpdateDate', '9999-12-31');
              }}>무기한</Form.DefaultButton>
            )}
          </Form.Field>
          <Form.Regist editable={editable} name="UpdateDate" rule={{required:'만료일을 입력하세요.'}} error={errors.UpdateDate}  />

          <Form.Field>
            <Form.Require><Form.Label>조회수</Form.Label></Form.Require>
            <Form.Input value={data.ReadCount} defaultValue={data.ReadCount} editable={false} />
          </Form.Field>

          <Form.Field>
            <Form.Require><Form.Label>내용</Form.Label></Form.Require>
            <Form.Input defaultValue={data.Contents} onChangeText={text => setValue('Contents', text, true)} 
                        multiline={true} editable={editable} />
          </Form.Field>
          <Form.Regist editable={editable} name="Contents" rule={{required:'내용을 입력하세요.'}} error={errors.Contents} />

          <Form.Field>
            <Form.TitleTop><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={Util.get(data, "CmFile")} />
            
          {userinfo.IsAdmin && editable ? (
            <Fragment>
              <Form.Field>
                <Form.Title><Form.Label>본사지침</Form.Label></Form.Title>
                <Form.Switch initialValue={data.IsAllView} onValueChange={(newValue) => { setValue('IsAllView', newValue) }} editable={editable} />
                <Form.Regist editable={editable} name="IsAllView" />
              </Form.Field>
            </Fragment>
          ) : null}
        </Form.Container>
      ) : (
        <Form.Loading /> 
      )}
    </BottomTabBarLayout>
  );
};

Screen.navigationOptions = ({ navigation} ) => {
  console.log("Screen.navigationOptions = ({ navigation} ) => {");
  const action = navigation.getParam('action', Form.VIEW); // create, edit, view
  const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
  const registerUserId = navigation.getParam('registerUserId', '');
  const { auth } = useAuth(navigation);
  console.log(registerUserId);
  return {
    
    header: () => (
      <Header
        navigation={navigation}
        title="관리지침"
        main={false}
        buttons={
            <Fragment>
              {!editable && registerUserId == session.getUserInfo("UserId") && (
                  <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;
