/**
 * Created by zhang on 2019/12/12.
 */
let electrovalenceObj = {
    setting:{
        header:[
            {headerName: "代号", headerWidth: 70, dataCode: "code", dataType: "String"},
            {headerName: "名称", headerWidth: 150, dataCode: "displayName",dataType: "String"},
            {headerName: "规格", headerWidth: 70, dataCode: "specs", dataType: "Number",validator:"number"},
            {headerName: "预算价", headerWidth: 75, dataCode: "electPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "加权系数", headerWidth: 80, dataCode: "coe", hAlign: "right", dataType: "Number",validator:"number"}
        ],
        view: {
            lockColumns: ["code","specs"],
            rowHeaderWidth:25,
            colHeaderHeight:36
        }
    },
    spread:null,
    sheet:null,
    datas:[],
    total:0,
    options:[
        {code:"3005003",name:"电网电",specs:"",unit:"kW·h",type:"201"},
        {code:"8017001",name:"5kW以内柴油发电机组",specs:"5GF1",unit:"台班",type:"301"},
        {code:"8017002",name:"15kW以内柴油发电机组",specs:"12GF1",unit:"台班",type:"301"},
        {code:"8017003",name:"30kW以内柴油发电机组",specs:"30GFY-2",unit:"台班",type:"301"},
        {code:"8017004",name:"50kW以内柴油发电机组",specs:"50GFY-2",unit:"台班",type:"301"},
        {code:"8017005",name:"75kW以内柴油发电机组",specs:"75GFY-4",unit:"台班",type:"301"},
        {code:"8017006",name:"100kW以内柴油发电机组",specs:"90GFZ",unit:"台班",type:"301"},
        {code:"8017007",name:"120kW以内柴油发电机组",specs:"120GFY-4",unit:"台班",type:"301"},
        {code:"8017008",name:"160kW以内柴油发电机组",specs:"160GF",unit:"台班",type:"301"},
        {code:"8017009",name:"200kW以内柴油发电机组",specs:"200GF",unit:"台班",type:"301"},
        {code:"8017010",name:"250kW以内柴油发电机组",specs:"250GF4-4",unit:"台班",type:"301"},
        {code:"8017011",name:"320kW以内柴油发电机组",specs:"320GF-2",unit:"台班",type:"301"}
    ],
    initSpread:function () {
        if(this.spread) return this.spread.refresh();
        this.spread = SheetDataHelper.createNewSpread($("#electrovalence_sheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.spread);
        this.sheet = this.spread.getSheet(0);
        sheetCommonObj.initSheet(this.sheet, this.setting, 30);
        this.sheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onElectrovalenceSelectionChange);
        this.sheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onElectrovalenceValueChange);
        this.sheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onElectrovalenceEditStarting);
    /*
        ;*/
        this.sheet.name('electrovalence_sheet');
        if(projectReadOnly){
            disableSpread(this.spread);
        }
    },
    showDatas:function (datas) {
        let sel = this.sheet.getSelections()[0];
        let oldData = sel.row<this.datas.length?this.datas[sel.row]:"";
        this.sheet.setRowCount(0);
        this.datas = datas?datas:this.getElectrovalenceDatas();
        this.calcPertElectrovalenceMarketPrice(this.datas);
        sheetCommonObj.showData(this.sheet, this.setting,this.datas);
        this.sheet.setRowCount(this.datas.length+1);
        let nameCol = _.findIndex(this.setting.header,{'dataCode':'displayName'});
        let nameOptions = this.getElectrovalenceOptions();
        sheetCommonObj.setComboBox(-1,nameCol,this.sheet,nameOptions,false,false,5);
        sel.row =  oldData?_.findIndex(this.datas,{'ID':oldData.ID}):sel.row ;
        this.sheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
    },
    getElectrovalenceDatas:function (ext) {
        let datas = [];
        let pgljMap = {};
        let com_electrovalence = projectObj.project.projectGLJ.datas.com_electrovalence;
        for(let pg of projectObj.project.projectGLJ.datas.gljList){
            pgljMap[gljUtil.getIndex(pg)] = pg;
        }
        if(com_electrovalence && com_electrovalence.gljList){
            for (let g of com_electrovalence.gljList){
                let t = this.createNewElectrovalenceData(g);
                let tg = pgljMap[gljUtil.getIndex(g)];
                if(tg) gljOprObj.setGLJPrice(t,tg,false,ext);
                datas.push(t);
            }
        }
        return datas;
    },
    createNewElectrovalenceData:function (g) {//只是拷贝一份
        let t = {
            ID:g.ID,
            GLJID:g.GLJID,
            projectGLJID:g.projectGLJID,
            name:g.name,
            displayName:g.displayName,
            code:g.code,
            specs:g.specs,
            unit:g.unit,
            type:g.type,
            coe: g.coe,
            from:g.from
        };
        return t;
    },

    calcPertElectrovalenceMarketPrice:function (datas,ext) {
        let total = 0;
        for(let d of datas){
            if(ext && ext[d.projectGLJID] && gljUtil.isDef(ext[d.projectGLJID].marketPrice)) d.marketPrice = ext[d.projectGLJID].marketPrice;
            if(d.name == "电网电"){
                d.electPrice = d.marketPrice;
            }else {
                let w = parseInt(d.name);
                if(!w) continue;
                let t = scMathUtil.roundForObj(d.marketPrice/w,getDecimal("process"));
                d.electPrice = scMathUtil.roundForObj(t * gljUtil.getElecCoe(),getDecimal("glj.unitPriceHasMix"));
            }
            let et = scMathUtil.roundForObj(d.electPrice * d.coe,getDecimal("process"));
            total = scMathUtil.roundForObj(et + total,getDecimal("process"));
        }
        this.total = scMathUtil.roundForObj(total,getDecimal("glj.unitPriceHasMix"));
        $("#electrovalenceLabel").text(`综合电价：${this.total}`);
        return this.total;
    },
    clacNewElecPrice:function (ext) {
        for(let g of projectObj.project.projectGLJ.datas.gljList){
            if(g.code == gljUtil.getElecCode() && g.name == "电" && g.unit == "kW·h"){//更新电价
                let datas  = this.getElectrovalenceDatas(ext);
                if(datas.length > 0){
                    let marketPrice = this.calcPertElectrovalenceMarketPrice(datas,ext);
                    if(marketPrice && g.unit_price.market_price != marketPrice+'') return {projectGLJID:g.id,id:g.unit_price.id,'unit_price_file_id':g.unit_price.unit_price_file_id,doc:{'market_price':marketPrice+''}}
                }
            }
        }
        return null;
    },
    getElectrovalenceOptions:function () {
        return _.map(this.options,"name")
    },
    onElectrovalenceSelectionChange:function (sender,args) {
        args.sheet.repaint();
    },
    onElectrovalenceEditStarting:function (sender,args) {
        let me = electrovalenceObj;
        let dataCode = me.setting.header[args.col].dataCode;
        if(dataCode == "electPrice" ){//除电网电外，不可修改
            let cancel = true;
            if(me.datas[args.row] && me.datas[args.row].name == "电网电") cancel  = false;
            args.cancel = cancel;
        }
    },


    onElectrovalenceValueChange:function (sender,args) {
        let me = electrovalenceObj;
        let dataCode = me.setting.header[args.col].dataCode;
        let value = args.newValue;
        if(dataCode == "displayName" && args.row >= me.datas.length) {//新增
             me.addElectrovalence(value);
        }else { //修改
            let tem = me.datas[args.row];
            if (value&&!sheetCommonObj.checkData(args.col,me.setting,value)) {
                alert('输入的数据类型不对，请重新输入!');
                return  me.showDatas(me.datas);
            }
            if(dataCode == 'coe' || dataCode == 'electPrice'){
                let dec = dataCode == 'coe' ?getDecimal("process"):getDecimal("glj.unitPrice");
                if(value){
                    value = scMathUtil.roundForObj(value,dec);
                }
                tem[dataCode] = value;
                if(dataCode == 'electPrice') tem.marketPrice = value;
            }else if(dataCode == 'displayName'){//下拉替换
                me.editElectrovalence(value,args.row,"replace");
            }
            me.showDatas(me.datas);
        }
    },
    addElectrovalence:async function (name) {
        this.editElectrovalence(name);
    },
    editElectrovalence:async function (name,row,type="add") {
        //新建项目的时候，电已经默认生成了，所以不用考考虑电没有的情况
        try {
            let glj = _.find(this.options,{name:name});
            if(glj){
                let tem = {displayName:glj.name,code:glj.code,specs:glj.specs,unit:glj.unit,type:glj.type,projectID : projectObj.project.ID()};
                tem.ID = uuid.v1();
                $.bootstrapLoading.start();
                let result =  await ajaxPost('/glj/insertElectrovalence',tem);
                //插入项目工料机列表
                if(type == "add" && (!result.projetcGLJData || result.projetcGLJData.length == 0)){
                   alert("没有找到该工料机，请检查工料机库");
                   return  this.showDatas(this.datas);
                }
                let newProjectPGJ = projectObj.project.projectGLJ.loadNewProjectGLJToCache(result.projetcGLJData);
                //加入综合电价显示列表缓存
                tem.GLJID = result.projetcGLJData.glj_id;
                tem.projectGLJID = result.projetcGLJData.id;
                tem.name =  result.projetcGLJData.name;
                tem.coe = 0;
                tem.from = "std";
                gljOprObj.setGLJPrice(tem,newProjectPGJ);

                if(type == "add"){
                    this.datas.push(tem);
                }else { //除了添加的就是替换
                    if(this.datas[row])this.datas[row]=tem;
                }
                this.showDatas(this.datas);
            }
        }catch (e){
            console.log(e)
        }finally {
            //materialCalcObj.showDatas();
            $.bootstrapLoading.end();
        }
    },
    getGljListFromDatas:function (datas) {
        let gljList = [];
        for(let d of datas){
            gljList.push(this.createNewElectrovalenceData(d));
        }
        return gljList;
    },
    updateElectrovalence:function () {
        let updateMap = {};
        let dwd = null;//电网电
        let com_electrovalence = projectObj.project.projectGLJ.datas.com_electrovalence;
        if(com_electrovalence){//存在则是更新
            updateMap['electrovalence'] = {
                actionType:'update',
                ID:com_electrovalence.ID,
                doc:{gljList:this.getGljListFromDatas(this.datas)}
            };
        }else { //不存在则是新增
            updateMap['electrovalence'] = {
                actionType:'add',
                doc:{
                    unit_price_file_id:projectObj.project.property.unitPriceFile.id,
                    gljList:this.getGljListFromDatas(this.datas)
                }
            };
            updateMap['electrovalence']['doc'].ID = uuid.v1();
        }
        for(let t of this.datas){
            if(t.name == '电网电'){
                dwd = t;
            }
        }
        let unitPrices = [];
        for(let g of projectObj.project.projectGLJ.datas.gljList){
            if(dwd && g.id == dwd.projectGLJID){
                if(g.unit_price.market_price != dwd.electPrice+''){
                  let  t_unitPrice = {projectGLJID:g.id,id:g.unit_price.id,'unit_price_file_id':g.unit_price.unit_price_file_id,doc:{'market_price':dwd.electPrice+""}};
                    unitPrices.push(t_unitPrice);
                }
            }
            if(g.code == gljUtil.getElecCode() && g.name == "电" && g.unit == "kW·h"){//更新电价
                if(g.unit_price.market_price != this.total+''){
                    let  d_unitPrice = {projectGLJID:g.id,id:g.unit_price.id,'unit_price_file_id':g.unit_price.unit_price_file_id,doc:{'market_price':this.total+''}};
                    unitPrices.push(d_unitPrice);
                }
            }
        }
        if(unitPrices.length > 0)updateMap["unitPrice"] =  unitPrices;
        this.submitElectrovalenceChange(updateMap)
    },
    submitElectrovalenceChange:async function (updateMap) {
        try {
            if(!_.isEmpty(updateMap)){
                $.bootstrapLoading.start();
                let result =  await ajaxPost('/glj/updateElectrovalence',updateMap);
                projectObj.project.projectGLJ.refreshEctrovalenceCache(updateMap);
            }
        }catch (e){
            console.log(e)
        }finally {
            $.bootstrapLoading.end();
        }

    }


};

$(function () {

    $("#electrovalenceDiv").on('shown.bs.modal', function () {
        electrovalenceObj.initSpread();
        electrovalenceObj.showDatas();
    });

    $("#removeElectrovalencec").click(function(){
        let record = sheetCommonObj.getSelectedRecode(electrovalenceObj.sheet,electrovalenceObj.datas);
        if(record){
            _.remove(electrovalenceObj.datas,{'ID':record.ID});
            electrovalenceObj.showDatas(electrovalenceObj.datas);
        }
    });

    $("#electrovalencecConfirm").click(function () {
        electrovalenceObj.updateElectrovalence();
    })
});