'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/8/6
 * @version
 */

// 向后端请求中间计量号
function getNewMeasureCode() {
    postData('/measure/newCode', null, function (code) {
        if (code !== '') {
            $('#mj-code').val(code);
        }
    });
}

function getMeasureWorkHtml (data) {
    const html = [];
    html.push('<tr>');
    html.push('<td>', '<a href="/measure/work/' + data.mid + '">', data.code, '</a>', '</td>');
    html.push('<td>0.00</td>');
    html.push('<td>' + moment(data.in_time).format('YYYYMM') + '</td>');
    html.push('<td></td>');
    html.push('<td>未上报</td>');
    html.push('<td>', data.user.role + '-' + data.user.name, '</td>');
    html.push('<td><a href="javascript: void(0);" data-toggle="modal" class="btn btn-outline-primary btn-sm" name="edit">编辑</a></td>')
    html.push('</tr>');
    return html.join('');
}

class codeRuleSet {
    constructor (obj) {
        this.body = obj;
        // 切换规则组件类型
        $('select', obj).change(function () {
            const codeType = this.selectedIndex;
            if (codeType === ruleConst.ruleType.addNo) {
                $('#format', obj).show();
                $('#text', obj).show();
                $('#text>label', obj).text('起始编号');
                $('#text>input', obj).val('001');
                const s = '0000000000' + 1;
                $('#text>input', obj).val(s.substr(s.length - $('#format>input', obj).val()));
            } else if (codeType === ruleConst.ruleType.text) {
                $('#format', obj).hide();
                $('#text', obj).show();
                $('#text>label', obj).text('文本');
                $('#text>input', obj).val('').attr('placeholder', '请在这里输入需要的文本');
            } else {
                $('#format', obj).hide();
                $('#text', obj).hide();
            }
        });
        // 修改编号位数
        $('#format>input', obj).change(function () {
            const s = '0000000000' + parseInt($('#text>input', obj).val());
            $('#text>input', obj).val(s.substr(s.length - $(this).val()));
        });
        // 新增规则组件
        $('#addRule', obj).click(function () {
            const codeType = $('select', obj)[0].selectedIndex;
            const rule = {rule_type: codeType}, html = [];
            let preview;
            switch (codeType) {
                case ruleConst.ruleType.tenderName: {
                    preview = $('#tenderName').text();
                    break;
                }
                case ruleConst.ruleType.text: {
                    rule.text =  $('#text>input', obj).val();
                    preview = rule.text;
                    break;
                }
                case ruleConst.ruleType.inDate: {
                    preview = moment().format('YYYYMM');
                    break;
                }
                case ruleConst.ruleType.addNo: {
                    rule.format = parseInt($('#format>input', obj).val());
                    rule.start = parseInt($('#text>input', obj).val());
                    const s = '0000000000';
                    preview = s.substr(s.length - rule.format);
                    break;
                }
            }
            // 更新规则
            codeRule.push(rule);
            // 更新规则显示
            html.push('<span class="badge badge-light" title="' + ruleConst.ruleString[codeType] + '" rule="' + JSON.stringify(rule) + '">');
            html.push('<span>' + preview + '</span>');
            html.push('<a href="javascript: void(0);" class="text-danger" title="移除"><i class="fa fa-remove"></i></a>');
            html.push('</span>');
            const part = $('#ruleParts', obj).append(html.join(''));
            // 更新规则预览
            $('#preview', obj).text($('#preview', obj).text() + preview);

            $('a', part).bind('click', function () {
                const index = $('a', obj).index(this);
                codeRule.splice(index, 1);
                $(this).parent().remove();
                const rules = $('span>span', obj), ruleText = [];
                for (const r of rules) {
                    ruleText.push(r.innerText);
                }
                $('#preview', obj).text(ruleText.join(''));
            });
        });
        // 删除规则组件
        $('a', $('#ruleParts', obj)).bind('click', function () {
            const index = $('a', obj).index(this);
            codeRule.splice(index, 1);
            $(this).parent().remove();
            const rules = $('span>span', obj), ruleText = [];
            for (const r of rules) {
                console.log(r.innerText + ':1');
                ruleText.push(r.innerText);
            }
            $('#preview', obj).text('当前规则：' + ruleText.join(''));
        });
    }
}

$(document).ready(() => {
    autoFlashHeight();
    // 新增中间计量 modal显示
    $('#add-mj').on('show.bs.modal', function() {
        getNewMeasureCode();
        if ($('#wlist').children.length === 0) {
            $('#addCancel').hide();
        } else {
            $('#addCancel').show();
        }
        $('#mj-code').removeClass('is-invalid');
    });
    // 新增中间计量--刷新编号
    $('#autoCode').click(getNewMeasureCode);
    // 添加中间计量 确定
    $('#addOk').click(function () {
        const data = {
            code: $('#mj-code').val(),
            date: $('#mj-date').val(),
        };
        postData('/measure/add', data, function (rst) {
            $('#mj-code').removeClass('is-invalid');
            $('#mj-add').modal('hide');
            $('#wlist').append(getMeasureWorkHtml(rst));
        }, function () {
            $('#mj-code').addClass('is-invalid');
            $('#mj-Hint').show();
        });
    });

    // 首次进入设置
    if (!codeRule || codeRule.length === 0) {
        codeRule = [];
        const firstSet = new codeRuleSet($('div.modal-body', '#first'));
        // 确认规则上传服务器
        $('#setRule', '#first').bind('click', function () {
            const data = {
                rule: ruleType,
                data: JSON.stringify(codeRule),
            };
            postData('/tender/rule', data, function () {
                $('#first').modal('hide');
                $('#add-mj').modal('show');
            });
        });

        $('#first').modal('show');
    } else if ($('#wlist').children.length === 0) {
        $('#add-mj').modal('show');
    }

    // 中间计量设置页面
    const obj = $('#rule');
    console.log(obj);
    const ruleSet = new codeRuleSet(obj);

    // 编辑
    $('a[name=edit]').bind('click', function () {
        const tr = $(this).parent().parent();
        const mid = tr.attr('mid');
        const code = tr.attr('code');
        // 调整删除页面
        $('#delOk').attr('mid', mid);
        $('#code', $('#del')).text(code);
        // 调整编辑页面
        const edit = $('#edit');
        edit.attr('mid', mid);
        $('#codeEdit').val(code);
        $('[data-target=#del]').text('删除 ' + code);
        edit.modal('show');
    });
    // 编辑 确定
    $('#editOk').click(function () {
        const data = {
            mid: $('#edit').attr('mid'),
            code: $('#codeEdit').val()
        }
        postData('/measure/modify', data, function (m) {
            const tr = $('tr[mid= ' + m.mid + ']');
            const tds = tr.children();
            tds[0].text(m.code);
            tds[2].text(moment(m.in_time).format('YYYYMM'));
        });
    });
    // 删除 确定
    $('#delOk').click(function () {
        const data = {
            mid: $(this).attr('mid'),
        }
        postData('/measure/delete', data, function (result) {
            if (result) {
                $('tr[mid= ' + data.mid + ']').remove();
            }
        })
    })
});