/**
 *  自定义控件书写模板
 */
(function (KDApi, $) {
    // 构造函数，变量名随意，与最后一句代码的KDApi.register的第二个参数一致即可
    function PopularCityRank(model) {
        this._setModel(model)
    }

    // 原型中封装生命周期函数，固定格式
    var isUpdate = false;
    PopularCityRank.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 jsPath = ["./css/tripboard.css"];
        KDApi.loadFile(jsPath, model, function () {
            if (isUpdate && props.data && props.data.others.length > 0) {
                KDApi.templateFilePath('./html/container_popularcityrank.html', model, {}).then(
                    function (result) {
                        model.dom.innerHTML = result;
                        loadData(model, props);
                    }
                )
            } else {
                KDApi.templateFilePath('./html/container_popularcityrank.html', model, {}).then(
                    function (result) {
                        model.dom.innerHTML = result;
                        var chartSelector = `[data-pid="${model.pageId}"] #popularcityrank-table-container, [pageid="${model.pageId}"] #popularcityrank-table-container`;
                        var emptySelector = `[data-pid="${model.pageId}"] .kd-cq-empty-popularcityrank,[pageid="${model.pageId}"] .kd-cq-empty-popularcityrank`;
                        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, 'PopularCity_No_Data');
                        emptyDom.appendChild(noDataDom);
                        emptyDom.setAttribute("style", "display:block;text-align:center;mix-blend-mode:multiply;");
                        chartDom.setAttribute("style", "display:none");
                    }
                )

            }
        })


    }

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

    function createTable(others, model) {
        // 选择器
        var chartSelector = `[data-pid="${model.pageId}"] #popularcityrank-table-container, [pageid="${model.pageId}"] #popularcityrank-table-container`;
        var emptySelector = `[data-pid="${model.pageId}"] .kd-cq-empty-popularcityrank, [pageid="${model.pageId}"] .kd-cq-empty-popularcityrank`;

        // 获取内容区域和空状态 DOM
        var content = document.querySelector(chartSelector);
        var emptyDom = document.querySelector(emptySelector);

        // 隐藏空状态，显示表格
        emptyDom.setAttribute("style", "display:none");
        content.setAttribute("style", "display:block;");

        // 获取表格 DOM
        var tableSelector = `[data-pid="${model.pageId}"] #popularcityrank_innertable, [pageid="${model.pageId}"] #popularcityrank_innertable`;
        var table = document.querySelector(tableSelector);

        // 判断金额是否大于等于 100000
        var amountarr = [];
        others.map(item => amountarr.push(item.totalAmount));
        var amountUnit = amountarr.every(amount => amount >= 100000);

        // 拼接表格内容
        table.innerHTML = `
        <thead>
            <tr>
                <th>${KDApi.getLangMsg(model, 'PopularCity_rank')}</th>
                <th>${KDApi.getLangMsg(model, 'PopularCity_cityname')}</th>
                <th>${KDApi.getLangMsg(model, 'PopularCity_ordernums')}</th>
                <th>${KDApi.getLangMsg(model, 'PopularCity_rate')}</th>
                <th>${amountUnit
            ? KDApi.getLangMsg(model, 'PopularCity_amount_wanyuan')
            : KDApi.getLangMsg(model, 'PopularCity_amount')
        }</th>
            </tr>
        </thead>
        <tbody>
            ${others.map(item => `
                <tr>
                    <td title="${item.rank}">${item.rank}</td>
                    <td title="${item.cityName}">${item.cityName}</td>
                    <td title="${item.orders}">${item.orders}</td>
                    <td title="${item.percentage}">${item.percentage}</td>
                    <td title="${amountUnit
            ? formatNumber(item.totalAmount)
            : item.totalAmount
        }">${amountUnit
            ? formatNumber(item.totalAmount)
            : item.totalAmount
        }</td>
                </tr>
            `).join('')}
        </tbody>
    `;

        return content;
    }


    var loadData = function (model, props) {
        var contentSelector = `[data-pid="${model.pageId}"] #popularcityrank_content, [pageid="${model.pageId}"] #popularcityrank_content`;
        var content = document.querySelector(contentSelector);

        const parentNode = content.parentNode;
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        console.log("浏览器宽度:" + parentNode.clientHeight * 0.3 * 0.95);
        content.style.width = w * 0.3 + "px";
        content.style.height = h * 0.3 + "px";

        const table = createTable(props.data.others, model);


        content.appendChild(table);

    }

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