/**
 * Created by Mai on 2017/7/25.
 */

var VolumePrice = {
    createNew: function (project) {
        let tools = {
            owner: project
        };

        class volumePrice {
            constructor () {
                this.datas = [];

                let maxID = 0;
                this.getNewID = function () {
                    return maxID += 1;
                };
                this.maxID = function (ID) {
                    if (arguments.length === 0) {
                        return maxID;
                    } else {
                        maxID = Math.max(ID, maxID);
                    }
                };
                tools.owner.registerModule(ModuleNames.volume_price, this);
            };

            getProject () {
                return tools.owner;
            };
            getSourceType () {
                return ModuleNames.volume_price;
            };

            loadData (datas) {
                this.datas = datas;
                // generate Fees & Flags Index，For View & Calculate
                for (let data of datas) {
                    data.feesIndex = {};
                    data.fees.forEach(function (fee) {
                        data.feesIndex[fee.fieldName] = fee;
                    });
                    this.maxID(data.ID);
                }
            };
            setMaxID (ID) {
                this.maxID(ID);
            }

            getTempVolumePrice (newID, billsID, serialNo) {
                var newData = {'ID': newID, 'serialNo': serialNo, projectID: tools.owner.ID()};
                newData[project.masterField.volumePrice] = billsID;
                newData.type = '材料';
                newData.programID = projectObj.project.projectInfo.property.engineering;
                return newData;
            };
            getBillsSortVolumePrice (billsID) {
                var arr = this.datas.filter(function (data) {
                    return data[tools.owner.masterField.volumePrice] === billsID;
                });
                arr.sort(function (x, y) {
                    return x.serialNo - y.serialNo;
                });
                return arr;
            };

            getCounterData (count) {
                var updateData = {'projectID': this.getProject().ID()};
                if (count) {
                    updateData[this.getSourceType()] = this.maxID() + count;
                } else {
                    updateData[this.getSourceType()] = this.maxID() + 1;
                }
                return updateData;
            };
            getInsertVolumePriceData (billsID, pre) {
                let bv = this.getBillsSortVolumePrice(billsID);
                let updateData = [];
                if (pre && bv.indexOf(pre) > -1) {
                    let preIndex = bv.indexOf(pre), i;
                    updateData.push({updateType: 'ut_create', updateData: this.getTempVolumePrice(this.maxID() + 1, billsID, preIndex < bv.length - 1 ? bv[preIndex + 1].serialNo : bv[preIndex].serialNo + 1)});
                    for (i = preIndex + 1; i < bv.length; i++) {
                        updateData.push({updateType: 'ut_update', updateData: this.getTempVolumePrice(bv[i].ID, billsID, i < bv.length - 1 ? bv[i+1].serialNo : bv[i].serialNo + 1)});
                    }
                } else {
                    updateData.push({updateType: 'ut_create', updateData: this.getTempVolumePrice(this.maxID() + 1, billsID, bv.length > 0 ? bv[bv.length - 1].serialNo + 1 : 1)});
                }
                return updateData;
            };
            insertVolumePrice (billsID, pre) {
                tools.owner.pushNow('insertVolumePrice', [this.getSourceType(), this.getProject().projCounter()], [this.getInsertVolumePriceData(billsID, pre), this.getCounterData()]);

                let bv = this.getBillsSortVolumePrice(billsID), newVP = null;
                if (pre && bv.indexOf(pre) > -1) {
                    let preIndex = bv.indexOf(pre);
                    newVP = this.getTempVolumePrice(this.getNewID(), billsID, preIndex < bv.length - 1 ? bv[preIndex + 1].serialNo : bv[preIndex].serialNo + 1);
                    this.datas.push(newVP);
                    for (let i = preIndex + 1; i < bv.length; i++) {
                        bv[i].serialNo = i < bv.length - 1 ? bv [i + 1].serialNo : bv[i].serialNo + 1;
                    }
                } else {
                    newVP = this.getTempVolumePrice(this.getNewID(), billsID, bv.length > 0 ? bv[bv.length - 1].serialNo + 1 : 1);
                    this.datas.push(newVP);
                }
                return newVP;
            };

            getDeleteData (volumePrice) {
                var updateData = [];
                updateData.push({'updateType': 'ut_delete', 'updateData': {'ID': volumePrice.ID, 'projectID': this.getProject().ID()}});
                return updateData;
            };
            delete (volumePrice) {
                this.getProject().pushNow('deleteVolumePrice', [this.getSourceType()], [this.getDeleteData(volumePrice)]);
                this.datas.splice(this.datas.indexOf(volumePrice), 1);
            };

            getDeleteDataByBills (nodes) {
                let updateData = [];
                for (let node of nodes) {
                    if (node.children.length > 0) {
                        updateData = updateData.concat(this.getDeleteDataByBills[node.children]);
                    } else {
                        let vps = this.getBillsSortVolumePrice(node.getID());
                        for (let vp of vps) {
                            updateData.push({'updateType': 'ut_delete', 'updateData': {'ID': vp.ID, 'projectID': this.getProject().ID()}});
                        }
                    }
                }
                return updateData;
            };
            deleteByBills (nodes) {
                for (let node of nodes) {
                    if (node.children.length > 0) {
                        this.deleteByBills([node.children]);
                    } else {
                        let vps = this.getBillsSortVolumePrice(node.getID());
                        for (let vp of vps) {
                            this.datas.splice(this.datas.indexOf(vp), 1);
                        }
                    }
                }
            };

            calculate (volumePrice) {
                if (!calcFees.findFee(volumePrice, 'common')) {
                    calcFees.addFee(volumePrice, 'common');
                }
                volumePrice.feesIndex.common.totalFee = (volumePrice.feesIndex.common.unitFee * volumePrice.quantity).toDecimal(tools.owner.Decimal.common.totalFee);
                volumePrice.needRefresh = true;
            }
            updateField(volumePrice, field, newValue, updateNow) {
                calcFees.setFee(volumePrice, field, newValue);
                let updateData = [];
                let data = {'ID': volumePrice.ID, 'projectID': this.getProject().ID()};
                if (field === 'quantity') {
                    data[field] = newValue;
                    this.calculate(volumePrice);
                    data.fees = volumePrice.fees;
                } else if (field === 'feesIndex.common.unitFee') {
                    this.calculate(volumePrice);
                    data.fees = volumePrice.fees;
                } else {
                    data[field] = newValue;
                }
                updateData.push({'updateType': 'ut_update', 'updateData': data});
                if (updateNow) {
                    tools.owner.pushNow('updateVolumePrice', this.getSourceType(), updateData);
                } else {
                    tools.owner.push(this.getSourceType(), updateData);
                }
            }
        }

        return new volumePrice();
    }
}
