<template>
    <div class="overlay" v-if="visible">
        <div class="content"
            :style="{height: showPreview ? previewDialogHeight + 'px' : dialogHeight +'px' }">
            <div class="head">
                <div class="left">
                    <div class="close-btn" @click="close">
                        <img class="icon-close" v-if="!showPreview" :src="require('../../assets/svg/icon-close.svg')" />
                        <img class="icon-close" v-else :src="require('../../assets/svg/icon-back.svg')" />
                    </div>
                    <div class="title">
                        Giveaways
                    </div>
                </div>
                <img class="icon-question" :src="require('../../assets/svg/icon-question.svg')">
            </div>
            <div class="body">
                <div class="left">
                    <div class="gift-pack-wrapper">
                        <img class="icon" :src="require('../../assets/svg/icon-gift-pack.svg')">
                    </div>
                    <div class="bottom">
                        <img class="icon" :src="require('../../assets/svg/icon-wallet.svg')">
                        <img class="icon" :src="require('../../assets/svg/icon-setting.svg')">
                    </div>
                </div>
                <div class="right">
                    <template v-if="!showPreview">
                        <div id="editor" class=""></div>
                        <div class="form-wrapper">
                            <div class="form-base">
                                <div class="item">
                                    <div class="label">
                                        <img class="icon"
                                            :src="require('../../assets/svg/icon-usd.svg')" />
                                        USD
                                    </div>
                                    <el-input
                                        v-model="baseFormData.amountValue"
                                        placeholder="$0.00"
                                        oninput = "value=value.replace(/[^\d]/g,'')"
                                        :input-style="{ 'box-shadow': 'none' }"/>
                                </div>
                                <div class="item">
                                    <div class="label">
                                        <img class="icon"
                                            :src="require('../../assets/svg/icon-quantity.svg')" />
                                        Quantity
                                        </div>
                                    <el-input
                                        v-model="baseFormData.totalCount"
                                        placeholder="Enter quantity"
                                        oninput = "value=value.replace(/[^\d]/g,'')"
                                        :input-style="{ 'box-shadow': 'none' }"/>
                                </div>
                            </div>
                            <div class="form-require">
                                <div class="bar">
                                    <div class="label">
                                        <img class="icon"
                                            :src="require('../../assets/svg/icon-require.svg')" />
                                        Require
                                    </div>
                                </div>
                                <div
                                    class="form-item"
                                    v-for="(item, index) in formList"
                                    :key="index">
                                    <div class="label">
                                        <img class="icon"
                                            :src="item.icon" />
                                        {{ item.label }}
                                    </div>
                                    <div class="control">
                                        <el-input
                                            :type="item.nodeType"
                                            rows="2"
                                            resize="none"
                                            v-model="item.text"
                                            v-if="item.nodeType == 'textarea'"
                                            placeholder="Enter account number"
                                            :input-style="{
                                                'box-shadow': 'none',
                                                'padding': '1px',
                                                'line-height': '1'
                                            }"/>
                                    </div>
                                    <el-switch v-model="item.checked" />
                                </div>
                            </div>
                            <div class="submit-btn" @click="confirm">NEXT</div>
                        </div>
                    </template>
                    <template v-if="showPreview">
                        <preview-card :postData="publishRes"></preview-card>
                    </template>
                    <div v-show="showPreview">
                        <paypal-button :amount="baseFormData.amountValue" @payPalFinsh="payPalFinsh"></paypal-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, reactive, defineProps, defineEmits, onMounted } from "vue";
import {postPublish, verifyPaypalResult} from "../../http/publishApi"
// import Quill from 'quill';
// import 'quill/dist/quill.snow.css'

// const quillOptions = {
//     placeholder: 'Compose an epic...',
// };

import previewCard from "./preview-card";
import paypalButton from "./paypal-button";

const paypalClientId = 'ASn7k0zqyS5AWYikVSfmamR-RFpjyU_QFJWSxOHHoWE04-RgHNO6nahn0GyHUaUAEBxj-aKgtSrq4O4G';

let publishRes = reactive({})

let visible = ref(false);
let showPreview = ref(false);
let dialogHeight = ref(620);
let previewDialogHeight = ref(880)

let baseFormData = reactive({
    amountCurrencyCode: "USD",
    amountValue: "",
    totalCount: "",
});

let formList = reactive([
    {
        label: "Follow",
        icon: require('../../assets/svg/icon-follow.svg'),
        nodeType: 'textarea',
        type: 1,
        text: '',
        checked: true
    },
    {
        label: "Like",
        icon: require('../../assets/svg/icon-like.svg'),
        nodeType: 'div',
        type: 2,
        checked: true
    },
    {
        label: "Retweet",
        icon: require('../../assets/svg/icon-retweet.svg'),
        nodeType: 'div',
        type: 3,
        checked: true
    },
]);

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false,
    },
});

watch(
    () => props.dialogVisible,
    (newVal) => {
        console.log("watch", newVal);
        visible.value = newVal;
        if(newVal) {
            // initQuill();
        }
    }
);

const emits = defineEmits(["close", "confirm", "payPalFinsh"]);

const close = () => {
    if (showPreview.value) {
        showPreview.value = false;
    } else {
        initParams();
        emits("close", false);
    }
};

const setPreviewDialogHeight = () => {
    let clientHeight = document.documentElement.clientHeight;
    let gapSafe = 80;

    if(previewDialogHeight.value > clientHeight - gapSafe) {
        previewDialogHeight.value = clientHeight - gapSafe;
    }
};

const confirm = () => {
    let {amountValue = 0, totalCount = 0, amountCurrencyCode} = baseFormData;
    if(!amountValue || !totalCount) {
        return;
    }
    amountValue = amountValue * 100; // 元转分

    let finishConditions = [];
    for(let i = 0; i < formList.length; i++) {
        let item = {};
        item.type = formList[i]['type'];
        if(item.type == 1 && formList[i]['checked'] && formList[i]['text']) { // follow 参数
            let relatedUsers = [];
            let text = formList[i]['text'].replace(/\s*/g,""); // 删除空格
            let textList = text.split('@');

            for(let i = 0; i < textList.length; i++) {
                let item =  textList[i];
                if(item) {
                    relatedUsers.push({name: item});
                }
            }
            item.relatedUsers = relatedUsers;
            finishConditions.push(item);
        } else if(formList[i]['checked']){
            finishConditions.push(item);
        }
    }
    console.log('finishConditions', finishConditions);
    let formData = {
        amountCurrencyCode,
        amountValue,
        totalCount,
        finishConditions
    }
    let data = {
        params: {
            postBizData: JSON.stringify(formData),
            postSrc: 1,  //1 twitter
            postType: 1, //1 红包
        }
    }
    postPublish(data).then((res) => {
        if(res.code == 0) {
            publishRes = res.data;
            setPreviewDialogHeight();
            showPreview.value = true;
        }
    })
};

const initParams = () => {
    baseFormData.amountValue = '';
    baseFormData.totalCount = '';
    formList[0].text = '';
}

const payPalFinsh = (params) => {
    let transaction = params.transaction;
    console.log('transaction', transaction)
    verifyPaypalResult({
        params: {
            paypalTransactionId: transaction.id,
            postId: publishRes.postId,
            paypalClientId: paypalClientId
        }
    }).then((res) => {
        if(res.code == 0) {
            //支付状态 0：未支付，1：支付成功，2：支付失败，3：已关闭，4：已退款
            if(res.data && res.data.payStatus == 1) {
                emits("payPalFinsh", {publishRes});
                showPreview.value = false;
                initParams();
            }
        }
    })
}


// const initQuill = () => {
//     let container = document.getElementById('editor');
//     let editor  = new Quill(container, quillOptions);

//     editor.on('text-change', () => {
//         if(editor.getText()) {
//             /**
//              * quill.insertText(5, 'Quill', {
//                 'color': '#ffff00',
//                 'italic': true
//                 });
//              */
//             // editor.setContents([
//             //     { insert: 'World!', attributes: { color: 'blue' } },
//             // ]);
//         }
//         console.log(editor.getText())
//     });
// }

onMounted(() => {
    setPreviewDialogHeight();
    // initQuill();
})

</script>

<style lang="scss" scoped>
.ql-container {
    height: 100px;
}
.overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 2000;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    overflow: auto;

    .content {
        width: 650px;
        height: 620px;
        background: #ffffff;
        border-radius: 16px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        box-sizing: border-box;

        .head {
            border-bottom: 1px solid #ececec;
            height: 48px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 14px;

            .left {
                display: flex;

                .close-btn {
                    display: flex;
                    align-items: center;
                    width: max-content;
                    margin-right: 12px;
                    cursor: pointer;
                }
            }

            .icon-question {
                cursor: pointer;
            }
        }

        .body {
            box-sizing: border-box;
            height: calc(100% - 48px);
            display: flex;

            .left,
            .right {
                height: 100%;
            }

            .left {
                width: 50px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                align-items: center;

                .gift-pack-wrapper {
                    width: 100%;
                    height: 54px;
                    background: #F5F5F5;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }

                .bottom {
                    .icon {
                        display: block;
                        margin-bottom: 26px;
                    }
                }
            }

            .right {
                width: calc(100% - 50px);
                box-sizing: border-box;
                position: relative;
                border-left: 1px solid #ececec;

                .form-wrapper {
                    padding: 26px 18px;
                    box-sizing: border-box;

                    .form-base {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .item {
                            width: 250px;
                            height: 60px;
                            border: 1px solid #e1e1e1;
                            box-sizing: border-box;
                            border-radius: 15px;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            padding: 16px 14px;

                            .label {
                                font-weight: 500;
                                font-size: 15px;
                                display: flex;
                                align-items: center;

                                .icon {
                                    width: 20px;
                                    height: 20px;
                                    margin-right: 8px;
                                }
                            }
                        }
                    }

                    .form-require {
                        border: 1px solid #e1e1e1;
                        box-sizing: border-box;
                        border-radius: 15px;
                        margin-top: 12px;

                        .bar {
                            padding: 2px 10px 0 10px;
                            box-sizing: border-box;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            line-height: 50px;

                            .label {
                                display: flex;
                                .icon {
                                    margin-right: 8px;
                                }
                            }

                            .icon-button {
                                width: 28px;
                                height: 28px;
                                cursor: pointer;
                            }
                        }

                        .form-item {
                            height: 50px;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            margin: 0 16px;
                            border-bottom: 1px solid #ececec;

                            .label {
                                width: 100px;
                                color: rgba(0, 0, 0, 0.6);
                                display: flex;
                                align-items: center;
                                .icon {
                                    margin-right: 10px;
                                }
                            }

                            .control {
                                width: 264px;
                                height: 50px;
                                line-height: 50px;
                                cursor: pointer;

                                .inner {
                                    width: 100%;
                                    height: 100%;
                                    box-sizing: border-box;
                                    display: flex;
                                    align-items: center;
                                }
                            }

                            .icon-remove-button {
                                cursor: pointer;
                            }
                        }
                    }
                }

                .submit-btn {
                    width: calc(100% - 36px);
                    height: 60px;
                    text-align: center;
                    line-height: 60px;
                    background: #4a99e9;
                    border-radius: 15px;
                    color: #fff;
                    position: absolute;
                    bottom: 32px;
                    left: 18px;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>
