import { View, Image } from '@tarojs/components'
import './choose_actions.scss'
import { IconClose } from '@/components/basic/Icons'
import { rpxToPx } from '@/utils/tools'
import NewButton, { NewButtonType } from '@/_health/base/new_button'
import Taro from '@tarojs/taro'
import { BASE_IMG_URL, baseUrl } from '@/services/http/api'
import { useTranslation } from 'react-i18next'
import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'
import { MainColorType } from '@/context/themes/color'
import { useEffect } from 'node_modules/@types/react'

export default function ChooseActions(props: { close: any, quick: any, chooseText: any, chooseImg: any }) {
    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;
    const { t } = useTranslation()

    function camera() {
        addImage(true)
    }

    function album() {
        addImage(false)
    }

    function chat() {
        Taro.chooseMessageFile({
            count: 9,
            type: 'image',
            success: async function (res) {
                const results = await Promise.all(res.tempFiles.map(getImageInfo));
                chooseSuccess(results, true)
            },
            fail(res) {
            },
        })
    }

    function text() {
        props.close()
        props.chooseText()
        // jumpPage(`/_record/pages/log_record?scenario=${props.scenario}&only_text=1`)
    }

    function checkin() {
        props.close()
        props.quick()
        // jumpPage(`/_record/pages/log_record?scenario=${props.scenario}&check_in=1`)
    }

    function addImage(isCamera) {
        var source: any = isCamera ? ['camera'] : ['album']
        console.log(source)
        Taro.chooseMedia({
            count: 9,
            sizeType: ['compressed'],
            mediaType: ['image'],
            sourceType: source,
            success: async function (res) {
                const results = await Promise.all(res.tempFiles.map(getImageInfo));


                chooseSuccess(results, true)
            },
            fail: function (res) {
            }
        })
    }

    async function chooseSuccess(res, isAlbum) {
        console.log('选择图片', res)
        // const filePaths = res.map(file => file.path
        //     // process.env.TARO_ENV === 'rn' || isFilePath ? file.path : file.tempFilePath
        // )
        Taro.showLoading({
            title: t('health.uploading')
        })

        try {
            const uploadedUrls = await Promise.all(res.map(path => uploadFile2(path, isAlbum ? 'album' : 'camera')))
            // setPics([...pics, ...uploadedUrls])
            // jumpPage(`/_record/pages/log_record?imgs=${JSON.stringify(uploadedUrls)}&scenario=${props.scenario}`)
            props.chooseImg(uploadedUrls)
            props.close()
            Taro.hideLoading()
        } catch (error) {
            console.error('Error uploading files:', error)
            Taro.hideLoading()
        }
    }

    function uploadFile2(obj: any, source: string): Promise<string> {
        return new Promise((resolve, reject) => {
            var path = obj.path
            const dot = path.lastIndexOf('.')
            const fileExt = dot > 0 ? path.substring(dot) : ''
            Taro.request({
                method: 'GET',
                url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`,
                header: {
                    'Authorization': 'bearer ' + global.token
                },
                data: {
                    type: 'FOOD_JOURNAL',
                    file_ext: fileExt
                },
                success: (rsp) => {
                    if (rsp.statusCode !== 200) {
                        reject(new Error(t('health.networkError')))
                        return
                    }
                    Taro.uploadFile({
                        url: rsp.data.upload_url,
                        filePath: path,
                        name: 'file',
                        formData: rsp.data.fields,
                        success: () => {
                            var temp = JSON.parse(JSON.stringify(obj))
                            temp.url = rsp.data.view_url
                            // resolve(rsp.data.view_url)
                            resolve(temp)
                        },
                        fail: (error) => {

                            reject(error)
                        }
                    })
                },
                fail: reject
            })
        })
    }

    const getImageInfo = (src) => {
        const { tempFilePath, path } = src
        return new Promise((resolve) => {
            Taro.getImageInfo({
                src: tempFilePath ? tempFilePath : path,
                success: (result) => resolve({
                    height: result.height,
                    width: result.width,
                    orientation: result.orientation,
                    path: result.path,
                    type: result.type
                }),
                fail: (error) => resolve({
                    height: 1024,
                    width: 1024,
                    orientation: 'up',
                    path: tempFilePath,
                    type: 'unknown'
                }),
            });
        });
    };

    return <View className="actions_bg" catchMove onClick={props.close}>

        <View className="navi_bar" style={{
            position: 'fixed',
            left: 0,
            right: 0,
            top: 0, height: navigationBarHeight, zIndex: 1000
        }}>
            <View style={{
                position: 'absolute',
                left: 0,
                right: 0,
                bottom: 0,
                height: 44,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}>
                <View style={{
                    position: 'absolute',
                    width: rpxToPx(92),
                    height: rpxToPx(64),
                    left: 22,
                    top: 22 - rpxToPx(32)
                }}
                    onClick={() => {
                        Taro.navigateBack()
                    }}>
                    <IconClose color="#fff" width={rpxToPx(64)} height={rpxToPx(64)} />
                </View>
            </View>
        </View>
        <NewButton type={NewButtonType.img} onClick={album}>
            <View className='action_btn h30 bold cardShowAni'>{t('health.add_photos')}
                <Image className='action_btn_img' src={BASE_IMG_URL + 'image.svg'} />
            </View>
        </NewButton>
        <NewButton type={NewButtonType.img} onClick={text}>
            <View className='action_btn h30 bold cardShowAni'>{t('health.add_text')}
                <Image className='action_btn_img' src={BASE_IMG_URL + 'text.svg'} />
            </View>
        </NewButton>
        <NewButton type={NewButtonType.img} onClick={camera}>
            <View className='action_btn h30 bold cardShowAni'>{t('health.camera2')}
                <Image className='action_btn_img' src={BASE_IMG_URL + 'camera.svg'} />
            </View>
        </NewButton>

        <NewButton type={NewButtonType.img} onClick={chat}>
            <View className='action_btn h30 bold cardShowAni'>{t('health.import_chat')}
                <Image className='action_btn_img' src={BASE_IMG_URL + 'wechat.svg'} />
            </View>
        </NewButton>
        <View style={{height:rpxToPx(120)}}/>

        {/* <View className='cardShowAni' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', height: rpxToPx(64), marginTop: rpxToPx(26) }}>
            <View className='or_line'/>
            <View className='white h30 bold' style={{marginLeft:rpxToPx(24),marginRight:rpxToPx(24)}}>OR</View>
            <View className='or_line'/>
        </View>


        <NewButton type={NewButtonType.img} onClick={checkin}>
            <View className='action_btn h30 bold cardShowAni'>Quick Check in</View>
        </NewButton> */}


        {/* <View className='btnAni' style={{ marginBottom: rpxToPx(84), marginTop: rpxToPx(60) }} onClick={props.close}>
            <IconClose color="#fff" width={rpxToPx(64)} height={rpxToPx(64)} />
        </View> */}
    </View>
}