/**
 *  自定义控件书写模板
 */

(function (KDApi, $) {
    // 构造函数，变量名随意，与最后一句代码的KDApi.register的第二个参数一致即可
    function NotReimburseOrderMob(model) {
        this._setModel(model)
    }

    // 原型中封装生命周期函数，固定格式
    var isUpdate = false;
    NotReimburseOrderMob.prototype = {
        _setModel: function (model) {


            this.model = model
        },
        init: function (props) {
            isUpdate = false;
            setHtml(this.model, props, isUpdate)
        },
        update: function (props) {
            isUpdate = true;
            setHtml(this.model, props, isUpdate)
        },
        destoryed: function () {
        }
    }

    var setHtml = function (model, props, isUpdate) {
        // 获取自定义控制属性 根据属性获取对应的自定义控件
        var config = props.configItems;
        var parentId;
        if (config) {
            parentId = config[0].value;
        }
        if (!isUpdate) {
            KDApi.templateFilePath('./html/not_reimburseorder_mob.html', model, {}).then(
                function (result) {
                    model.dom.innerHTML = result;
                    var data = props.data;
                    if (!data) {
                        var chartSelector = `#${parentId} .carousel`;
                        var emptySelector = `#${parentId} .kd-cq-empty-notreimburseorder-mob`;
                        var chartDom = document.querySelector(chartSelector);
                        var emptyDom = document.querySelector(emptySelector);
                        var noDataDom = document.createElement("span");
                        noDataDom.className='kd-cq-empty-description';
                        noDataDom.setAttribute("style","margin-top:8px;color:#666");
                        noDataDom.textContent=KDApi.getLangMsg(model, 'NotReimbursedOrder_No_Data');
                        emptyDom.appendChild(noDataDom);
                        emptyDom.setAttribute("style", "display:block;text-align:center");
                        chartDom.setAttribute("style", "display:none");
                        return;
                    }
                }
            )

        }

        if (isUpdate && props.data && Object.keys(props.data).length > 0 && props.data.data && props.data.data.length > 0) {

            KDApi.loadFile("./css/not_reimburseorder_mob.css", model, function () {
                KDApi.templateFilePath('./html/not_reimburseorder_mob.html', model, {}).then(
                    function (result) {
                        model.dom.innerHTML = result;
                        loadData(model, props);
                    }
                )


            })
        } else {
            var chartSelector = `#${parentId} .carousel`;
            var emptySelector = `#${parentId} .kd-cq-empty-notreimburseorder-mob`;
            var chartDom = document.querySelector(chartSelector);
            var emptyDom = document.querySelector(emptySelector);
            emptyDom.setAttribute("style", "display:block;text-align:center");
            chartDom.setAttribute("style", "display:none");
        }
        ;
    }

    function formatNumber(num) {
        if (num == null) {
            return num;
        }
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    var loadData = function (model, props) {
        // 获取自定义控制属性 根据属性获取对应的自定义控件
        var config = props.configItems;
        var parentId;
        if (config) {
            parentId = config[0].value;
        }
        var chartSelector = `#${parentId} .carousel`;
        var emptySelector = `#${parentId} .kd-cq-empty-notreimburseorder-mob`;
        var content = document.querySelector(chartSelector);
        var emptyDom = document.querySelector(emptySelector);
        // 隐藏空状态，显示表格
        emptyDom.setAttribute("style", "display:none");
        content.setAttribute("style", "display:block;");

        // 获取容器
        const carouselInner = document.querySelector(`#${parentId} .carousel #carousel-inner`);

        // 初始化订单行
        generateOrderRows(props.data.data, parentId, model);

        let scrollInterval;
        // 添加首尾无缝衔接逻辑
        let index = 0;

        function startCarousel() {
            const rowHeight = document.querySelector(".order-row").offsetHeight; // 获取真实行高
            var orders = props.data.data;
            const totalRows = carouselInner.children.length * 2; // 总行数
            const containerHeight = document.querySelector(".carousel").clientHeight; // 容器高度
            const visibleRows = Math.floor(containerHeight / rowHeight); // 可见的行数


            // 自动轮播
            scrollInterval = setInterval(() => {
                index++;
                carouselInner.style.transition = "transform 2s linear";
                carouselInner.style.transform = `translateY(-${index}px)`;
                // 如果已经滚动到一定位置，则动态追加新内容
                if (index >= totalRows * rowHeight / 2) {
                    // 动态追加新内容
                    generateOrderRows(props.data.data, parentId, model);
                }
            }, 50);
        }

        content.addEventListener("touchstart", () => {
            clearInterval(scrollInterval);
        });
        content.addEventListener("touchend", () => {
            checkAndStartCarousel();
        });

        // 检测是否需要轮播
        function checkAndStartCarousel() {
            var carousel = document.querySelector(`#${parentId} .carousel`);
            const carouselInner = document.querySelector(`#${parentId} .carousel #carousel-inner`);
            const containerHeight = carousel.offsetHeight;
            const contentHeight = carouselInner.scrollHeight;

            if (contentHeight > containerHeight) {
                generateOrderRows(props.data.data, parentId, model);
                startCarousel(containerHeight, contentHeight);
            }
        }

        checkAndStartCarousel();

    };

    // 动态生成订单行
    function generateOrderRows(orders, parentId, model) {
        var userTab = false;
        if ("userboards" === parentId) {
            userTab = true;
        }
        // 获取容器
        const carouselInner = document.querySelector(`#${parentId} .carousel #carousel-inner`);
        //carouselInner.innerHTML = ""; // 清空内容
        orders.forEach(order => {
            const orderRow = document.createElement("div");
            orderRow.className = "order-row";
            if (userTab) {
                orderRow.innerHTML = `
                    <div>
                        <span class="order-type" title=${order.type}>${order.type}</span>
                        <span class="order-id" title=${order.orderNum}>${order.orderNum}</span>
                        <span class="price" title=${order.amount}>${order.amount}</span>
                    </div>
                    <div class="dates">
                        ${KDApi.getLangMsg(model, 'NotReimbursedOrder_bookDate')}：${order.orderDate} &nbsp;&nbsp;&nbsp;   ${KDApi.getLangMsg(model, 'NotReimbursedOrder_useDate')}：${order.useDate}
                    </div>
                `;
            } else {
                orderRow.innerHTML = `
                    <div>
                        <span class="order-type">${order.type}</span>
                        <span class="order-id">${order.orderNum}</span>
                        <span class="order-user">${order.userInfo}</span>
                        <span class="price">${order.amount}</span>
                    </div>
                    <div class="dates">
                          ${KDApi.getLangMsg(model, 'NotReimbursedOrder_bookDate')}：${order.orderDate} &nbsp;&nbsp;&nbsp;   ${KDApi.getLangMsg(model, 'NotReimbursedOrder_useDate')}：${order.useDate}
                    </div>
                `;
            }

            carouselInner.appendChild(orderRow);
        });
    }


    // 你只需知道第一个参数是你接下来要新增控件方案时填的方案id，第二个参数是上面声明的构造函数
    KDApi.register('kingdee-fi-notreimbursed-order-mob', NotReimburseOrderMob,{isMulLang: true})
})(window.KDApi) // 这里的jQuery不是必须要传进去的，可移除，要用到的时候才传，PC端系统默认会有jQuery对象，版本是1.12.4