'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2019/6/5
 * @version
 */
//导出接口相关
const ExportView = (() => {
    let _base = XML_EXPORT_BASE,
        _cache = _base.CACHE,
        _util = _base.UTIL;
    // 导出数据缓存
    let _exportCache = [];
    //设置工程编号表格数据设置
    const sheetSetting = {
        header: [
            {headerName: '名称', headerWidth: 200, dataCode: 'name', dataType: 'String'},
            {headerName: '工程编号', headerWidth: 200, dataCode: 'code', dataType: 'String'},
        ],
        view: {
            lockColumns: ['name'],
            lockRows: [0]
        }
    };
    //操作状态
    const STATE = {
        checking: false,    //自检
        exporting: false,   //导出
        confirming: false   //导出确认
    };
    let spread = null;
    //初始化设置工程编号表格
    function initSpread(datas) {
        if (spread) {
            return;
        }
        spread = SheetDataHelper.createNewSpread($("#exportSpread")[0], 1);
        sheetCommonObj.spreadDefaultStyle(spread);
        let sheet = spread.getSheet(0);
        sheetCommonObj.initSheet(sheet, sheetSetting, 30);
        sheetCommonObj.showTreeData(sheet, sheetSetting, datas);
    }
    //获取设置的工程编号
    function getCodeFromSheet(sheet) {
        let codeCol = 1;
        let rst = [];
        //排除建设项目行
        for (let row = 1; row < sheet.getRowCount(); row++) {
            rst.push(sheet.getText(row, codeCol) || '');
        }
        return rst;
    }
    // 回到初始状态，需要清空cache中的数据
    function resetState() {
        _exportCache = [];
        _cache.clear();
    }
    // 设置提示高度样式
    function setHeightByInfo(infos) {
        if (infos.length * 20 > 400) {
            $('#hintBox_caption').addClass('export-check');
        }
    }
    // 显示工程编码设置窗口
    function showSetCodeModal(isPring) {
        if (isPring) {
            setTimeout(() => {
                $('#exportCode').modal('show');
            }, 300);
        } else {
            $('#exportCode').modal('show');
        }
    }
    // 确定导出
    async function handleExportConfirm(codes) {
        if (!spread || !_exportCache || !_exportCache.length) {
            return false;
        }
        if (STATE.confirming) {
            return;
        }
        STATE.confirming = true;
        let pr = new SCComponent.InitProgressBar();
        try {
            pr.start('导出数据接口', '正在导出文件，请稍候……');
            // 导出文件
            await _base.exportFile(codes, _exportCache, XMLStandard.resetContentCode, XMLStandard.saveAsFile);
        } catch (err) {
            console.log(err);
            alert(err);
        }
        pr.end();
        $('#exportCode').modal('hide');
        $('#export').modal('hide');
        setTimeout(() => {
            STATE.confirming = false;
        }, 300);
    }
    //事件监听
    function exportListener() {
        //导出接口-项目自检
        $('#export-check').click(async function () {
            let failList = _cache.getItem('failList');
            let checkedDatas = $('#export input[type="checkbox"]:checked');
            if (!checkedDatas.length) {
                return;
            }
            if (STATE.checking) {
                return;
            }
            STATE.checking = true;
            let pr = new SCComponent.InitProgressBar();
            try {
                if (!_exportCache || !_exportCache.length) {
                    pr.start('导出数据接口', '正在自检，请稍候……');
                    for (let checkedData of checkedDatas) {
                        let fileKind = parseInt($(checkedData).val());
                        let exportData = await _base.extractExportData(XMLStandard.entry, _base.CONFIG.GRANULARITY.PROJECT,
                            XMLStandard.summaryObj, fileKind, projectObj.project.ID(), userID);
                        _exportCache.push(...exportData);
                    }
                }
                // 基本信息、工程特征必填项自检，这里的必填项不由xsd文件规定，而是后台根据业务需要配置
                const requiredFails = _util.propertyCheck();
                if (requiredFails.length) {
                    setHeightByInfo(requiredFails);
                    throw requiredFails.join('<br/>');
                }
                failList = _util.deWeightHints(failList);
                if (failList.length) {
                    //设置提示弹窗
                    setHeightByInfo(failList);
                    throw failList.join('<br/>');
                } 
                // 弱自检
                const infos = _util.softCheck();
                if (infos.length) {
                    setHeightByInfo(infos);
                    throw infos.join('<br/>');
                }
                throw '自检完成，未检测到错误数据。'
            } catch (err) {
                console.log(err);
                alert(err);
            }
            pr.end();
            setTimeout(() => {
                STATE.checking = false;
            }, 300);
        });

        //导出接口,如果没有错误，弹出工程编号设置窗口
        $('#export-confirm').click(async function () {
            let failList = _cache.getItem('failList');
            let checkedDatas = $('#export input[type="checkbox"]:checked');
            if (!checkedDatas.length) {
                return;
            }
            if (STATE.exporting) {
                return;
            }
            STATE.exporting = true;
            let pr = new SCComponent.InitProgressBar();
            try {
                let isPring = false;    //是否调用了进度条（控制工程窗口什么时候显示，优化交互）
                if (!_exportCache || !_exportCache.length) {
                    isPring = true;
                    pr.start('导出数据接口', '正在导出文件，请稍候……');
                    for (let checkedData of checkedDatas) {
                        let fileKind = parseInt($(checkedData).val());
                        let exportData = await _base.extractExportData(XMLStandard.entry, _base.CONFIG.GRANULARITY.PROJECT, 
                            XMLStandard.summaryObj, fileKind, projectObj.project.ID(), userID);
                        _exportCache.push(...exportData);
                    }
                    pr.end();
                }
                // 基本信息、工程特征必填项自检，这里的必填项不由xsd文件规定，而是后台根据业务需要配置
                const requiredFails = _util.propertyCheck();
                if (requiredFails.length) {
                    setHeightByInfo(requiredFails);
                    throw requiredFails.join('<br/>');
                }
                failList = _util.deWeightHints(failList);
                if (failList.length) {
                    //错误-设置提示弹窗
                    setHeightByInfo(failList);
                    throw failList.join('<br/>');
                }
                // 如果没有自检过，需要进行弱自检，并且弹出的窗口包含“继续、取消”按钮
                const infos = _util.softCheck();
                if (infos.length) {
                    const doYes = () => {
                        showSetCodeModal(isPring);
                    };
                    hintBox.infoBox('系统提示', infos.join('<br/>'), hintBox.btnType.yesNo, doYes, null, ['继续', '取消']);
                    setTimeout(() => {
                        STATE.exporting = false;
                    }, 300);
                    return;
                }
                //弹出工程编号设置窗口
                showSetCodeModal(isPring);
            } catch (err) {
                console.log(err);
                pr.end();
                alert(err);
            }
            setTimeout(() => {
                STATE.exporting = false;
            }, 300);
        });
        //工程编号设置窗口-----
        //设置工程编号
        $('#exportCode').on('shown.bs.modal', function () {
            let projectData = null;
            if(typeof SEIObject !== 'undefined' && SEIObject.exporting == true){//如果是重庆指标接口调用的
                if(SEIObject.fileCache && SEIObject.fileCache.length == 2){
                    projectData = SEIObject.fileCache[0].projectData;
                }else{
                    alert('数据错误！');
                    $(this).modal('hide');
                    return false;
                }
                $("#export_index_checkbox").show();
            }else {
                if (!_exportCache || !_exportCache.length) {
                    alert('数据错误！');
                    $(this).modal('hide');
                    return false;
                }
                projectData = _cache.getItem('projectData');
                $("#export_index_checkbox").hide();
            }
            initSpread(XML_EXPORT_BASE.UTIL.getCodeSheetData(projectData));
        });
        //设置完工程编号后，导出数据。如果选中多个文件，导出压缩包
        $('#exportCode-confirm').click(async function () {
            // 工程编号
            let codes = getCodeFromSheet(spread.getSheet(0));
            if (codes.includes('')) {
                alert('单项、单位工程工程编号不可为空。');
                STATE.confirming = false;
                return false;
            }
            if ([...new Set(codes)].length !== codes.length) {
                alert('单项、单位工程工程编号必须唯一。');
                STATE.confirming = false;
                return false;
            }
            typeof SEIObject !== 'undefined' && SEIObject.exporting ? await exportUtil.exprotZBFX(codes) : await handleExportConfirm(codes);
        });
        //导出窗口--------
        $('#export').on('hide.bs.modal', function() {
            resetState();
            STATE.checking = false;
            STATE.exporting = false;
            STATE.confirming = false;
            //恢复设置提示弹窗 因为是共用的alert
            //$('#hintBox_caption').removeClass('export-check');  已经统一在info_box关闭时删除了
            $('#export input[type="checkbox"]:eq(0)').prop('checked', true);
            if (spread) {
                spread.destroy();
                spread = null;
            }
        });
        $('#export input[type="checkbox"]').click(function () {
            resetState();
        });
    }
    return {exportListener}
})();