var FPY_detailFun = function (KDApi, $, _) {

    let model = {},
        items = [],
        goodsArr = [],
        pageId = '',
        kplx = '0', // 0蓝色发票，1红色发票 2空白红冲  10红字信息表
        qdhp = '0', // 1清单红票
        zsfs = '0', // 0-普通征税方式 2- 差额征税
        editType = '0', // 0可编辑，1不可编辑    批量开票查看时用到
        seeditable = '0', // 税额是否可编辑，0-不可编辑
        hsbz = '0', // 0不含税;1含税
        deduction = ''; // 扣除额
    // this.totalAmount = ''; // 发票总金额

    const focusArr = ['ggxh', 'xmdw', 'xmsl', 'xmdj', 'xmje']; // 回车切换焦点顺序
    const taxRateArr = [
        {value: '0.17', text: '17%'},
        {value: '0.16', text: '16%'},
        {value: '0.13', text: '13%'},
        {value: '0.11', text: '11%'},
        {value: '0.10', text: '10%'},
        {value: '0.09', text: '9%'},
        {value: '0.06', text: '6%'},
        {value: '0.05', text: '5%'},
        {value: '0.04', text: '4%'},
        {value: '0.03', text: '3%'},
        {value: '0.01', text: '1%'},
        {value: '0.015', text: '1.5%'},
        {value: '0.00Z0', text: '0%(出口退税)'}, // lslbs: '1'
        {value: '0.00Z1', text: '0%(免税)'}, // lslbs: '1'
        {value: '0.00Z2', text: '0%(不征税)'}, // lslbs: '2'
        {value: '0.00Z3', text: '0%(普通零税率)'} // lslbs: '3'
    ];

    this.initHtml = function (_model, props) {
        model = _model;
        var popsData = {};
        if (props != null && props.data != null) {
            popsData = props.data;
        }
        KDApi.loadFile('../invoicedetail/css/detailLine.css', model, function () {
            KDApi.templateFilePath('../invoicedetail/html/detailLine.html', model, popsData).then(
                function (result) {
                    if (model.dom.innerHTML === "" || isUpdate) {
                        model.dom.innerHTML = result;
                    }
                    setInitData(popsData);
                    initEvent(props)
                }
            )
        })
    };

    var setInitData = function (props) {
        try {
            var data = props.data ? props.data : props;
            pageId = data['pageId'];
            hsbz = data['hsbz'];
            kplx = data['kplx'];
            qdhp = data['qdhp'];
            zsfs = data['zsfs'];
            console.log('setInitData', data);
            seeditable = data['seeditable'];
            editType = data['editType'];
            if (data["items"]) {
                items = data['items'];
                if ('1' === editType) {
                    $('#addDetailLine' + pageId).hide();
                    $('#addDiscountLine' + pageId).hide();
                } else {
                    $('#addDetailLine' + pageId).show();
                    $('#addDiscountLine' + pageId).show();
                    if ('1' === kplx) {
                        if (zsfs === '2') {
                            $('#addDetailLine' + pageId).hide();
                            $('#addDiscountLine' + pageId).hide();
                            $('#addDeduction' + pageId)[0].style.display = 'none';
                        } else {
                            $('#addDiscountLine' + pageId).hide();
                        }
                    } else {
                        if (zsfs === '2') {
                            $('#addDetailLine' + pageId).hide();
                            $('#addDeduction' + pageId)[0].style.display = 'inline-block';
                            if (items.length === 2) {
                                $('#addDiscountLine' + pageId).hide();
                            }
                        } else {
                            if (items[items.length - 1].xmlx === '2') {
                                $('#addDiscountLine' + pageId).hide();
                            } else {
                                $('#addDiscountLine' + pageId).show();
                            }
                            $('#addDeduction' + pageId)[0].style.display = 'none';
                        }
                    }
                }

            } else {
                items = [];
                pushDefaultItem();
            }
            // 红字信息表
            if (kplx == '10') {
                $('#addDiscountLine' + pageId).hide();
            }
			// 清单红票
			if('1' == qdhp){
				$('#addDetailLine' + pageId).hide();
				$('#addDiscountLine' + pageId).hide();
			}
            if(items.length > 300) {
                setTimeout(()=> {
                    showLine(pageId);
                    calcTotal(pageId);
                }, 666)
            }else {
                showLine(pageId);
                calcTotal(pageId);
            }
        } catch (err) {
        }
    };

    function pushDefaultItem() {
        items = [{
            index: '',
            id: '',
            xmlx: '0', // 0正常行;1折扣行;2被折扣行
            xmmc: '',  // 项目名称
            ggxh: '',  // 规格型号
            xmdw: '',  // 项目单位
            xmsl: '',  // 项目数量
            xmdj: '',  // 项目单价
            xmdjhs: '',  // 项目单价含税
            xmje: '',  // 项目金额
            xmjehs: '',  // 项目金额含税
            sl: '',  // 税率
            slText: '',  // select选中使用
            se: '',    // 税额
            spbm: '',  // 商品编码
            spmc: '',  // 商品名称
            zzstsgl: '', // 增值税特殊管理
            kce: ''      // 扣除额
        }];
    }

    this.updateHtml = function (props) {
        pageId = props.data['pageId'];
        var popsData = {};
        if (props != null && props.data != null) {
            popsData = props.data;
        }
        console.log('-----updateHtml popsData:', popsData);
        var eventkey = popsData['eventkey'];
        console.log('-----eventkey:', eventkey);
        switch (eventkey) {
            case 'queryGoods':
                queryGoods(pageId, popsData);
                break;
            case 'sethsbz':
                sethsbz(pageId, popsData);
                break;
            case 'setkplx':
                setkplx(pageId, popsData);
                break;
            case 'opendiscount':
                opendiscount(pageId, popsData);
                break;
            case 'openinvoice':
                openinvoice(pageId, popsData);
                break;
            case 'btn_save':
            case 'btn_submit':
                // 红字信息表点保存或提交
                redInfoOperation(eventkey);
                break;
            case 'btnflush':
                flush(pageId);
                break;
            case 'setzsfs':
                setzsfs(pageId, popsData);
                break;
            case 'loadData':
                loadData(pageId, popsData);
                break;
            case 'queryName':
                queryName(pageId, popsData);
                break;
            case 'returncezs':
                returncezs(pageId, popsData);
                break;
        }
    };

    function queryGoods(pageId, popsData) {
        var xmmc = popsData['xmmc'];
        var spmc = popsData['spmc'];
        var index = popsData['index'];
        var spbm = popsData['spbm'];
        var sl = popsData['sl'];
        var slText = popsData['slText'];
        var xmdj = popsData['xmdj'];
        var xmdjhs = popsData['xmdjhs'];
        var zzstsgl = popsData['zzstsgl'];
        items[index].spmc = spmc;
        items[index].sl = sl;
        items[index].slText = slText;
        items[index].xmmc = xmmc.indexOf('*') > -1 ? xmmc : '*' + spmc + '*' + xmmc;
        items[index].spbm = spbm;
        items[index].zzstsgl = zzstsgl;
        items[index].xmdj = xmdj;
        items[index].xmdjhs = xmdjhs;
        items[index].xmdw = popsData['xmdw'];
        items[index].ggxh = popsData['ggxh'];
        console.log('queryGoods items:', items);

        $('#detailtable' + pageId).find('.part').eq(index).find('.xmmc').find('input').eq(0).blur(); // 手动失去焦点
        calcTotal(pageId);
    }

    function sethsbz(pageId, popsData) {
        hsbz = popsData['hsbz'];

        if ('1' == hsbz) {
            $('#headje' + pageId).html('金额(含税)');
            $('#headdj' + pageId).html('单价(含税)');
        } else {
            $('#headje' + pageId).html('金额(不含税)');
            $('#headdj' + pageId).html('单价(不含税)');
        }
        for (const i in items) {
            updateDetailHtml(i, pageId);
        }
        calcTotal(pageId);
    }

    function setkplx(pageId, popsData) {
        // 点击开票方式 0-正数 1-负数 2-空白红冲 3 - 开差额
        flush(pageId);
        kplx = popsData['kplx'];
        items = popsData['items'];
        deduction = '';
        $('#addDeduction' + pageId).hide();
        switch (kplx) {
            case "0":
                $('#addDetailLine' + pageId).show();
                $('#addDiscountLine' + pageId).show();
                break;
            case "1":
                // $('#addDetailLine' + pageId).hide();
                $('#addDiscountLine' + pageId).hide();
                break;
            case "2":
                console.log("kplx2>>>>>>>" + kplx);
                $('#addDetailLine' + pageId).show();
                $('#addDiscountLine' + pageId).hide();
                // $('#addDeduction' + pageId)[0].style.display = 'none';
                break;
        }
        hsbz = popsData['hsbz'];
        if ('1' == hsbz) {
            $('#headje' + pageId).html('金额(含税)');
            $('#headdj' + pageId).html('单价(含税)');
        } else {
            $('#headje' + pageId).html('金额(不含税)');
            $('#headdj' + pageId).html('单价(不含税)');
        }
		
		// 清单红票
		if('1' == popsData['qdhp']){
			$('#addDetailLine' + pageId).hide();
            $('#addDiscountLine' + pageId).hide();
		}
		
        // for (const i in items) {
        //     // calculateSE(i, pageId);
        //     calcSE(i)
        // }
        showLine(pageId);
        calcTotal(pageId);
    }

    function opendiscount(pageId, popsData) {
        // 添加折扣行
        var rowData = popsData['rowData'];
        items[items.length - 1].xmlx = '2';
        items.push(rowData);
        items[items.length - 1].kce = '0'; // 折扣行的差额置0
        showLine(pageId);
        calcTotal(pageId);
    }

    function openinvoice() {
        model.invoke('openinvoice', items);
    }

    function redInfoOperation(eventKey) {
        model.invoke(eventKey, items);
    }

    function setzsfs(pageId, popsData) {
        if (popsData['check'] === '1') {
            let flag = false; // 默认没有数据
            for (let key in items[0]) {
                if (!!items[0][key] && items[0][key] > 0) {
                    flag = true;
                }
            }
            if (items.length > 1 || flag) {
                model.invoke('checkback', '1');
            } else {
                model.invoke('checkback', '0');
            }
            return;
        }
        flush(pageId);
        kplx = popsData['kplx'];
        if (kplx === '3') {
            editType = 0;
            $('#addDetailLine' + pageId).hide();
            $('#addDeduction' + pageId)[0].style.display = 'inline-block';
        } else {
            kplx = '0';
            deduction = '';
            $('#addDetailLine' + pageId).show();
            $('#addDiscountLine' + pageId).show();
            $('#addDeduction' + pageId).hide();
        }
    }

    function loadData(pageId, popsData) {
        editType = popsData['editType'];
        var items_ = popsData['items'];
        if (!!items_) {
            items = items_;
        }
        if (popsData['seeditable']) {
            seeditable = popsData['seeditable'];
        }
        if ('1' === editType) {
            $('#addDetailLine' + pageId).hide();
            $('#addDiscountLine' + pageId).hide();
        } else {
            $('#addDetailLine' + pageId).show();
            $('#addDiscountLine' + pageId).show();
        }
        showLine(pageId);
        if (!!items_) {
            calcTotal(pageId);
        }
    }

    function queryName(pageId, popsData) {
        goodsArr = popsData['goods'];
        if (goodsArr.length === 0) {
            $('#drop-down' + pageId).hide();
            return;
        }
        var index = goodsArr[0].index;

        var str = ``;
        for (var i = 0; i < goodsArr.length; i++) {
            var curItem = popsData['goods'][i];
            str += `<li title="${curItem['xmmc'].replace(/^\*.+\*/g, '')}" data-index='${i}' class="item-name">${curItem['xmmc'].replace(/^\*.+\*/g, '')}</li>`;
        }
        $('#drop' + pageId).html(str);
        $('#drop-down' + pageId)[0].style.top = ((Number(index) + 1) * $('#detailtable' + pageId + ' .part')[0].clientHeight + $('#detailpart' + pageId).height() - Number($('#detailtable' + pageId).scrollTop())) + 'px';
        $('#drop-down' + pageId).show();
    }

    function returncezs(pageId, popsData) {
        deduction = popsData['deduction'];
        // 所有明细更新扣除额
        for (let item of items) {
            if (item['xmlx'] != '1') {
                item.kce = deduction;
            }
        }
        for (const i in items) {
            calcSE(i);
            inverseCalcXMJE(i);
            inverseCalcXMDJ(i);
        }
        showLine(pageId);
        calcTotal(pageId);
    }

    function flush() {
        pushDefaultItem();
        showLine(pageId);
    }

    // 渲染明细行
    function showLine(pageId) {
        $('#drop' + pageId).off('click'); // 解绑商品模糊搜索下拉选择事件
        let text = '';
        for (let i in items) {
            let item = items[i];
            text += `<div class='part'>
                <span class="item-index">${Number(i) + 1}</span><div class='name xmmc'><input placeholder="可使用Enter键搜索"  type='text' ${item.xmlx !== '0' || editType === '1' || qdhp === '1' ? 'disabled' : ''} value='${item.xmmc}' data-name='xmmc' data-index='${i}' maxlength="90" autocomplete="off"></div>
                <div class='name ggxh'><input type='text' ${item.xmlx !== '0' || editType === '1' || qdhp === '1' ? 'disabled' : ''} value='${item.ggxh}' data-name='ggxh' data-index='${i}' maxlength="40" autocomplete="off"></div>
                <div class='name xmdw'><input type='text' ${item.xmlx !== '0' || editType === '1' || qdhp === '1' ? 'disabled' : ''} value='${item.xmdw}' data-name='xmdw' data-index='${i}' maxlength="20" autocomplete="off"></div>
                <div class='name xmsl'><input type='text' ${item.xmlx === '1' || editType === '1' || qdhp === '1' ? 'disabled' : ''} value='${item.xmsl}' data-name='xmsl' data-index='${i}' maxlength="16" autocomplete="off"></div>
                <div class='name xmdj'><input  type='text' ${item.xmlx === '1' || editType === '1' || qdhp === '1' ? 'disabled' : ''} value='${hsbz === '0' ? item.xmdj : item.xmdjhs}' data-name='xmdj' data-index='${i}' maxlength="16" autocomplete="off"></div>
                <div class='name xmje'><input type='text' ${editType === '1' ? 'disabled' : ''} value='${hsbz === '0' ? item.xmje : item.xmjehs}' data-name='xmje' data-index='${i}' maxlength="12" autocomplete="off"></div>
                <div class='name sl'>
                    <select ${item.xmlx !== '0' || editType === '1' || qdhp === '1' ? 'disabled' : ''} data-name='sl' data-index='${i}' style='height: 23px;'><option value="" style="display: none;"></option>`;
            for (const o of taxRateArr) {
                text += `<option value='${o.value}' ${o.value === item.slText ? 'selected' : ''}>${o.text}</option>`;
            }
            text += `
                    </select>
                </div>
                <div class='name se'><input type='text' ${seeditable === '1' || qdhp === '1' ? '' : 'disabled'}  value='${item.se}' data-name='se' data-index='${i}' maxlength="20" autocomplete="off"></div>
                <div class='name cz'>${i !== '0' && item.xmlx !== '2' && editType !== '1' ? `<span class='del' data-index='${i}'></span>` : ''}</div>
            </div>`;
        }
        $('#detailtable' + pageId).html(text);
        bindSelectEvent(); // 重新注册商品模糊搜索下拉选择事件
    }

    function bindSelectEvent() {
        // 选择名称下拉选项
        $('#drop' + pageId).on('click', 'li', e => {
            const {index} = e.target.dataset;
            const value = trim(e.target.innerText);
            console.log('------选择搜索下拉名称-----' + value);
            var i = goodsArr[0].index;
            items[i] = {...items[i], ...goodsArr[index]};
            updateDetailHtml(i);
            calcTotal();
            $('#drop-' + pageId).html('');
            $('#drop-down' + pageId).hide();
        });

        // 点击其他地方隐藏下拉框
        $(document).on('click', e => {
            const className = e.target.className;
            const {name} = e.target.dataset;
            if (className != 'drop-down' && name != 'xmmc') {
                $('#drop' + pageId).html('');
                $('#drop-down' + pageId).hide();
            }
        });
    }

    var initEvent = function (props) {
        bindSelectEvent();
        pageId = props.data['pageId'];
        $('#detailtable' + pageId).on('click', '.del', e => {
            const i = $(e.target).attr('data-index');
            // 折扣行删除，被折扣行改为正常行
            if (items[i].xmlx === '1') {
                items[i - 1].xmlx = '0';
                $('#addDiscountLine' + pageId).show();
            }
            items.splice(i, 1);
            showLine(pageId);
            calcTotal(pageId);
        });

        $("#addDetailLine" + pageId).click(() => {
            if (kplx == '10' && items.length === 8) {
                model.invoke('tipNotify', '红字信息表最多只能有8行明细');
                return
            }
			if ( (kplx == '1' || kplx == '2') && items.length === 8) {
                model.invoke('tipNotify', '红字发票最多只能有8行明细');
                return
            }
            items.push({
                index: '',
                xmlx: '0', // 0正常行;2被折扣行;1折扣行
                xmmc: '',  // 项目名称
                ggxh: '',  // 规格型号
                xmdw: '',  // 项目单位
                xmsl: '',  // 项目数量
                xmdj: '',  // 项目单价
                xmdjhs: '',  // 项目单价含税
                xmje: '',  // 项目金额
                xmjehs: '',  // 项目金额含税
                sl: '',  // 税率
                slText: '',  // select选中使用
                se: '',    // 税额
                spbm: '',  // 商品编码
                spmc: '',  // 商品名称
                zzstsgl: '', // 增值税特殊管理
                kce: ''      // 扣除额
            });
            showLine(pageId);
        });

        $("#addDiscountLine" + pageId, model.dom).click(function () {
            const lastItem = items[items.length - 1];
            if (kplx === '3' && lastItem.kce === '') {
                model.invoke('tipNotify', '扣除金额不能为空！');
                return;
            }
            if (lastItem.xmlx === '1') {
                model.invoke('tipNotify', '最后一行已经是折扣行');
                return;
            } else if (lastItem.xmje - lastItem.kce <= 0) {
                model.invoke('tipNotify', '被折扣行金额不能小于等于0');
                return;
            } else if (!lastItem.xmmc) {
                model.invoke('tipNotify', '被折扣行“项目名称”不能为空');
                return;
            } else {
                console.log('添加折扣行');
                model.invoke('opendiscount', lastItem);
            }
        });

        // add deduction
        $("#addDeduction" + pageId, model.dom).click(function () {
            model.invoke('addDeduction', items);
        });

        $('#detailtable' + pageId).on('keydown', 'input', e => {
            const {name, index} = e.target.dataset;
            if (e.keyCode === 13 && name === 'xmmc') {
                var itemrow = items[index];
                itemrow.index = index;
                model.invoke('queryGoods', itemrow);
            }
            if (e.keyCode === 13 && name !== 'xmmc') {
                let i = focusArr.indexOf(name);
                $('#detailtable' + pageId).find('.part').eq(index).find('.' + name).find('input').eq(0).blur(); // 手动失去焦点
                if (i === focusArr.length - 1){
                    return false;
                }
                $('#detailtable' + pageId).find('.part').eq(index).find('.' + focusArr[i + 1]).find('input').eq(0).focus(); // 手动赋予焦点
            }
        });

        $('#detailtable' + pageId).on('dblclick', 'input', e => {
            if (editType == '1' || qdhp == '1') {
                return;
            }
            const {name, index} = e.target.dataset;
            if (name === 'xmmc') {
                var itemrow = items[index];
                itemrow.index = index;
                if (itemrow.xmlx !== '0') {
                    return;
                }
                model.invoke('queryGoods', itemrow);
            }
        });

        //input输入
        $('#detailtable' + pageId).on('input', 'input', e => {
            const {name, index} = e.target.dataset;
            const value = trim(e.target.value);
            console.log('------input输入-----' + name);
            switch (name) {
                case 'xmmc':
                    var xmmc = value;
                    var spmc = items[index].spmc;
                    if (xmmc == spmc) {

                        items[index].xmmc = '';
                        items[index].spmc = '';
                        items[index].spbm = '';

                        syncShowData('xmmc', '', index, pageId);
                    } else {
                        if (value != '') {
                            items[index][name] = value;
                        }
                        syncShowData(name, value, index, pageId);
                    }
                    if (value.length >= 2) {
                        var o = {
                            index: index,
                            value: value
                        };
                        model.invoke('queryName', o);
                    }
                    break;
                default:
                    break;
            }
        });

        // 明细行滚动的时候，隐藏下拉框
        $('#detailtable' + pageId).on('scroll', e => {
            if ($('#detailtable' + pageId).scrollTop() > 0 && $('#drop-down' + pageId)[0].style.display === 'block') {
                $('#drop-down' + pageId).hide()
            }
        });

        // input失去焦点
        $('#detailtable' + pageId).on('blur', 'input', e => {
            const {name, index} = e.target.dataset;
            let value = trim(e.target.value);
            console.log('-----------失去焦点-----' + name);
            switch (name) {
                case 'xmsl': // 数量
                    if (isNaN(value)) {
                        model.invoke('tipNotify', '请输入正确的数量');
                        value = '';
                    }
                    inputXMSL(value, index);
                    break;
                case 'xmdj': // 单价
                    if (isNaN(value)) {
                        model.invoke('tipNotify', '请输入正确的单价');
                        value = '';
                    }
                    inputXMDJ(value, index);
                    break;
                case 'xmje': // 金额
                    if (isNaN(value)) {
                        model.invoke('tipNotify', '请输入正确的金额');
                        value = '';
                    }
                    inputXMJE(value, index);
                    break;
                case 'xmmc':
                    var xmmc = value;
                    var spmc = items[index].spmc;
                    if (xmmc == spmc) {
                        items[index].xmmc = '';
                        items[index].spmc = '';
                        items[index].spbm = '';
                    } else {
                        if (value === '') {
                            items[index].xmsl = '';
                            items[index].xmje = '';
                            items[index].xmjehs = '';
                            items[index].se = '';
                        }
                    }
                    break;
                default:
                    index !== undefined && (items[index][name] = value);
                    break;
            }
            updateDetailHtml(index, pageId, model);
            calcTotal(pageId);
        });

        $('#detailtable' + pageId).on('change', 'select', e => {
            const {name, index} = e.target.dataset;
            const value = e.target.value;
            let sl = '0';
            let lslbs = '';
            let ssyhzc = '';
            let ssyhzcnr = '';
            switch (value) {
                case '0.00Z0': // 出口退税
                    lslbs = '1';
                    break;
                case '0.00Z1': // 免税
                    lslbs = '1';
                    ssyhzc = '1';
                    ssyhzcnr = '免税';
                    break;
                case '0.00Z2': // 不征税
                    lslbs = '2';
                    ssyhzc = '1';
                    ssyhzcnr = '不征税';
                    break;
                case '0.00Z3': // 普通零税率
                    lslbs = '3';
                    ssyhzc = '0';
                    ssyhzcnr = '';
                    break;
                default:
                    sl = value;
            }
            items[index][name] = sl;
            items[index].slText = value;
            inputSL(index);
            updateDetailHtml(index);
            calcTotal();
        });
    };

    function trim(v) {
        return v.replace(/^\s+/g, '').replace(/\s+$/g, '');
    }

    // 数量输入 （计算单价、金额、税额）
    function inputXMSL(value, i) {
        const {xmsl, xmdj, xmdjhs, xmje} = items[i];
        if (xmsl === value){
            return; // 如果数量没有改变则不需要重新计算
        }
        if (value == 0) {
            items[i].xmsl = '';
            items[i].xmje = '';
            items[i].xmjehs = '';
            items[i].se = '';
            return
        }
        // 数值，红冲应为负值，其它应为正值
        if (value === '0' || isNaN(value) || (kplx == '10' && value >= 0) || ((kplx === '1' || kplx === '2') && value >= 0) || ((kplx === '0' || kplx === '3') && value < 0)) {
            // 数据错误不更新，需要提示
            const tip = kplx === '0' || kplx === '3' ? '数量应为正值' : '数量应为负值';
            items[i].xmsl = '';
            model.invoke('tipNotify', tip);
        } else {
            items[i].xmsl = toFixedTwoEight(value);
            // 计算金额和税额
            if ((hsbz === '0' && xmdj !== '') || (hsbz === '1' && xmdjhs !== '')) {
                calcXMJE(i);
                calcSE(i);
                inverseCalcXMJE(i);
                inverseCalcXMDJ(i)
            } else if (xmje !== '') {
                calcXMDJ(i);
                inverseCalcXMDJ(i)
            }
        }
    }

    // 单价输入 （计算金额跟数量）
    function inputXMDJ(value, i) {
        const {xmsl, xmdj, xmdjhs, xmje} = items[i];
        if ((hsbz === '0' && xmdj === value) || (hsbz === '1' && xmdjhs === value)){
            return; // 如果单价没有改变则不需要重新计算
        }
        if (value == 0) {
            items[i].xmdj = '';
            items[i].xmdjhs = '';
            items[i].xmje = '';
            items[i].xmjehs = '';
            items[i].se = '';
            return;
        }
        // 非负数
        if (isNaN(value) || value <= 0) {
            // 数据错误不更新，需要提示
            model.invoke('tipNotify', '单价应为正数');
            items[i].xmdj = '';
            items[i].xmdjhs = '';
            return;
        }
        hsbz === '0' ? items[i].xmdj = toFixedTwoEight(value) : items[i].xmdjhs = toFixedTwoEight(value);
        // 计算数量 金额 税额
        if (xmsl === '' && xmje != '') {
            calcXMSL(i);
            inverseCalcXMDJ(i);
        } else if (xmsl === '' && xmje === '') {
            inverseCalcXMDJ(i);
        } else if (xmsl !== '') {
            calcXMJE(i);
            calcSE(i);
            inverseCalcXMJE(i);
            inverseCalcXMDJ(i); // 提前反算（失去焦点时同时反算出含税/不含税对应值）
        }
    }

    // 金额输入
    function inputXMJE(value, i) {
        const {xmsl, xmdj, xmje, xmjehs} = items[i];
        if ((hsbz === '0' && xmje === value) || (hsbz === '1' && xmjehs === value)){
            return; // 如果金额没有改变则不需要重新计算
        }
        if (value == 0) {
            items[i].xmdj = '';
            items[i].xmdjhs = '';
            items[i].xmje = '';
            items[i].xmjehs = '';
            items[i].se = '';
            return;
        }
        // 数值，红冲、折扣行应为负值，其它应为正值
        if (isNaN(value) || (kplx == '10' && value >= 0) || (kplx === '1' && value >= 0) || (kplx === '2' && value >= 0) || ((kplx === '0' || kplx === '3') && value <= 0 && items[i].xmlx != 1) || (items[i].xmlx == 1 && value >= 0)) {
            // 数据错误不更新，需要提示
            const tip = kplx === '1' || kplx === '2' || kplx == '10' || items[i].xmlx == 1 ? '金额应为负值' : '金额应为正值';
            model.invoke('tipNotify', tip);
            items[i].xmje = '';
            items[i].xmjehs = '';
        } else {
            hsbz === '0' ? items[i].xmje = toFixedTwo(value) : items[i].xmjehs = toFixedTwo(value);
            if (xmsl !== '') {
                calcXMDJ(i);
                calcSE(i);
                inverseCalcXMJE(i);
                inverseCalcXMDJ(i);
            } else if (xmsl === '' && xmdj !== '') {
                calcXMSL(i);
                calcSE(i);
                inverseCalcXMJE(i);
            }
            if (xmsl === '' && xmdj === '') {
                calcSE(i);
                inverseCalcXMJE(i);
            }
        }
    }

    // 改变税率（计算单价、金额、税率）
    function inputSL(i) {
        const {sl, xmje, kce} = items[i];
        if (hsbz === '0') {
            if (sl * 1 === 0.015) {
                items[i].se = toFixedTwo(accMul(accDiv(Add(xmje, -kce), '1.035'), sl));
            } else {
                items[i].se = toFixedTwo(accMul(Add(xmje, -kce), sl));
            }
        } else {
            if (sl * 1 === 0.015) {
                items[i].se = toFixedTwo(
                    accMul(
                        accDiv(Add(items[i].xmjehs, -kce), Add(1, 0.05)), sl)); //  税率 * 含税金额/(1 + 0.05)
            } else {
                items[i].se = toFixedTwo(
                    accMul(
                        accDiv(Add(items[i].xmjehs, -kce), Add(1, sl)), sl)); //  税率 * 含税金额/(1 + 税率)
            }
        }
        inverseCalcXMJE(i);
        inverseCalcXMDJ(i);
    }

    // 计算数量
    function calcXMSL(i) {
        const {xmdj, xmdjhs, xmje, xmjehs} = items[i];
        if (hsbz === '0') {
            items[i].xmsl = toFixedTwoEight(accDiv(xmje, xmdj));
        } else {
            items[i].xmsl = toFixedTwoEight(accDiv(xmjehs, xmdjhs));
        }
    }

    // 计算单价
    function calcXMDJ(i) {
        const {xmsl, xmje, xmjehs} = items[i];
        if (hsbz === '0') {
            items[i].xmdj = toFixedTwoEight(accDiv(xmje, xmsl));
        } else {
            items[i].xmdjhs = toFixedTwoEight(accDiv(xmjehs, xmsl));
        }
    }

    // 计算金额
    function calcXMJE(i) {
        const {xmsl, xmdj, xmdjhs} = items[i];
        if (hsbz === '0') {
            items[i].xmje = toFixedTwo(accMul(xmdj, xmsl));
        } else {
            items[i].xmjehs = toFixedTwo(accMul(xmdjhs, xmsl));
        }
    }

    // 计算税额
    function calcSE(i) {
        const {sl, xmje, kce} = items[i];
        if(sl === ''){
            return;
        }

        if (hsbz === '0') {
            if (sl * 1 === 0.015) {
                items[i].se = toFixedTwo(accMul(accDiv(Minus(xmje, kce), '1.035'), sl));
            } else {
                items[i].se = toFixedTwo(accMul(Minus(xmje, kce), sl));
            }
        } else {
            if (sl * 1 === 0.015) {
                items[i].se = toFixedTwo(
                    accMul(
                        accDiv(Minus(items[i].xmjehs, kce), Add(1, 0.05)), sl)); //  税率 * 含税金额/(1 + 0.05)
            } else {
                items[i].se = toFixedTwo(
                    accMul(
                        accDiv(Minus(items[i].xmjehs, kce), Add(1, sl)), sl)); //  税率 * 含税金额/(1 + 税率)
            }
        }
    }

    // 含税不含税反算（单价）   反算单价时时先反算金额
    function inverseCalcXMDJ(i) {
        const {sl, xmsl, xmje, xmjehs, xmdj, xmdjhs} = items[i];
        if (hsbz === '0') {
            // 不含税，则反算出含税
            if (xmdj === '') return;
            if (xmje !== '' && xmsl !== '') {
                items[i].xmdjhs = toFixedTwoEight(accDiv(xmjehs, xmsl));
            } else {
                items[i].xmdjhs = toFixedTwoEight(accMul(xmdj, Add(1, sl)));
            }
        } else {
            if (xmdjhs === '') return;
            if (xmjehs !== '' && xmsl !== '') {
                items[i].xmdj = toFixedTwoEight(accDiv(xmje, xmsl));
            } else {
                items[i].xmdj = toFixedTwoEight(accDiv(xmdjhs, Add(1, sl)));
            }
        }
    }

    // 含税不含税反算（金额）
    function inverseCalcXMJE(i) {
        const {xmje, xmjehs, se} = items[i];
        if (hsbz === '0') {
            // 不含税，则反算出含税
            if (xmje === '') return;
            items[i].xmjehs = toFixedTwo(Add(xmje, se));
        } else {
            if (xmjehs === '') return;
            items[i].xmje = toFixedTwo(Minus(xmjehs, se));
        }
    }

    // 同步更新页面明细列表数据
    function updateDetailHtml(index) {
        index = Number(index);
        if (items[index].xmje.indexOf('e+') > -1 || items[index].xmje.split('.')[0].length > 12) {
            items[index].xmsl = '';
            items[index].xmdj = '';
            items[index].xmdjhs = '';
            items[index].xmje = '';
            items[index].xmjehs = '';
            items[index].se = '';
            model.invoke('tipNotify', '金额整数部分不能超过12位！');
        }
        if (hsbz === '0') {
            syncShowData('xmdj', items[index].xmdj, index, pageId);
            syncShowData('xmje', items[index].xmje, index, pageId);
        } else {
            syncShowData('xmdj', items[index].xmdjhs, index, pageId);
            syncShowData('xmje', items[index].xmjehs, index, pageId);
        }
        syncShowData('xmsl', items[index].xmsl, index, pageId);
        syncShowData('sl', items[index].slText, index, pageId);
        syncShowData('se', items[index].se, index, pageId);
        syncShowData('xmmc', items[index].xmmc, index, pageId);
        syncShowData('ggxh', items[index].ggxh, index, pageId);
        syncShowData('xmdw', items[index].xmdw, index, pageId);
    }

    // dom控制 同步显示数据
    function syncShowData(name, value, index) {
        if (name === 'sl') {
            $('#detailtable' + pageId).find('.part').eq(index).find('.' + [name]).find('select').val(value);
        } else {
            $('#detailtable' + pageId).find('.part').eq(index).find('.' + [name]).find('input').val(value);
        }
    }

    // 合计计算显示
    function calcTotal() {
        let amountAcc = '', taxAcc = '', amountTaxTotalUppercase = '', amountTaxTotalLowercase = '';
        items.forEach((item, index) => {
            let xmje = item.xmje;
            let se = item.se;
            if (item.xmje !== '') {
                amountAcc = Add(amountAcc, xmje);
                taxAcc = Add(taxAcc, se);
                amountTaxTotalLowercase = Add(item.xmjehs, amountTaxTotalLowercase) + '';
            }
        });
        // this.totalAmount = amountAcc;
        if (amountAcc !== '') {
            amountTaxTotalUppercase = amountTaxTotalLowercase < 0
                ? '（负）' + moneyToCapital(amountTaxTotalLowercase.replace('-', ''))
                : moneyToCapital(amountTaxTotalLowercase);
            amountTaxTotalLowercase = '￥' + toFixedTwo(amountTaxTotalLowercase);
            amountAcc = toFixedTwo(amountAcc);
            taxAcc = toFixedTwo(taxAcc);
        }
        $('#amountAcc' + pageId).html(amountAcc);
        $('#taxAcc' + pageId).html(taxAcc);
        $('#amountTaxTotalLowercase' + pageId).html(amountTaxTotalLowercase);
        $('#amountTaxTotalUppercase' + pageId).html(amountTaxTotalUppercase);
    }

    // 数字转文字
    function moneyToCapital(n) {
        if (n === 0) {
            return "零";
        }
        if (n === '') {
            return '';
        }
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
            return '';
        var unit = "千百拾亿千百拾万千百拾元角分", str = "";
        n += '00';
        var p = n.indexOf('.');
        if (p >= 0)
            n = n.substring(0, p) + n.substr(p + 1, 2);
        unit = unit.substr(unit.length - n.length);
        for (var i = 0; i < n.length; i++)
            str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
    }

    // 乘法
    function accMul(arg1, arg2, arg3 = 1) {
        var m = 0,
            s1 = arg1.toString(),
            s2 = arg2.toString(),
            s3 = arg3.toString();
        try {
            m += s1.split('.')[1].length;
        } catch (e) {
        }
        try {
            m += s2.split('.')[1].length;
        } catch (e) {
        }
        try {
            m += s3.split('.')[1].length;
        } catch (e) {
        }
        return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) * Number(s3.replace('.', '')) / Math.pow(10, m);
    }

    // 除法
    function accDiv(arg1, arg2) {
        var d1, d2,
            n1 = Number(arg1.toString().replace(".", "")),
            n2 = Number(arg2.toString().replace(".", ""));
        if (n2 == 0) return 0;
        try {
            d1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            d1 = 0;
        }
        try {
            d2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            d2 = 0;
        }
        return (n1 / n2) * Math.pow(10, d2 - d1);
    }

    //加法
    function Add(arg1, arg2) {
        var r1, r2, m;
        try {
            r1 = arg1.toString().split('.')[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split('.')[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
    }

    // 减法
    function Minus(arg1, arg2) {
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split('.')[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split('.')[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }

    // 保留两位小数
    function toFixedTwo(n) {
        let _sign = (Number(n) < 0) ? -1 : 1;
        return ((Math.round(accMul(accMul(n, 100), _sign)) / 100 ) * _sign).toFixed(2);
    }

    // 保留指定小数不补零
    function toFixedNoZero(val, len) {
        len = isNaN(len) ? 0 : len;
        let num = Math.pow(10, len);
        return Math.round(val * num) / num;
    }

    // 保留两位到8位小数
    function toFixedTwoEight(val) {
        let _sign = (Number(val) < 0) ? -1 : 1;

        let num = Math.pow(10, 8);
        let tem = Math.round(val * num * _sign) / num * _sign;
        return tem.toString();
    }
};