'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

const { app, assert } = require('egg-mock/bootstrap');
const excel = require('node-xlsx');
const xlsx = require('js-xlsx');
const addData = {
    name: 'test_deal_bills',
    category: null,
};
const mockData = {};
const _ = require('lodash');

describe('test/app/service/deal_bills.test.js', () => {
    // 准备测试数据，新增测试标段
    before(function* () {
        const ctx = app.mockContext();
        // 模拟登录session
        const postData = {
            account: '734406061@qq.com',
            project: 'T201711273363',
            project_password: 'mai654321',
        };
        ctx.session = {};
        const loginResult = yield ctx.service.projectAccount.accountLogin(postData, 2);
        assert(loginResult);
        mockData.session = ctx.session;
        // 移除旧测试数据
        const testTender = yield ctx.service.tender.getDataByCondition({
            name: addData.name,
            project_id: ctx.session.sessionProject.id,
        });
        if (testTender) {
            const result = yield ctx.service.tender.deleteTenderNoBackup(testTender.id);
            assert(result);
        }
        // 新增测试用标段
        const result = yield ctx.service.tender.add(addData);
        assert(result);
        const tender = yield ctx.service.tender.getDataByCondition({
            name: addData.name,
            project_id: ctx.session.sessionProject.id,
        });
        mockData.tender = {id: tender.id, data: tender};
        ctx.tender = mockData.tender;
    });
    // 导入 Excel数据（数据源：node-xlsx导入）
    it('test import Excel data by node-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-upload-test.xls';
        const sheets = excel.parse(file);

        const result = yield ctx.service.dealBills.importData(sheets[0], ctx.tender.id);
        assert(result);

        const bills = yield ctx.service.dealBills.getAllDataByCondition({where: {tender_id: ctx.tender.id}});
        assert(bills.length === 1);
        assert(bills[0].code === '101-1');
        assert(bills[0].tender_id === ctx.tender.id);
    });
    // 导入 Excel数据（数据源：js-xlsx导入）
    it('test import Excel data by js-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-upload-test.xls';

        const wb = xlsx.readFile(file);
        const name = wb.SheetNames[0];
        const sheetData = {
            rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
            merge: wb.Sheets[name]["!merges"],
        };
        const result = yield ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
        assert(result);

        const bills = yield ctx.service.dealBills.getAllDataByCondition({where: {tender_id: ctx.tender.id}});
        assert(bills.length === 1);
        assert(bills[0].code === '101-1');
        assert(bills[0].tender_id === ctx.tender.id);
    });
    // 导入 数据类型有误的excel（数据源：js-xlsx导入）
    it('test import Excel data with Type-Error by js-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-bills-typeError.xlsx';

        const wb = xlsx.readFile(file);
        const name = wb.SheetNames[0];
        const sheetData = {
            rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
            merge: wb.Sheets[name]["!merges"],
        };
        try {
            const result = yield ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
            assert(false);
        } catch (err) {
            assert(err);
            assert(err.indexOf('数据类型有误') > 0);
        }
    });
    // 导入 表头定义有误的excel（数据源：js-xlsx导入）
    it('test import Excel data with Col-Define-Error by js-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-bills-colDefError.xlsx';

        const wb = xlsx.readFile(file);
        const name = wb.SheetNames[0];
        const sheetData = {
            rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
            merge: wb.Sheets[name]["!merges"],
        };
        try {
            const result = yield ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
            assert(false);
        } catch (err) {
            assert(err);
            assert(err.indexOf('表头定义有误') > 0);
        }
    });
    // 导入 表头定义有误的excel（数据源：js-xlsx导入）
    it('test import Excel data with Col-Define-Error by js-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-bills-filterInvalidRows.xlsx';

        const wb = xlsx.readFile(file);
        const name = wb.SheetNames[0];
        const sheetData = {
            rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
            merge: wb.Sheets[name]["!merges"],
        };
        const result = yield ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
        assert(result);

        const bills = yield ctx.service.dealBills.getAllDataByCondition({where: {tender_id: ctx.tender.id}});
        assert(bills.length === 98);
    });
    // 导入 存在数量单价为空的数据
    it('test import Excel data by js-xlsx', function* () {
        const ctx = app.mockContext(mockData);
        const file = app.baseDir  + '/test/app/test_file/deal-bills-emptyCalcField.xls';

        const wb = xlsx.readFile(file);
        const name = wb.SheetNames[0];
        const sheetData = {
            rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
            merge: wb.Sheets[name]["!merges"],
        };
        const result = yield ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
        assert(result);

        const bills = yield ctx.service.dealBills.getAllDataByCondition({where: {tender_id: ctx.tender.id}});
        assert(bills.length === 4);

        assert(bills[0].code === '101-1');
        assert(bills[0].unit_price === 20000);
        assert(bills[0].quantity === 1);
        assert(bills[0].total_price === 1000);
        assert(bills[1].code === '101-2');
        assert(bills[1].unit_price === 1200);
        assert(!bills[1].quantity || bills[0].quantity === 1);
        assert(bills[1].total_price === 200);
        assert(bills[2].code === '101-3');
        assert(!bills[2].unit_price || bills[0].unit_price === 0);
        assert(bills[2].quantity === 2);
        assert(bills[2].total_price === 4000);
        assert(bills[3].code === '101-4');
        assert(bills[3].unit_price === 2000);
        assert(bills[3].quantity === 3);
        assert(!bills[3].total_price || bills[0].total_price === 0);
    });
});
