package com.steerinfo.ems.ifemsmesactitem.service.impl;

import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifemsmesactitem.mapper.IfEmsMesActitemMapper;
import com.steerinfo.ems.ifemsmesactitem.model.IfEmsMesActitem;
import com.steerinfo.ems.ifemsmesactitem.service.IIfEmsMesActitemService;
import com.steerinfo.ems.ifmesemsproductorder.service.impl.IfMesEmsProductorderServiceImpl;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmactvalue.mapper.TRmActValueMapper;
import com.steerinfo.ems.trmactvalue.model.TRmActValue;
import com.steerinfo.ems.trmactvalue.service.ITRmActValueService;
import com.steerinfo.ems.trmenergy.service.ITRmEnergyService;
import com.steerinfo.ems.trmenergyproperty.service.ITRmEnergyPropertyService;
import com.steerinfo.ems.trmunit.service.ITRmUnitService;
import com.steerinfo.ems.trmworkproc.model.TRmWorkproc;
import com.steerinfo.ems.trmworkproc.service.ITRmWorkprocService;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IfEmsMesActitem服务实现：
 * @author generator
 * @version 1.0-SNAPLong 2019-12-06 04:40
 * 类描述
 * 修订历史：
 * 日期：2019-12-06
 * 作者：generator
 * 参考：
 * 描述：IfEmsMesActitem服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "ifEmsMesActitemService")
public class IfEmsMesActitemServiceImpl extends BaseServiceImpl<IfEmsMesActitem, Long> implements IIfEmsMesActitemService {

    private static final Logger logger = LoggerFactory.getLogger(IfEmsMesActitemServiceImpl.class);
    @Autowired
    private IfEmsMesActitemMapper ifEmsMesActitemMapper;

    @Autowired
    private TRmActValueMapper tRmActValueMapper;

    @Autowired
    ITRmActValueService tRmActValueService;

    @Autowired
    ITRmEnergyService tRmEnergyService;

    @Autowired
    ITRmEnergyPropertyService tRmEnergyPropertyService;

    @Autowired
    ITRmWorkprocService tRmWorkprocService;

    @Autowired
    ITRmUnitService tRmUnitService;

    @Autowired
    IFormulaService formulaService;

    @Override
    protected IBaseMapper<IfEmsMesActitem, Long> getMapper() {
        return ifEmsMesActitemMapper;
    }

    /**
     * 获取主键流水
     * @return
     */
    public Long getId(){
        return ifEmsMesActitemMapper.getId();
    }

    /**
     * 获取数据到能耗实绩确认表
     * @param params
     * @return
     */
    public String getUploadData(){
        int addSize = 0;
        int updateSize = 0;
        int errorSize = 0;
        List<Map<String,Object>> rows = tRmActValueService.getUploadData();
        logger.info("获取生产计划数据条数：" + rows.size());
        for (int i = 0; i < rows.size();i++){
            try {
                IfEmsMesActitem model = new IfEmsMesActitem();
                model.setItemid(rows.get(i).get("ITEMID").toString());
                model.setItemname(rows.get(i).get("ITEMNAME").toString());
                if (rows.get(i).get("ITEMDESC") != null) {
                    model.setItemdesc(rows.get(i).get("ITEMDESC").toString());
                }
                String time = rows.get(i).get("CLOCK").toString();
                model.setClock(time);
                model.setTimegranid(rows.get(i).get("TIMEGRANID").toString());
                model.setWorkprocid(rows.get(i).get("WORKPROCID").toString());
                TRmWorkproc tRmWorkproc = tRmWorkprocService.getById(model.getWorkprocid());
                model.setWorkprocidName(tRmWorkproc.getName());
                model.setLine(tRmWorkproc.getBcode());
                model.setEnergyid(rows.get(i).get("ENERGYID").toString());
                model.setEnergyidName(tRmEnergyService.getById(model.getEnergyid()).getName());
                model.setPropertyid(rows.get(i).get("PROPERTYID").toString());
                model.setPropertyidName(tRmEnergyPropertyService.getById(model.getPropertyid()).getName());
                model.setUnitid(rows.get(i).get("UNITID").toString());
                model.setUnitidName(tRmUnitService.getById(model.getUnitid()).getName());
                model.setApportvalue(Double.parseDouble(rows.get(i).get("APPORTVALUE").toString()));
                Map<String, Object> param = new HashMap<>();
                param.put("paramkey", "ems_auto_upload");
                model.setState(this.selectParam(param).get(0).get("PARAM_VALUE").toString());
                if(!"YEAR".equalsIgnoreCase(model.getTimegranid())) {
                    Map<String, Object> param2 = new HashMap<>();
                    param2.put("clock", time.replaceAll("-", "").substring(0, 6));
                    param2.put("code", rows.get(i).get("ITEMID").toString());
                    param2.put("tablename", "T_RM_ACT_VALUE");
                    param2.put("isavailable", "1");
                    if (formulaService.getByParams(param2) == null) {
                        errorSize++;
                        param2.put("isavailable", "0");
                        if (formulaService.getByParams(param2) != null) {
                            logger.error("第" + i + "条能耗实绩数据的公式被禁用,主键：（itemid:" + rows.get(i).get("ITEMID").toString() + ",clock:" + rows.get(i).get("CLOCK").toString() + ",timegranid:" + rows.get(i).get("TIMEGRANID").toString() + ")");
                        } else {
                            logger.error("第" + i + "条能耗实绩数据的公式不存在,主键：（itemid:" + rows.get(i).get("ITEMID").toString() + ",clock:" + rows.get(i).get("CLOCK").toString() + ",timegranid:" + rows.get(i).get("TIMEGRANID").toString() + ")");
                        }
                    }
                    Formula formula = formulaService.getByParams(param2);
                    model.setFormula(formula.getSourcecode());
                    model.setFormuladescription(formulaService.anaFormula(formula));
                }
                if (ifEmsMesActitemMapper.updateUKey(model) == 0) {
                    model.setId(ifEmsMesActitemMapper.getId());
                    ifEmsMesActitemMapper.insert(model);
                    addSize++;
                } else {
                    model.setId(ifEmsMesActitemMapper.getDataByUKey(model).getId());
                    updateSize++;
                }
                TRmActValue updatefid = new TRmActValue();
                updatefid.setClock(model.getClock());
                updatefid.setTimegranid(model.getTimegranid());
                updatefid.setItemid(model.getItemid());
                updatefid.setFid(model.getId());
                tRmActValueMapper.updateFid(updatefid);
            }
            catch (Exception e){
                logger.error("第" + i + "条能耗实绩数据出现异常,主键：（itemid:" + rows.get(i).get("ITEMID").toString() + ",clock:" + rows.get(i).get("CLOCK").toString() + ",timegranid:" + rows.get(i).get("TIMEGRANID").toString() + "),错误原因：" + e);
                errorSize++;
            }
        }
        this.getindex();
        logger.info("本次总共新增能耗实绩数据条数：" + addSize);
        logger.info("本次总共更新能耗实绩数据条数：" + updateSize);
        logger.info("本次总共错误能耗实绩数据条数：" + errorSize);
        return "本次总共添加" + rows.size() + "条能耗实绩数据,其中更新" + updateSize + "条,新增" + addSize + "失败" + errorSize + "条。";
    }

    public PageList<Map<String, Object>> queryPage(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> rows = ifEmsMesActitemMapper.selectdataformula(parameters);
        for (int i = 0;i < rows.size();i++){
            Map<String, Object> param = rows.get(i);
            if(param.get("SOURCEID") == null || "".equals(param.get("SOURCEID"))){
                logger.error("id为" + param.get("id") + "的能耗数据没有公式");
                param.put("FORMULADESCRIPTION", "");
            }
            else {
                Formula formula = formulaService.getById(param.get("SOURCEID").toString());
                param.put("FORMULADESCRIPTION", formulaService.anaFormula(formula));
            }
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    public void updateState(IfEmsMesActitem model){
        model.setState("2");
        model.setMemo(null);
        model.setRectime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
        ifEmsMesActitemMapper.updateByPrimaryKeySelective(model);
    }
    public List<IfEmsMesActitem> getDatatoMes(){
        return this.ifEmsMesActitemMapper.getDatatoMes();
    }

    public void insertParam(Map<String, Object> param){
        ifEmsMesActitemMapper.insertParam(param);
    }

    public int updateParam(Map<String, Object> param){
        return ifEmsMesActitemMapper.updateParam(param);
    }
    public List<Map<String, Object>> selectParam(Map<String, Object> param){
        return ifEmsMesActitemMapper.selectParam(param);
    }

    public void getindex(){
        List<IfEmsMesActitem> list = ifEmsMesActitemMapper.getindex();
        for (int i = 0; i < list.size(); i++){
            ifEmsMesActitemMapper.updateByPrimaryKeySelective(list.get(i));
        }
    }
}
