import { createElement, setTooltip, createIcon, requestAnimationFrame } from "../../ui";
import { r as lang, nullOrEmpty, escapeHtml, escapeEmoji } from "../../utility";
import { createBox, appendMedia, createHideMessageTitleButton, createHideMessageCommentTail } from "./lib";

let r = lang;

export default class CustomerRecordComment {
    _var = {};

    constructor(opt) {
        this._var.option = opt ?? {};
        const getText = opt?.getText;
        if (typeof getText === 'function') {
            r = getText;
        } else if (typeof GetTextByKey === 'function') {
            r = GetTextByKey;
        }
    }

    get text() { return this._var.enter?.value }
    set text(s) {
        const element = this._var.enter;
        if (element != null) {
            element.value = s
            s = String(nullOrEmpty(s) ? 0 : val.length) + '/' + String(this._var.option.maxLength);
            this._var.container.querySelector('.message-bar .prompt-count').innerText = s;
        }
    }

    /**
     * @param {boolean} flag
     */
    set messageHidden(flag) {
        const el = this._var.container.querySelector('.msgadminsetting');
        if (el == null) {
            return;
        }
        this._var.option.showCommentHidden = flag;
        // TODO: 是否与参数 flag 无关
        el.classList.remove('iconview');
        el.classList.add('iconnotview');
    }

    /**
     * @param {boolean} flag
     */
    set loading(flag) {
        if (this._var.container == null) {
            return;
        }
        this._var.enter.disabled = flag;
        this._var.container.querySelector('.button-send-message').disabled = flag;
    }
    get replyMsgId() { return this._var.replymsgid || -1 }
    set replyMsgId(v) {
        this._var.replymsgid = null;
        this._var.replymsgctrl.style.display = 'none'
    }

    /**
     * @param {boolean} flag
     */
    set readonly(flag) {
        this._var.option.readonly = flag;
        if (this._var.container == null) {
            return;
        }
        this._var.enter.disabled = flag === true;
        this._var.container.querySelector('.button-send-message').style.display = flag === true ? 'none' : '';
        this._var.container.querySelector('.message-bar .prompt-count').style.display = flag === true ? 'none' : '';
    }

    create() {
        const readonly = this._var.option.readonly;
        const container = createBox(
            createElement('div', null,
                createElement('div', div => {
                    div.className = 'title-module';
                    div.innerText = r('FLTL_00584', 'Comments');
                },
                    createHideMessageTitleButton(this, 'showCommentHidden')
                )
            ),
            [
                createElement('button', button => {
                    button.className = 'roundbtn button-close';
                    button.style.backgroundColor = 'transparent';
                    if (this._var.option.hasClose !== true) {
                        button.style.display = 'none';
                        return;
                    }
                    button.appendChild(createIcon('fa-solid', 'times', {
                        fill: '#000'
                    }));
                    button.addEventListener('click', () => {
                        if (typeof this._var.option.onClose === 'function') {
                            this._var.option.onClose();
                        }
                    })
                })
            ]
        );
        // enter box
        const enter = createElement('textarea', 'ui-text');
        enter.placeholder = r('FLTL_01154', 'Enter Comment Here');
        enter.maxLength = this._var.option.maxLength ??= 3000;
        enter.addEventListener('input', () => {
            const val = this.text;
            const s = String(nullOrEmpty(val) ? 0 : val.length) + '/' + String(this._var.option.maxLength);
            this._var.container.querySelector('.message-bar .prompt-count').innerText = s;
        });
        if (readonly === true) {
            enter.disabled = true;
        }
        this._var.enter = enter;
        container.appendChild(
            createElement('div', 'message-bar',
                enter,
                createElement('div', div => {
                    div.className = 'customer-reply';
                    div.style.display = 'none';
                    this._var.replymsgctrl = div;
                },
                    createElement('span', span => {
                        span.className = 'reply-user';
                    }),
                    createElement('span', span => {
                        span.className = 'reply-msg';
                    }),
                    createElement('layer', layer => {
                        layer.appendChild(createIcon('fa-light', 'times'));
                        layer.addEventListener('click', () => {
                            this.replyMsgId = null;
                        });
                    })
                ),
                createElement('div', div => div.style.textAlign = 'right',
                    createElement('div', 'prompt-count'),
                    createElement('button', button => {
                        button.className = 'roundbtn button-send-message';
                        button.style.backgroundColor = 'rgb(19, 150, 204)';
                        if (readonly === true) {
                            button.style.display = 'none';
                        }
                        button.appendChild(createIcon('fa-solid', 'paper-plane'));
                        // setTooltip(button, r('FLTL_02692', 'Send Message'));
                        setTooltip(button, r('FLTL_02301', 'Post Note'));
                        button.addEventListener('click', () => {
                            if (typeof this._var.option.onAddComment === 'function') {
                                this._var.option.onAddComment(this.text, this._var.replymsgid);
                                this.replyMsgId = null;
                            }
                        })
                    })
                )
            )
        );

        const message = createElement('div', 'list-bar');
        this._var.message = message;
        container.appendChild(message);
        return this._var.container = container;
    }

    load(data, func, hisFunc, keep) {
        const children = [];
        if (data?.length > 0) {
            const lastVisible = this._var.option.showCommentHidden;
            for (let comment of data) {
                const div = createElement('div', 'item-div');
                if (comment.Hidden) {
                    div.classList.add('hidden-content');
                    if (!lastVisible) {
                        div.style.display = 'none';
                    }
                }
                // if (sendto !== '') {
                //     sendto = r('FLTL_02716', 'Sent To :') + `\n${sendto}`;
                // }
                div.appendChild(createElement('div', div => {
                    div.className = 'item-poster';
                    div.innerText = comment.UserName;
                }));
                const content = createElement('div', 'item-content');
                if (comment.ReplyMessage) {
                    const reply = createElement('div', div => {
                        div.className = 'reply';
                        div.innerHTML = comment.ReplyMessage.Comment;
                    });
                    content.appendChild(reply);
                }
                const mmsParts = createElement('div', div => div.style.display = 'none');
                content.appendChild(createElement('span', span => span.innerHTML = escapeHtml(escapeEmoji(comment.Comment)), mmsParts));
                if (comment.MMSParts?.length > 0) {
                    mmsParts.style.display = '';
                    for (let kv of comment.MMSParts) {
                        appendMedia(mmsParts, kv.Key, kv.Value);
                    }
                }
                div.append(
                    content,
                    createHideMessageCommentTail(
                        this, 'showCommentHidden',
                        comment, 'SubmitLocalDateStr',
                        func, hisFunc)
                );
                children.push(div);
            }
            children[0].style.marginTop = '0';
        }
        if (this._var.message.children.length > 0) {
            this._var.lastTop = this._var.message.scrollTop;
        }
        this._var.message.replaceChildren(...children);
        requestAnimationFrame(() => this._var.message.scrollTop = keep ? this._var.lastTop : this._var.message.scrollHeight);
    }
}