'use strict';

/**
 * 期 - 中间计量
 *
 * @author Mai
 * @date 2019/1/16
 * @version
 */

$(document).ready(() => {
    let gsSpread, gsTree;
    stageIm.init(stage, imType);

    function getSelectDetailData() {
        const rowIndex = parseInt($('#im-list').attr('rowIndex'));
        const data = stageIm.getImData()[rowIndex];
        return data;
    }

    function reLoadDetailData() {
        const data = getSelectDetailData();
        $('#edit-detail').show();
        $('#save-detail').hide();
        $('#cancel-detail').hide();
        $('#bgl-code').val(data.bgl_code ? data.bgl_code : '');
        $('#bw-name').val(data.bw ? data.bw : '');
        $('#start-peg').val(data.start_peg ? data.start_peg : '');
        $('#end-peg').val(data.end_peg ? data.end_peg : '');
        $('#unit-name').val(data.jldy ? data.jldy : '');
        $('#drawing-code').val(data.drawing_code ? data.drawing_code : '');
        $('#calc-memo').val(data.calc_memo ? data.calc_memo : '');
        if (data.calc_img) {
            $('#calc-img').html('<img src="/' + data.calc_img + '" class="d-100" width="100%">');
        } else {
            $('#calc-img').html('');
        }
    }

    function reBuildImData() {
        const imData = stageIm.buildImData();
        const html = [];
        for (const im of imData) {
            html.push('<tr>');
            html.push('<td>');
            html.push(im.code);
            html.push('</td>');
            html.push('<td>');
            html.push(im.im_code);
            html.push('</td>');
            html.push('<td>');
            html.push(im.doc_code);
            html.push('</td>');
            html.push('<td>');
            html.push(im.fbfx);
            html.push('</td>');
            html.push('<td align="right">');
            html.push(im.jl);
            html.push('</td>');
            html.push('</tr>');
        }
        $('#im-list').html(html.join(''));
        $('tr:first', '#im-list').addClass('table-warning');
        $('#im-list').attr('rowIndex', 0);
        reLoadDetailData();
        $('tr', '#im-list').click(function () {
            $('tr.table-warning').removeClass('table-warning');
            $(this).addClass('table-warning');
            $('#im-list').attr('rowIndex', this.rowIndex - 1);
            reLoadDetailData();
        });
    }

    postData(window.location.pathname + '/load', { loadType: 'all' }, function (data) {
        stageIm.loadData(data.ledger, data.curStage, data.stageDetail);
        reBuildImData();
    });

    let gatherConfirmPopover = {
        reBind: function (obj, eventName, fun) {
            obj.unbind(eventName);
            obj.bind(eventName, fun);
        },
        check: function (pos, hint, okCallback) {
            const confirmObj = $('#gather-confirm'), hintObj = $('#gather-confirm-hint');
            const okObj = $('#gather-confirm-ok'), cancelObj = $('#gather-confirm-cancel');
            this.reBind(cancelObj, 'click', function () {
                confirmObj.hide();
            });
            this.reBind(okObj, 'click', function () {
                okCallback();
                confirmObj.hide();
            });
            hintObj.text(hint);
            confirmObj.css("top", pos.y).css("left", pos.x).show();
        }
    };

    // 选择中间计量模式
    $('div[name="im-type"]').click(function () {
        function chooseType(obj) {
            obj.style.cursor = 'default';
            $(obj).children().addClass('text-primary');
            $('h5', obj).prepend('<i class="fa fa-check pull-right"></i>');
        }
        function validType(obj) {
            obj.style.cursor = 'pointer';
            $(obj).children().removeClass('text-primary');
            $('i', obj).remove();
        }
        if (this.style.cursor === 'pointer') {
            const typeArr = $('div[name="im-type"]');
            for (const t of typeArr) {
                if ($(t).attr('im-type') === $(this).attr('im-type')) {
                    chooseType(t);
                } else {
                    validType(t)
                }
            }
        }
    });
    // 提交 中间计量模式
    $('#choose-ok').click(() => {
        const chooseType = _.find($('div[name="im-type"]', '#im-type'), function (it) {
            return it.style.cursor !== 'pointer';
        });
        const data = {
            im_type: parseInt($(chooseType).attr('im-type')),
            im_pre: $('#im-pre').val(),
        };
        postData(window.location.pathname + '/build', data, function (result) {
            stage.im_type = data.im_type;
            stage.im_pre = data.im_pre;
            // 加载生成数据
            reBuildImData();
            $('#choose').modal('hide');
        });
    });
    // 拉取树结构信息
    $('#choose2').on('shown.bs.modal', function () {
        if (!gsSpread) {
            gsSpread = SpreadJsObj.createNewSpread($('#im-gather-spread')[0]);
            SpreadJsObj.initSheet(gsSpread.getActiveSheet(), {
                cols: [
                    {title: '计量\n汇总', colSpan: '1', rowSpan: '1', field: 'check', hAlign: 1, width: 50, formatter: '@', readOnly: true, cellType: 'checkbox'},
                    {title: '项目节编号', colSpan: '1', rowSpan: '1', field: 'code', hAlign: 0, width: 150, formatter: '@', readOnly: true, cellType: 'tree'},
                    {title: '清单编号', colSpan: '1', rowSpan: '1', field: 'b_code', hAlign: 0, width: 80, formatter: '@', readOnly: true},
                    {title: '名称', colSpan: '1', rowSpan: '1', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                    {title: '单位', colSpan: '1', rowSpan: '1', field: 'unit', hAlign: 1, width: 60, formatter: '@', readOnly: true},
                ],
                headRows: 1,
                emptyRows: 0,
                headRowHeight: [40],
                defaultRowHeight: 21,
            });
            gsSpread.bind(spreadNS.Events.ButtonClicked, function (e, info) {
                function checkParent(node) {
                    const parent = gsTree.getParent(node);
                    if (parent) {
                        return parent.check ? parent.check : checkParent(parent);
                    } else {
                        return false;
                    }
                }

                function checkChildren(node) {
                    for (const child of node.children) {
                        if (child.check) {
                            return true;
                        } else if (checkChildren(child)) {
                            return true;
                        }
                    }
                    return false;
                }

                if (!$('#im-gather-check')[0].checked) { return; }

                const sheet = info.sheet, cellType = sheet.getCellType(info.row, info.col);
                if (cellType instanceof GC.Spread.Sheets.CellTypes.CheckBox) {
                    if (sheet.isEditing()) {
                        sheet.endEdit(true);
                    }
                }
                if (info.sheet.zh_setting) {
                    const col = info.sheet.zh_setting.cols[info.col];
                    if (col.field !== 'check') {
                        return;
                    }

                    const sortData = info.sheet.zh_dataType === 'tree' ? info.sheet.zh_tree.nodes : info.sheet.zh_data;
                    const node = sortData[info.row];
                    if (!node.check) {
                        if (checkParent(node)) {
                            const rect = info.sheet.getCellRect(info.row, info.col);
                            gatherConfirmPopover.check({
                                x: rect.x + rect.width / 2 + 25,
                                y: rect.y + rect.height / 2 + 3,
                            }, '父项已勾选，继续将取消父项勾选。', function () {
                                node.check = true;
                                const parents = gsTree.getFullPathNodes(gsTree.getParent(node).full_path);
                                const rows = [gsTree.nodes.indexOf(node)];
                                for (const p of parents) {
                                    if (p.check) {
                                        p.check = false;
                                        rows.push(gsTree.nodes.indexOf(p));
                                    }
                                }
                                SpreadJsObj.reLoadRowsData(info.sheet, rows);
                            });
                        } else if (checkChildren(node)) {
                            const rect = info.sheet.getCellRect(info.row, info.col);
                            gatherConfirmPopover.check({
                                x: rect.x + rect.width / 2 + 25,
                                y: rect.y + rect.height / 2 + 3,
                            }, '子项已勾选，继续将取消子项勾选。', function () {
                                node.check = true;
                                const posterity = gsTree.getPosterity(node);
                                const rows = [gsTree.nodes.indexOf(node)];
                                for (const p of posterity) {
                                    if (p.check) {
                                        rows.push(gsTree.nodes.indexOf(p));
                                        p.check = false;
                                    }
                                }
                                SpreadJsObj.reLoadRowsData(info.sheet, rows);
                            });
                        } else {
                            node.check = true;
                            SpreadJsObj.reLoadRowsData(info.sheet, [gsTree.nodes.indexOf(node)]);
                        }
                    } else {
                        node.check = false;
                        SpreadJsObj.reLoadRowsData(info.sheet, [gsTree.nodes.indexOf(node)]);
                    }
                }
            });
            const gsTree = stageIm.getGsTree();
            const gatherNodes = stage.im_gather_node ? _.map(stage.im_gather_node.split(','), _.toNumber) : [];
            for (const node of gsTree.datas) {
                node.check = gatherNodes.indexOf(node.id) !== -1;
            }
            gsTree.expandByLevel(4);
            SpreadJsObj.refreshTreeRowVisible(gsSpread.getActiveSheet());
            SpreadJsObj.resetFieldReadOnly(gsSpread.getActiveSheet, 'check', !$('#im-gather-check')[0].checked);
        } else {
            const gsTree = stageIm.getGsTree();
            const gatherNodes = stage.im_gather_node ? _.map(stage.im_gather_node.split(','), _.toNumber) : [];
            for (const node of gsTree.datas) {
                node.check = gatherNodes.indexOf(node.id) !== -1;
            }
            SpreadJsObj.reLoadColsData(gsSpread.getActiveSheet(), [0]);
        }
    });
    // 提交 高级设置
    $('#choose2-ok').click(() => {
        if (!gsTree) { return; }
        const nodes = [];
        for (const node of gsTree.datas) {
            if (node.check) {
                nodes.push(node.id);
            }
        }
        const data = {
            im_gather: $('#im-gather-check')[0].checked,
            im_gather_node: nodes.join(','),
        };
        postData(window.location.pathname + '/adv', data, function (result) {
            stage.im_gather = data.im_gather;
            stage.im_gather_node = data.im_gather_node;
            $('#choose2').modal('hide');
        });
    });
    // 编辑
    $('#edit-detail').click(function () {
        $(this).hide();
        $('#save-detail').show();
        $('#cancel-detail').show();
        $('#bgl-code').removeAttr('readonly');
        $('#bw-name').removeAttr('readonly');
        $('#start-peg').removeAttr('readonly');
        $('#end-peg').removeAttr('readonly');
        $('#unit-name').removeAttr('readonly');
        $('#drawing-code').removeAttr('readonly');
        $('#calc-memo').removeAttr('readonly');
    });
    // 保存
    $('#save-detail').click(() => {
        function check(field, obj, org, update) {
            const newValue = obj.val();
            if (!org[field]) {
                if (newValue !== '') {
                    update[field] = newValue;
                }
            } else if (newValue !== org[field]){
                update[field] = newValue;
            }
        }

        const data = getSelectDetailData();
        const updateData = {lid: data.lid};
        if (data.uuid) {
            updateData.uuid = data.uuid;
        } else {
            updateData.code = data.code;
            updateData.name = data.name;
            updateData.unit = data.unit;
            updateData.unit_price = data.unit_price;
        }
        check('bgl_code', $('#bgl-code'), data, updateData);
        check('bw', $('#bw-name'), data, updateData);
        check('start_peg', $('#start-peg'), data, updateData);
        check('end_peg', $('#end-peg'), data, updateData);
        check('jldy', $('#unit-name'), data, updateData);
        check('drawing_code', $('#drawing-code'), data, updateData);
        check('calc_memo', $('#calc-memo'), data, updateData);
        postData(window.location.pathname + '/save', updateData, function (result) {
            _.assign(data, result);
            $('#edit-detail').show();
            $('#save-detail').hide();
            $('#cancel-detail').hide();
            $('#bgl-code').attr('readonly', '');
            $('#bw-name').attr('readonly', '');
            $('#start-peg').attr('readonly', '');
            $('#end-peg').attr('readonly', '');
            $('#unit-name').attr('readonly', '');
            $('#drawing-code').attr('readonly', '');
            $('#calc-memo').attr('readonly', '');
        });
    });
    // 取消
    $('#cancel-detail').click(() => {
        $('#edit-detail').show();
        $(this).hide();
        $('#save-detail').hide();
        $('#bgl-code').attr('readonly', '');
        $('#bw-name').attr('readonly', '');
        $('#start-peg').attr('readonly', '');
        $('#end-peg').attr('readonly', '');
        $('#unit-name').attr('readonly', '');
        $('#drawing-code').attr('readonly', '');
        $('#calc-memo').attr('readonly', '');
        reLoadDetailData();
    });


    // 草图相关
    // 移动图片
    const moveImageItem = function (ev) {
        const item = this;
        const view = $('.img-view')[0];
        let oEvent = ev;
        // 浏览器有一些图片的默认事件,这里要阻止
        oEvent.preventDefault();
        let disX = oEvent.clientX - item.offsetLeft;
        let disY = oEvent.clientY - item.offsetTop;
        view.onmousemove = function (ev) {
            oEvent = ev;
            oEvent.preventDefault();
            let x = oEvent.clientX -disX;
            let y = oEvent.clientY -disY;

            // 图形移动的边界判断
            x = x <= 0 ? 0 : x;
            x = x >= view.offsetWidth - item.offsetWidth ? view.offsetWidth - item.offsetWidth : x;
            y = y <= 0 ? 0 : y;
            y = y >= view.offsetHeight - item.offsetHeight ? view.offsetHeight - item.offsetHeight : y;
            item.style.left = x + 'px';
            item.style.top = y + 'px';
        };
        // 图形移出父盒子取消移动事件,防止移动过快触发鼠标移出事件,导致鼠标弹起事件失效
        view.onmouseleave = function () {
            view.onmousemove = null;
            view.onmouseup = null;
        };
        // 鼠标弹起后停止移动
        view.onmouseup=function() {
            view.onmousemove = null;
            view.onmouseup = null;
        };
    };
    const removeImageItem = function () {
        $(this).parent().remove();
    };
    // 加载草图组成
    $('#edit-img').on('show.bs.modal', function () {
        const data = getSelectDetailData();
        const items = JSON.parse(data.calc_img_org) || [];
        const html = [];
        for (const item of items) {
            const itemStyle = 'top:' + item.top + ';' + 'left:' + item.left + ';';
            html.push('<div class="img-item" style="' + itemStyle + '">');
            html.push('<div class="img-bar">');
            html.push('<a href="javascript: void(0);" class="text-danger" title="删除"><i class="fa fa-remove"></i></a>');
            html.push('</div>');
            html.push('<img src="', item.src, '" id="draggable">');
            html.push('</div>');
        }
        $('.img-view').html(html.join(''));
        $('.img-item').mousedown(moveImageItem);
        $('.img-bar').click(removeImageItem);
    });
    // 上传图片
    $('#upload-img').click(function () {
        $('#upload-img-file').trigger('click');
    });
    $('#upload-img-file').change(function () {
        if ($(this).val()) {
            const formData = new FormData();
            formData.append('file', this.files[0]);
            postDataWithFile(window.location.pathname + '/add-img', formData, function (result) {
                const html = [];
                html.push('<div class="img-item">');
                html.push('<div class="img-bar">');
                html.push('<a href="" class="text-danger" title="删除"><i class="fa fa-remove"></i></a>');
                html.push('</div>');
                html.push('<img src="', '/' + result, '" id="draggable">');
                html.push('</div>');
                $('.img-view').append(html.join(''));
                $('.img-item').mousedown(moveImageItem);
                $('.img-bar').click(removeImageItem);
            });
        }
    });
    // 保存草图修改结果
    $('#edit-img-ok').click(function () {
        // 记录上传的图片的信息
        const items = $('.img-item');
        const data = getSelectDetailData();
        if (items.length > 0) {
            const itemInfo = [];
            for (const item of items) {
                const itemData = {
                    src: $('img', item).attr('src'),
                    left: item.style.left,
                    top: item.style.top,
                };
                itemInfo.push(itemData);
            }
            // 获取合并好的图片数据
            const canvas = document.createElement('canvas');
            const view = $('.img-view')[0];
            canvas.height = view.clientHeight;
            canvas.width = view.clientWidth;
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            for (const b of $('.img-item')) {
                const pos = $(b).position();
                const img = $('img', b)[0];
                ctx.drawImage(img, pos.left, pos.top, img.width, img.height);
            }
            // 生成上传数据
            const updateData = {updateType: 'update', lid: data.lid};
            if (data.uuid) {
                updateData.uuid = data.uuid;
            } else {
                updateData.code = data.code;
                updateData.name = data.name;
                updateData.unit = data.unit;
                updateData.unit_price = data.unit_price;
            }
            updateData.img = canvas.toDataURL('image/jpeg');
            updateData.imgInfo = itemInfo;
            postData(window.location.pathname + '/merge-img', updateData, function (result) {
                _.assign(data, result);
                $('#calc-img').html('<img src="/' + data.calc_img + '" class="d-100" width="100%">');
                $('#edit-img').modal('hide');
            });
        } else if (data.calc_img) {
            postData(window.location.pathname + '/merge-img', {updateType: 'clear', lid: data.lid, uuid: data.uuid}, function (result) {
                _.assign(data, result);
                $('#calc-img').html('');
                $('#edit-img').modal('hide');
            });
        }
    });
});