import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, View, 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 UploadFile, { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import { WebView } from 'react-native-webview';
import { ListStyle } from '~/Components/Listing/Search';
import { Util } from '~/Utils/utils';
import Loading from '~/Components/UIControls/Loading';
import { Tab, TabHeader, TabTitleGroup, TabTitle, TabContent, TabItem } from '~/Components/UIControls/Tab';
import FacilityList from './FacilityList';
import { TouchableOpacity } from 'react-native-gesture-handler';

let headerScript = ``;
headerScript += ``;

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', 0);
    const seq = navigation.getParam('seq', 0);
    const tab = navigation.getParam('tab', 'report-history-form');
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});

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

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

    // search
    const fetch = async (editable = false) => {
        setLoading(true);
        await session.load();

        if (action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/ReportHistory/Get?siteId=${siteId}&seq=${seq}`);
                setData(result);
                setEditable(editable);
            } catch (error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    };

    return (
        <BottomTabBarLayout>
            <Tab>
                <TabHeader>
                    <TabTitleGroup top={true}>
                        <TabTitle
                            onPress={() => {
                                navigation.setParams({ tab: 'report-history-form' });
                            }}
                            active={tab == 'report-history-form' ? true : false}
                            title="일지정보"
                        />
                        <TabTitle
                            onPress={() => {
                                navigation.setParams({ tab: 'relative-facility-list' });
                            }}
                            active={tab == 'relative-facility-list' ? true : false}
                            title="연관시설목록"
                        />
                    </TabTitleGroup>
                </TabHeader>
                <TabContent>
                    <TabItem active={tab == 'report-history-form' ? true : false}>
                        <View style={{ padding: 5, flex: 1 }}>
                            <View style={[ListStyle.vertical, { padding: 10, borderBottomWidth: 1, borderBottomColor: '#f0f0f0' }]}>
                                <Text style={[ListStyle.text]}>{Util.get(data, 'ReportName')}</Text>
                                <View style={[ListStyle.horizon]}>
                                    <Text style={[ListStyle.textGray, { flex: 1 }]}>{Util.get(data, 'BusinessFieldName')}</Text>
                                    <Text style={[ListStyle.textGray]}>{Util.get(data, 'FormatName')}</Text>
                                </View>
                                <View style={[ListStyle.horizon]}>
                                    <Text style={[ListStyle.textGray, { flex: 1 }]}>첨부파일</Text>
                                    <TouchableOpacity onPress={() => { Util.downloadFile(Util.get(data, 'CmFile')) }}>
                                        <Text style={[ListStyle.textGray]}>{Util.get(data, 'CmFile.Name')}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            <WebView
                                originWhitelist={['*']}
                                source={{
                                    html: `<!DOCTYPE html>
                                <html>
                                <head>
                                <style type='text/css'>
                                .stamp {
                                    max-height: 50px;
                                }
                                </style>
                                </head>
                                <body>
                                <div id='ubitems-fixed-content' style='display:inline-block; position:relative;'>
                                ${`
                                <div style="position: absolute; right: 0px; top: 20px;">
                                    <table border="1" style="border-collapse:collapse; background: white; border-color: black; ">
                                    <tr>
                                        <td rowspan="3" style="text-align: center;">
                                        결<br />
                                        <br />제
                                        </td>
                                        <td style="height: 20px; text-align: center;">팀장</td>
                                        <td style="height: 20px; text-align: center;">소장</td>
                                    </tr>
                                    <tr>
                                        <td height="50" style="min-width: 80px; text-align: center;">
                                        ${!!data.ApproverUserStamp1 
                                            ? ('<img src="' + Util.get(data, 'ApproverUserStamp1.Url') + '" class="stamp" />') 
                                            : (data.Confirm1??'')}
                                        </td>
                                        <td style="min-width: 80px; text-align: center;">
                                        ${!!data.ApproverUserStamp2 
                                            ? ('<img src="' + Util.get(data, 'ApproverUserStamp2.Url') + '" class="stamp" />') 
                                            : (data.Confirm2??'')}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="height: 20px; text-align:center; font-size:11px">${data.ApproveDate1??''}</td>
                                        <td style="height: 20px; text-align:center; font-size:11px">${data.ApproveDate2??''}</td>
                                    </tr>
                                    </table>
                                </div>
                                `}
                                ${Util.get(data, 'Content', '')}
                                </div>
                                <script type="text/javascript">
                                document.onreadystatechange = function() {
                                    if(document.readyState === 'complete') {
                                        var contentWidth = document.getElementById('ubitems-fixed-content').clientWidth;
                                        var clientWidth = document.body.clientWidth;
                                        var zoom = (clientWidth / contentWidth) - 0.01;
                                        document.body.style.zoom = zoom;
                                    }
                                }
                                </script>
                                </body>
                                </html>`,
                                }}
                                style={{ marginTop: 0, flex: 1 }}
                            />
                        </View>
                    </TabItem>

                    <TabItem active={tab == 'relative-facility-list' ? true : false} lazy={true} alwaysReload={true}>
                        <FacilityList navigation={navigation} />
                    </TabItem>
                </TabContent>
            </Tab>

            {loading && <Form.Loading />}
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title={`일지관리`} main={false} />,
    };
};

export default Screen;
