'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/9/26
 * @version
 */
let editCate;
// 初始化分类数据
function InitCategoryData(category) {
    const data = category instanceof Array ? category : [category];
    for (const d of data) {
        d.typeStr = cType.text[d.type];
    }
}
// 获取自定义分类可选类型Html(下拉、单选)
function getTypeHtml() {
    const html = [];
    for (const k in cType.key) {
        const value = cType.key[k];
        html.push('<div class="form-check form-check-inline">');
        html.push('<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio' + value + '" value="' + value + '">');
        html.push('<label class="form-check-label" for="inlineRadio' + value + '">', cType.text[value], '</label>');
        html.push('</div>');
    }
    return html.join('');
}
// 获取自定义分类html
function getCategoryHtml(category) {
    const data = category instanceof Array ? category : [category];
    const html = [];
    for (const d of data) {
        html.push('<tr ', d.value && d.value.length > 0 ? '' : 'class="table-warning"', 'cid="' + d.id + '">');
        html.push('<td>', d.name, '</td>');
        html.push('<td>', d.typeStr, '</td>');
        html.push('<td>');
        if (d.value && d.value.length > 0) {
            for (const v of d.value) {
                html.push('<span class="h5"><span class="badge badge-secondary">', v.value, '</span></span>\n');
            }
        } else {
            html.push('请在右侧添加值');
        }
        html.push('</td>');
        html.push('<td>');
        html.push('<a href="javasrcipt: void(0);" name="add" class="btn btn-sm btn-outline-primary"', 'cid="' + d.id, '">添加值</a>\n');
        html.push('<a href="javasrcipt: void(0);" name="edit-cate" class="btn btn-sm btn-outline-primary"', 'cid="' + d.id + '">编辑</a>\n');
        html.push('<a href="javasrcipt: void(0);" name="del" class="btn btn-sm btn-outline-danger"', 'cid="' + d.id + '">删除</a> ');
        html.push('</td>');
        html.push('<tr>');
    }
    return html.join('');
}
// 获取分类值html
function getValueHtml(value) {
    const html = [];
    for (const v of value) {
        html.push('<tr name="value" vid="' + v.id + '">');
        html.push('<td><input class="form-control form-control-sm" name="value" placeholder="请输入值" value="' + v.value + '" vid ="' + v.id +  '"></td>');
        html.push('<td>', v.relaTenders.length + v.newTenders.length ,'</td>');
        html.push('<td><a href="javasrcipt: void(0);" class="text-danger" name="del-value" vid="' + v.id + '">删除</a></td>');
        html.push('</tr>');
    }
    return html.join('');
}
// 根据分类id查找分类
function findCategory(cid) {
    for (const c of cData) {
        if (c.id === cid) {
            return c;
        }
    }
}
// 删除值 获取其他可用值的html
function getValidValueHtml(vid) {
    const html = [];
    const values = $('tr:not(.table-danger)[name=value]', '#value-list');
    for (const value of values) {
        const v = $(value);
        if (v.attr('vid') === vid || $('input', v).val() === '') { continue }
        html.push('<div class="form-check form-check-inline">');
        html.push('<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio' + v.attr('vid') + '" value="' + v.attr('vid') +'">');
        html.push('<label class="form-check-label" for="inlineRadio' + v.attr('vid') + '">' + $('input', v).val() + '</label>');
        html.push('</div>');
    }
    return html.join('');
}
// 初始化 添加值 编辑数据
function getEditCate(category) {
    function findTenderCate(tender, value) {
        for (const c of tender.category) {
            if (c.cid == value.cid) {
                return c;
            }
        }
    }

    editCate = JSON.parse(JSON.stringify(category));
    for (const v of editCate.value) {
        v.relaTenders = tenders.filter(function (t) {
            const cate = findTenderCate(t, v);
            return cate ? cate.value == v.id : false;
        });
        v.newTenders = [];
    }
}
// 绑定编辑值、删除值
function bindCategoryValueControl() {
    $('a[name="del-value"]').click(function () {
        const vid = $(this).attr('vid');
        const value = _.find(editCate.value, function (v) {
            return v.id == vid;
        });
        if (value.delete) { return; }

        if (value.relaTenders.length > 0) {
            // 提示用户转移标段
            $('#tender-count').text(value.relaTenders.length).attr('vid', vid);
            $('#tender-target').html(getValidValueHtml(vid));
            $('input[type=radio]', '#tender-target')[0].checked = true;
            $('#del-cate-value-ok').click(function () {
                const delVid = $('#tender-count').attr('vid');
                const tarVid = $('input:checked', '#tender-target').val();
                const delValue = _.find(editCate.value, function (v) {
                    return v.id == delVid;
                });
                const tarValue = _.find(editCate.value, function (v) {
                    return v.id == tarVid;
                });
                tarValue.newTenders = tarValue.newTenders.concat(delValue.relaTenders, delValue.newTenders);
                delValue.relaTenders = [];
                delValue.newTenders = [];
                delValue.delete = true;
                const delTr = $('tr[vid=' + delVid + ']');
                delTr.addClass('table-danger');
                $('input', delTr).attr('disabled', '');
                delTr.children()[1].innerText = '移动到其他项';
                $('tr[vid=' + tarVid + ']').children()[1].innerText = tarValue.relaTenders.length + tarValue.newTenders.length;
                $('#del-cate-value').modal('hide');
            });
            $('#del-cate-value').modal('show');
        } else {
            value.delete = true;
            const tr = $('tr[vid=' + vid + ']');
            tr.addClass('table-danger');
            $('input', tr).attr('disabled', '');
        }
    });
}
// 绑定分类控制等（添加值、编辑、删除）
function bindCategoryControl() {
    // 弹出添加值
    $('a[name=add]').bind('click', function () {
        const id = parseInt($(this).attr('cid'));
        const category = findCategory(id);
        getEditCate(category);
        $('#add-ok').attr('cid', id);
        if (editCate) {
            const list = $('#value-list');
            list.html(getValueHtml(editCate.value) + '<tr id="add-value-row"><td colspan="3"><a href="javascript: void(0);">添加新值</a></td></tr>');
            $('#add-value-row').click(function () {
                const newID = editCate.value.length > 0 ? _.maxBy(editCate.value, function (v) { return v.id; }).id + 1 : 1;
                const newValue = {
                    isNew: true,
                    id: newID,
                    value: '',
                    relaTenders: [],
                    newTenders: editCate.value.length > 0 ? [] : tenders.concat([]),
                };
                editCate.value.push(newValue);
                $(this).before(getValueHtml([newValue]));
                bindCategoryValueControl();
            });
            bindCategoryValueControl();
            $('#add').modal('show');
        }
    });
    // 弹出 编辑
    $('a[name=edit-cate]').bind('click', function () {
        const id = parseInt($(this).attr('cid'));
        const category = findCategory(id);
        $('input[name=name]', '#edit-cate').val(category.name);
        $('div[name=type]', '#edit-cate').html(getTypeHtml());
        $('#inlineRadio' + category.type, '#edit-cate')[0].checked = true;
        $('#edit-cate-ok').attr('cid', $(this).attr('cid'));
        $('#edit-cate').modal('show');
    });
    // 弹出 删除类别
    $('a[name=del]').bind('click', function () {
        $('#del-cate-ok').attr('cid', $(this).attr('cid'));
        $('#del-cate').modal('show');
    });
}

$(document).ready(() => {
    InitCategoryData(cData);
    $('#categoryList').html(getCategoryHtml(cData));
    bindCategoryControl();
    $('div[name=type]', '#add-cate').html(getTypeHtml());
    // 新增分类
    $('#add-cate-ok').click(function () {
        const name = $('input[name=name]', '#add-cate');
        const type = $('input[type=radio]:checked', '#add-cate');
        const data = {
            name: name.val(),
            type: parseInt(type.val()),
        };
        postData('/setting/category/add', data, function (data) {
            InitCategoryData(data);
            $('#categoryList').append(getCategoryHtml(data));
            bindCategoryControl();
            cData.push(data);
            $('#add-cate').modal('hide');
            name.val('');
            type[0].checked = false;
        }, function (msg) {
            $('#add-cate').modal('hide');
        });
    });
    // 添加值
    $('#add-ok').click(function () {
        const valueArr = [];
        const value = $('input[name=value]');
        for (const v of value) {
            if (v.value !== '') {
                const cateValue = _.find(editCate.value, function (ec) {
                    return $(v).attr('vid') == ec.id;
                });
                let newValue = {};
                if (cateValue.delete) {
                    newValue = { id: cateValue.id, delete: true, };
                } else if (cateValue.isNew) {
                    newValue = { value: $(v).val(), new: true, };
                } else {
                    newValue = { id: cateValue.id, value: $(v).val()};
                }
                if (!cateValue.delete && cateValue.newTenders.length > 0) {
                    newValue.newTenders = _.map(cateValue.newTenders, 'id');
                }
                valueArr.push(newValue);
            }
        }
        const data = {
            id: parseInt($(this).attr('cid')),
            updateValue: valueArr,
        };
        postData('/setting/category/value', data, function (data) {
            tenders = data.tenders;
            const category = findCategory(data.category.id);
            category.value = data.category.value;
            InitCategoryData(category);
            $('tr[cid=' + data.category.id + ']')[0].outerHTML = getCategoryHtml(category);
            bindCategoryControl();
            $('#add').modal('hide');
        }, function () {
            $('#add').modal('hide');
        });
    });
    // 编辑
    $('#edit-cate-ok').click(function () {
        const name = $('input[name=name]', '#edit-cate');
        const type = $('input[type=radio]:checked', '#edit-cate');
        const data = {
            id: parseInt($(this).attr('cid')),
            name: name.val(),
            type: parseInt(type.val()),
        }
        postData('/setting/category/update', data, function (data) {
            const category = findCategory(data.id);
            for (const c in data) {
                category[c] = data[c];
            }
            InitCategoryData(category);
            $('tr[cid=' + data.id + ']')[0].outerHTML = getCategoryHtml(category);
            bindCategoryControl();
            $('#edit-cate').modal('hide');
        }, function () {
            $('#edit-cate').modal('hide');
        });
    });
    // 删除类别
    $('#del-cate-ok').click(function () {
        const data = {
            id: parseInt($(this).attr('cid')),
        }
        postData('/setting/category/del', data, function () {
            $('tr[cid=' + data.id + ']').remove();
            $('#del-cate').modal('hide');
        }, function () {
            $('#del-cate').modal('hide');
        });
    });
});