(function (root, factory) {
    if (typeof exports !== 'undefined' && typeof module !== 'undefined' && module.exports) {
        // NodeJS
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else {
        // Browser globals
        root.propsJs = factory();
    }
}(this, function () {
    "use strict";

    const exportFunc = {
        // 公共导出函数
        initTag: async function (dstClass) {
            await privateFunc.paddingPropConf()

            $.each($(`.${dstClass}`), (k, v) => {
                const html = privateFunc.BuildRewardsTag(privateFunc.formatNodeData($(v)))

                $(v).html(html)
                privateFunc.appendInputHtml($(v))
            })
        },

        initEdit: async function (event, resClass, type) {
            // 构建弹窗
            privateFunc.buildModalHtml(event)

            $('#prizeModal').modal();
            const $node = $(event).parents('tr').slice(0, 1).find(`.${resClass}`)

            await privateFunc.paddingPropConf(type)

            privateFunc.container = $node
            privateFunc.PropsData = $.userPlugin.ParseIntData(privateFunc.formatNodeData($node));
            console.log(JSON.stringify(privateFunc.PropsData))

            privateFunc.initTableHtml()
        },

        // 私有导出函数
        _updatePrize: () => {
            const dataObject = privateFunc.formatObject();
            console.log("updatePrize ", JSON.stringify(dataObject))

            // 奖励合法性校验
            if (!privateFunc.verifyReward(dataObject)) {
                return;
            }

            const $node = privateFunc.container
            $node.empty()
            $node.data("value", dataObject)

            $node.html(privateFunc.BuildRewardsTag(dataObject))
            privateFunc.appendInputHtml($node)

            $('#prizeModal').modal('hide');
        },

        _delPropHtml: function (event) {
            $(event).parents('tr')[0].remove()
        },

        _addPropHtml: function () {
            const $node = $('#propsConfForm')

            const propsHtml = privateFunc.addOnePropTrHtml({"propsId": 14, "num": 1, "rtype": 1, "skin": 0})

            $node.find('table tbody').append(propsHtml)
            $('.selectpicker').selectpicker({});
        },

        _changeTrPropId: (event, rCnt) => {
            const propsId = parseInt(event.value)
            console.log("变更道具选择:", propsId);

            const prop = {propsId, "skin": 0}

            // 固定选项变更
            const $rtypeNode = $(event).parents(`tr.prize_${rCnt}`).find(`.propsRtype`)
            $rtypeNode.empty()
            $rtypeNode.append(privateFunc.getRtypeOptionHtml(prop));

            // 奖励值变更
            $(`input[name="props[${rCnt}][num]"]`).val(1)

            // 皮肤选项变更
            const $skinNode = $(event).parents(`tr.prize_${rCnt}`).find(`#selectSkinTd_${rCnt}`)

            $skinNode.empty()
            $skinNode.append(privateFunc.buildSkinSelectHtml(prop, rCnt));
            $('.selectpicker').selectpicker({});
        },
    }

    const privateFunc = {
        PropsConf: [], ActIdList: [], NumIsOneList: [], RewardNumLimit: [], PropsData: [], FixedIds: [], type: "", container: {}, rewardCnt: 0,

        paddingPropConf: async (type) => {
            privateFunc.FixedIds = isArray(type) ? type : []
            type = type === undefined || isArray(type) ? 'act' : type
            if (privateFunc.type !== type || privateFunc.PropsConf.length === 0) {
                await $.get('/config/getPropsCommonConfig/' + type).then((response) => {
                    privateFunc.type = type
                    if (typeof response == 'string') response = JSON.parse(response);
                    privateFunc.PropsConf = response.data.propsList;
                    privateFunc.ActIdList = response.data.actIdList;
                    privateFunc.NumIsOneList = response.data.numIsOneList;
                    privateFunc.RewardNumLimit = response.data.rewardNumLimit;
                }).catch((error) => {
                    alert('init props component failed:' + error.statusText)
                })
            }
        },

        buildModalHtml: (event) => {
            if ($(event).parents('body').find('#prizeModal').length !== 0) {
                return
            }

            /*奖励配置弹窗*/
            const html = `
         <div class="modal fade" id="prizeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog" style="top: 20%;width: 80%;">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">奖励配置</h4>
                    </div>
                    <div class="modal-body" style="text-align: center;">
                        <form id="propsConfForm">
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="propsJs._updatePrize()">确认</button>
                    </div>
                </div>
            </div>
        </div>
    `
            $(event).parents('body:last').append(html)
        },

        initTableHtml: () => {
            const $node = $('#propsConfForm')
            $node.empty()

            let propsHtml = ""
            let rewardCnt = 0;

            !isEmpty(privateFunc.PropsData) && privateFunc.PropsData.forEach(v => {
                propsHtml += privateFunc.buildOnePropTrHtml(v, rewardCnt);
                rewardCnt++;
            })

            let html = `
                <table class="table table-bordered props_table">
                    <thead><tr><th>奖励类型</th><th>是否固定</th><th>奖励值</th><th>皮肤</th><th width="120">操作</th></tr></thead>
                    <tbody class="props_body">
                        ${propsHtml}
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5">
                                <div class="text-center">
                                    <botton class="btn btn-primary" onclick="propsJs._addPropHtml(this)">添加</botton>
                                </div>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            `;
            $node.append(html)
            $('.selectpicker').selectpicker({});
        },

        appendInputHtml: (node) => {
            const name = node.data("name")
            if (isEmpty(name)) {
                return
            }

            const value = JSON.stringify(privateFunc.formatNodeData(node))
            const html = `<input type="hidden" name="${name}" value='${value}'>`;

            node.append(html)
        },

        addOnePropTrHtml: (prop) => {
            const lvIdx = $('#propsConfForm').find('.props_body tr:last').data('idx')
            const rCnt = lvIdx === undefined ? 0 : parseInt(lvIdx) + 1;

            return privateFunc.buildOnePropTrHtml(prop, rCnt)
        },

        buildOnePropTrHtml: (prop, rCnt) => {
            console.log("rCnt:", rCnt, "prop:", JSON.stringify(prop));

            const propNum = !isNaN(prop.num) ? prop.num : 1;

            const propsSelectHtml = privateFunc.buildPropsSelectHtml(prop, rCnt)
            const skinSelectHtml = privateFunc.buildSkinSelectHtml(prop, rCnt)
            const rtypeOptionHtml = privateFunc.getRtypeOptionHtml(prop)

            return `
                <tr class="prize_${rCnt}" data-idx="${rCnt}">
                    <td>
                        ${propsSelectHtml}
                    </td>
                    <td>
                       <select class="form-control propsRtype" name="props[${rCnt}][rtype]">
                           ${rtypeOptionHtml}
                       </select>
                    </td>
                    <td>
                        <input type="number" class="form-control"  name="props[${rCnt}][num]" value="${propNum}">
                    </td>
                    <td id="selectSkinTd_${rCnt}">
                        ${skinSelectHtml}
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger deleteParent" onclick="propsJs.  _delPropHtml(this)">删除</button>
                    </td>
                </tr>
            `;
        },

        buildPropsSelectHtml: (prop, rCnt) => {
            const optionHtml = (function (prop) {
                let optionHtml = '';
                for (const v of privateFunc.PropsConf) {
                    if (!isEmpty(privateFunc.FixedIds) && !privateFunc.FixedIds.includes(v.id)) continue;

                    const sel = (prop.propsId === v.id) ? 'selected' : '';
                    optionHtml += `<option value="${v.id}" ${sel}> ${v.name} </option>`;
                }
                return optionHtml;
            })(prop)

            return `
                <select class="form-control selectpicker" name="props[${rCnt}][propsId]" data-live-search="true" onchange="propsJs._changeTrPropId(this,${rCnt})">
                    ${optionHtml}
                </select>
            `
        },

        buildSkinSelectHtml: (prop, rCnt) => {
            const optionHtml = (function (prop) {
                let skinList = [];
                for (const v of privateFunc.PropsConf) {
                    if (prop.propsId === v.id) {
                        skinList = v.skinList;
                        break;
                    }
                }

                if (skinList.length === 0) {
                    return '<option value="0" selected>暂无皮肤可选</option>'
                }

                let optionHtml = ""
                for (const v of skinList) {
                    const sel = prop.skin === v.id ? 'selected' : '';
                    optionHtml += `<option value="${v.id}" ${sel}>${v.name}</option>`;
                }

                return optionHtml;
            })(prop)

            return `
                <select class="form-control selectpicker" name="props[${rCnt}][skin]" data-live-search="true">
                    ${optionHtml}
                </select>`
        },

        getRtypeOptionHtml: (prop) => {
            let rtypeSel = (prop.rtype === 2) ? "selected" : "";

            let optionHtml = `<option value="1">固定值</option>`
            switch (prop.propsId) {
                case 14:
                    optionHtml += `<option value="2" ${rtypeSel}>等级取值</option>`
                    break;
                case 13:// 随机金卡
                case 48:// 随机黑金卡
                case 49:// 随机限时金卡
                case 50:// 随机限时黑金卡
                case 67:// 随机限时彩虹卡
                    optionHtml += `<option value="2" ${rtypeSel}>随机值</option>`
                    break;
            }

            return optionHtml;
        },

        getSkinConf: (propsId) => {
            for (const v of privateFunc.PropsConf) {
                if (v.id === propsId) {
                    return v.skinList;
                }
            }

            return []
        },

        getOneSkinName: (propsId, skin) => {
            const skinArr = privateFunc.getSkinConf(propsId)
            if (skinArr.length === 0) {
                return '';
            }

            for (const skinInfo of skinArr) {
                if (skinInfo.id === skin) {
                    return skinInfo.name;
                }
            }

            return ''
        },

        getOnePropName: (propsId) => {
            for (const v of privateFunc.PropsConf) {
                if (v.id === propsId) {
                    return v.name;
                }
            }
            return ''
        },

        BuildRewardsTag: (data) => {
            let html = ""
            if (data.length === 0) {
                return html
            }

            for (const v of data) {
                let propsName = privateFunc.getOnePropName(v.propsId)

                let dc = 'btn-primary';
                if ((v.skin && v.skin !== 0) || v.rtype !== 1) {
                    dc = "btn-danger";
                }

                // 有皮肤
                if (v.skin && v.skin !== 0) {
                    const skinName = privateFunc.getOneSkinName(v.propsId, v.skin)
                    if (skinName === '') {
                        propsName = `${propsName}(ID:${v.skin})(已失效)`
                    } else {
                        propsName = `${skinName}(ID:${v.skin})`
                    }
                }

                let propsUnit
                // 随机金卡 随机黑金卡 随机限时金卡 随机限时黑金卡 随机限时彩虹卡
                if ([13, 48, 49, 50, 67].includes(v.propsId)) {
                    propsUnit = v.rtype === 1 ? ' 固定' : (v.rtype === 2 ? '随机' : '固定金卡反面');
                } else if (privateFunc.ActIdList.includes(v.propsId)) {
                    propsUnit = '分钟';
                } else {
                    propsUnit = v.rtype === 1 ? '个' : '倍';
                }

                const span = `<span style="margin-top: 2px;height: 30px;font-size: 12px" class="btn  ${dc}">${propsName}：${v.num}${propsUnit}</span>&nbsp;`
                html += span;
            }
            return html
        },

        formatObject: () => {
            return $.userPlugin.ParseIntData(Object.values($('#propsConfForm').toObject().props ?? []))
        },

        verifyReward: (dataObject) => {
            for (const v of dataObject) {
                if (privateFunc.NumIsOneList.includes(v.propsId) && v.num !== 1) {
                    alert('宝箱,金卡等奖励值只支持一个');
                    return false;
                }

                if (privateFunc.ActIdList.includes(v.propsId) && v.skin === 0) {
                    alert('活动券的皮肤必须选择');
                    return false;
                }

                const propsNum = privateFunc.RewardNumLimit[v.propsId]
                if (!isEmpty(propsNum) && propsNum < v.num) {
                    const propName = privateFunc.getOnePropName(v.propsId)
                    const ret = confirm(`【${propName}】的发放我们建议不能超过：${propsNum}  确认发放么？`);
                    if (ret !== true) {
                        return false
                    }
                }
            }

            return true
        },

        formatNodeData:(node)=>{
            const nodeData = node.data('value')
            return  isArray(nodeData) ? nodeData : []
        },

        parseObject: (array) => {
            const dataArr = [];
            for (const item of array) {

                const matchArr = item.name.match(/(?<=\[)(.+?)(?=\])/g);

                if (dataArr[matchArr[0]] === undefined) {
                    dataArr[matchArr[0]] = {
                        "propsId": 0, "num": 0, "rtype": 1, "skin": ""
                    }
                }

                dataArr[matchArr[0]][matchArr[1]] = item.value
            }

            let formatArr = []
            for (const v of dataArr) {
                formatArr.push(v)
            }

            return $.userPlugin.ParseIntData(formatArr);
        }
    };

    return exportFunc
}));



