import { PPTElementShadow, PPTTextElement } from '@/types/slides';

export const ResolveText = (item: any, index: number,offsetLeft:number,offsetTop:number): PPTTextElement => {

    let domLeft = item.layer.left-offsetLeft
    let domwidth = item.layer.width
    let domTop = item.layer.top-offsetTop
    let domheight = item.layer.height
    const opacity = (parseFloat(item.layer.opacity) / 255.0)

    let f = item.layer.typeTool().export()
    
    const { left, top, width, height, value, font, transform } = f
    const { colors, styles, alignment, sizes, names, weights } = font
    let fontSize = 24.0
    if (sizes && sizes[0]) {
        if (transform.yy !== 1) {
            fontSize = (Math.round((sizes[0] * transform.yy) * 100) * 0.01)
        } else {
            fontSize = sizes[0]
        }
    }
    
    const StyleSheet = item.layer.adjustments.typeTool.obj.engineData.EngineDict.StyleRun.RunArray[0].StyleSheet || {}
    const { StyleSheetData } = StyleSheet
    const tracking = fontSize * (StyleSheetData.Tracking / 1000)
    const lineHeight = StyleSheetData.Leading
    let leading = (Math.round((lineHeight * transform.yy) * 100) * 0.01) / fontSize
    let objectEFFFects = item.layer.objectEffects ? item.layer.objectEffects() : null
    let color = `rgba(${colors[0][0]},${colors[0][1]},${colors[0][2]},${(parseFloat(colors[0][3]) / 255.0).toFixed(2)})`

    let style = `text-align:${alignment[0]}; font-size:${fontSize-2}px; font-weight:${weights[0]};`
    if (font.textDecoration || StyleSheetData.Strikethrough) {
        style += `text-decoration:${font.textDecoration ? font.textDecoration[0] : ''} ${StyleSheetData.Strikethrough ? ' line-through' : ''};`
    }
    if (StyleSheetData.FauxItalic){
        style += `font-style:italic;`
    }

    let content = `<p style="${style}">${value}</p>`
    let textShadow: any = null
    if (objectEFFFects && objectEFFFects.data?.DrSh.enab) {
        textShadow = getShadows(objectEFFFects)
    }
    let background = ''
    if (objectEFFFects && objectEFFFects.data?.GrFl.enab) {
        background += `rgba(${colors[0][0]},${colors[0][1]},${colors[0][2]},${(parseFloat(colors[0][3]) / 255.0).toFixed(2)})`
        background += " "+getGradient(objectEFFFects)
        background += " no-repeat"
        background += " fixed"
        background += " center center"
        // div.style.backgroundPositionX = objectEFFFects.data.GrFl.Ofst.Hrzn.value+"px"
        // div.style.backgroundPositionY = objectEFFFects.data.GrFl.Ofst.Vrtc.value+"px"
        color = 'transparent',
            textShadow = null
    }

    const isVertical = item.layer.adjustments.typeTool.obj.textData.Ornt.value != 'Hrzn'
    if(isVertical) {
        let checkWord = value[0]+value[value.length-1]
        let words = checkWord.match(/[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g)
        if(words&&words.length>0){
            domheight += fontSize*words.length*1.4
            domTop -= fontSize
           
        }else{
            domheight += fontSize*1.4
        }
        domLeft -= 10+((leading-1)*fontSize/2)
    }
    else {
        domwidth +=fontSize+(value[value.length-1]=='】'?fontSize:0)
        domTop -= 10+((leading-1)*fontSize/2)
    }


    let element: PPTTextElement = {
        id: "text_" + index,
        type: 'text',
        left:domLeft,
        width:domwidth,
        top:domTop,
        height:domheight,
        rotate: 0,
        opacity,
        content,
        defaultFontName: names.join(','),
        defaultColor: color,
        fill: background,
        lineHeight: leading,
        wordSpace: tracking,
        vertical: isVertical,
        FiledTypeStr: content
    }
    if (textShadow) element.shadow = textShadow

    return element
}

const getGradient = (obj: any) => {
    const { GrFl } = obj.data
    const angle = GrFl.Angl.value - 90
    let linear = `linear-gradient(${angle}deg `
    let intr = GrFl.Grad.Intr
    GrFl.Grad.Clrs.forEach((x: any, i: number) => {
        const clrStr = JSON.stringify(x['Clr ']).split(',')
        let r: string = '0'
        let g: string = '0'
        let b: string = '0'
        clrStr.forEach(item => {
            if (item.indexOf('Rd') !== -1) {
                r = item.replace('"Rd  ":', '')
            } else if (item.indexOf('Bl') !== -1) {
                b = item.replace('"Bl  ":', '').replace('}', '')
            } else if (item.indexOf('Grn') !== -1) {
                g = item.replace('"Grn ":', '')
            }
        })
        const color =
            linear += `, rgba(${parseInt(r)},${parseInt(g)},${parseInt(b)},${GrFl.Opct.value / 100})`
        //linear-gradient(90deg, #FFF 0%, 18% ,#e5b8a4 36%, 68%, #FFF)
        let cent = "", posi = ""
        if (i < GrFl.Grad.Clrs.length - 1) {
            posi = Math.ceil(x.Lctn * 100 / intr) + "%"
            cent = Math.ceil((x.Lctn + ((GrFl.Grad.Clrs[i + 1].Lctn - x.Lctn) * x.Mdpn / 100)) * 100 / intr) + "%"
            linear += ` ${posi}, ${cent}`
        }
    })
    linear += ")"

    return linear;
}

const getShadows = (drsh: any) => {
    const { DrSh } = drsh.data

    const clrStr = JSON.stringify(DrSh['Clr ']).split(',')
    let r: string = '0'
    let g: string = '0'
    let b: string = '0'
    clrStr.forEach(item => {
        if (item.indexOf('Rd') !== -1) {
            r = item.replace('"Rd  ":', '')
        } else if (item.indexOf('Bl') !== -1) {
            b = item.replace('"Bl  ":', '').replace('}', '')
        } else if (item.indexOf('Grn') !== -1) {
            g = item.replace('"Grn ":', '')
        }
    })
    const angle = DrSh.lagl.value
    const distance = DrSh.Dstn.value
    var angleInRadians = angle * Math.PI / 180;
    const shadowColor = `rgba(${parseInt(r)},${parseInt(g)},${parseInt(b)},${DrSh.Opct.value / 100})`
    const x = Math.round(distance * Math.cos(angleInRadians));
    const y = Math.round(distance * Math.sin(angleInRadians));

    let result: PPTElementShadow = {
        v: x,
        h: y,
        blur: DrSh.blur.value,
        color: shadowColor
    }
    return result;
}