package com.nantian.cloud.jljc.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.CcDirectVo;
import com.nantian.cloud.jljc.vo.CcFactorVo;
import com.nantian.sc.cloud.admin.api.entity.SysUser;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@RestController
@AllArgsConstructor
@RequestMapping("/ccFactor")
@Api(value = "ccFactor", tags = "直接排放因子")
@CrossOrigin
public class CcFactorController {

	private final CcFactorService ccFactorService;

	private final CcIndirectService ccIndirectService;

	private final CcDirectService ccDirectService;

	private final TReportService tReportService;

	private final TReportEnergysTructureService tReportEnergysTructureService;

	/**
	 * 查询
	 *
	 *
	 * @param ccFactor
	 * @return
	 */
	@GetMapping("/page")
	@SysLog("分页获取直接排放因子")
	@ApiOperation(value = "分页获取直接排放因子", notes = "分页获取直接排放因子")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "ccFactor", value = "直接排放因子对象", required = false, dataType = "json", paramType = "path")
	})
	public R getCcFactor(Page page, CcFactor ccFactor) {
		ccFactor.setDelFlag("1"); //筛选未删除项
		return R.ok(ccFactorService.getFactors());
		//return R.ok(ccFactorService.page(page, Wrappers.query(ccFactor)));
	}

	/**
	 * 修改
	 *
	 * @param ccFactor
	 * @return R
	 */
	@PutMapping
	@SysLog("修改直接排放因子")
	@ApiOperation(value = "修改直接排放因子", notes = "修改直接排放因子")
	@ApiImplicitParam(name = "ccFactor", value = "直接排放因子对象", required = true, dataType = "json", paramType = "path")
	public R updateById(@RequestBody CcFactor ccFactor) {
		ScUser u = SecurityUtils.getUser();
		ccFactor.setUserid(u.getId());
		ccFactor.setUpdateTime(new Date());
		return R.ok(ccFactorService.updateById(ccFactor));
	}


	/**
	 * 保存
	 *
	 * @param ccFactor
	 * @return R
	 */
	@PostMapping
	@SysLog("新增直接排放因子")
	@ApiOperation(value = "新增直接排放因子", notes = "新增直接排放因子")
	@ApiImplicitParam(name = "ccFactor", value = "直接排放因子对象", required = true, dataType = "json", paramType = "path")
	public R save(@RequestBody CcFactor ccFactor) {
		ScUser u = SecurityUtils.getUser();
		ccFactor.setUserid(u.getId());
		ccFactor.setDeptId(u.getDeptId());
		ccFactor.setDelFlag("1");
		ccFactor.setUpdateTime(new Date());
		return R.ok(ccFactorService.save(ccFactor));
	}


	/**
	 * 删除
	 *
	 * @param ccFactorId
	 * @return R
	 */
	@DeleteMapping("/{ccFactorId}")
	@SysLog("删除直接排放因子")
	@ApiOperation(value = "删除直接排放因子", notes = "删除直接排放因子")
	@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
	public R removeById(@PathVariable Integer ccFactorId) {
		CcFactor ccFactor = ccFactorService.getById(ccFactorId);
		if(ccFactor==null){
			return R.failed("该直接排放因子不存在，删除失败！");
		}
		ScUser u = SecurityUtils.getUser();
		ccFactor.setDelFlag("4");
		ccFactor.setUserid(u.getId());
		ccFactor.setUpdateTime(new Date());
		return R.ok(ccFactorService.updateById(ccFactor));
	}


	/**
	 * 分页查询碳排放情况
	 * @return
	 */
	@GetMapping("/co2/page")
	@SysLog("分页获取直接排放因子")
	@ApiOperation(value = "分页获取直接排放因子", notes = "分页获取直接排放因子")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "ccFactor", value = "直接排放因子对象", required = false, dataType = "json", paramType = "path")
	})
	public R getCo2Page(Page page, String cmpName,Integer year) {
		return R.ok(ccIndirectService.getAll(page,cmpName,year));  //添加数据权限
		//return R.ok(ccFactorService.page(page, Wrappers.query(ccFactor)));
	}



	/**
	 * 查询碳直接排放明细情况
	 * @return
	 */
	@GetMapping("/directco2")
	@SysLog("碳直接排放明细")
	@ApiOperation(value = "碳直接排放明细", notes = "碳直接排放明细")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "epc", value = "企业社会行用代码", required = false, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "year", value = "统计年", required = false, dataType = "String", paramType = "path")
	})
	public R getDirectCo2Page(String epc,Integer year) {
		return R.ok(ccDirectService.getAllByEpcYear(epc,year));
	}

	/**
	 * 生成统计数据
	 * @return
	 */
	@GetMapping("/dewlwithData")
	@SysLog("生成统计数据")
	@ApiOperation(value = "生成统计数据", notes = "生成统计数据")
	@ApiImplicitParams({})
	public R dewlwithData(Integer year) {
		TReport tReport=new TReport();
		tReport.setDelFlag("1");
		tReport.setAuditStatus("2");
		tReport.setYear(year);
		List<CcFactorVo> listFactor=ccFactorService.getFactors();  //添加数据权限

		deleteByYear(year);
		List<TReport> list=tReportService.list(Wrappers.query(tReport));
		for(TReport item:list){
			List<TReportEnergysTructure> list2=tReportEnergysTructureService.getTructureByReportId(item.getId());
			for(TReportEnergysTructure item2:list2){
				if (chooseFromList(listFactor,item2)){
					CcDirect cc=new CcDirect();
					cc.setYear(year);
					cc.setEnergyId(item2.getEnergyCode());
					cc.setEnergyValue(new BigDecimal(Double.toString(item2.getConsumeSum())));
					cc.setEnterpriseCode(item.getEnterpriseCode());

					ccDirectService.save(cc);
				}else{
					if (chooseAnother(item2)){
						dealWithInDirect(item2,year,item.getEnterpriseCode());
					}
				}
			}
		}
		totalDataByYear(year,listFactor);

		return R.ok("生成统计数据OK");
	}

	private void totalDataByYear(Integer year,List<CcFactorVo> listFactor){
		CcIndirect cc=new CcIndirect();
		cc.setYear(year);
		List<CcIndirect> list1=ccIndirectService.list(Wrappers.query(cc));
		for(CcIndirect item:list1){
			// 10000 * 千瓦时电量 * kg/kWh /1000 = 吨
			BigDecimal totalElict=item.getEltric().multiply(item.getElitricCo2()).multiply(new BigDecimal("10"));
			// 净购热力百万千焦 * tCo2/GJ
			BigDecimal totalHot=item.getHot().multiply(item.getHotCo2());
			item.setIndirectTotal(totalElict.add(totalHot));

			BigDecimal totalDirect=getTotalDirect(year,item,listFactor);
			item.setDirectTotal(totalDirect);

			ccIndirectService.updateById(item);
		}
	}

	private BigDecimal getTotalDirect(Integer year,CcIndirect item,List<CcFactorVo> listFactor){
		List<CcDirectVo> list=ccDirectService.getAllByEpcYear(item.getEnterpriseCode(),year);
		BigDecimal ret=new BigDecimal("0"),tmp;
		for(CcDirectVo cc:list){
			CcFactorVo vo=getFactor(listFactor,cc.getEnergyId());

			if (cc.getEnergyId().intValue()==15||
					cc.getEnergyId().intValue()==11||
					cc.getEnergyId().intValue()==12
			) {
				//气*10000 * kJ/m3   tC/TJ /1000000 = 吨
				tmp = vo.getHotValue().multiply(vo.getCcValue()).multiply(vo.getOfs()).multiply(new BigDecimal(cc.getEnergyValue())).divide(new BigDecimal("100"));
			}else{
				//固体*1000 * kJ/kg  tC/TJ /1000000 = 吨
				tmp = vo.getHotValue().multiply(vo.getCcValue()).multiply(vo.getOfs()).multiply(new BigDecimal(cc.getEnergyValue())).divide(new BigDecimal("1000"));
			}
			ret=tmp.add(ret);
		}
		return ret;
	}

	private CcFactorVo getFactor(List<CcFactorVo>  listFactor,Integer id){
		for (CcFactorVo item:listFactor){
			if (item.getEnergyId().equals(id)){
				return item;
			}
		}
		return null;
	}

	private void deleteByYear(Integer year){
		CcIndirect item=new CcIndirect();
		item.setYear(year);
		ccIndirectService.remove(Wrappers.query(item));

		CcDirect item2=new CcDirect();
		item2.setYear(year);
		ccDirectService.remove(Wrappers.query(item2));
	}

	private boolean chooseFromList(List<CcFactorVo> listFactor,TReportEnergysTructure item2){
		boolean flag=false;
		for(CcFactorVo item:listFactor){
			if (item.getEnergyId().equals(item2.getEnergyCode())){
				flag=true;
				break;
			}
		}
		return flag;
	}

	private boolean chooseAnother(TReportEnergysTructure item2){
		boolean flag=false;

		if (item2.getEnergyCode().intValue()==32||item2.getEnergyCode().intValue()==33){
			flag=true;
		}

		return flag;
	}

	private void dealWithInDirect(TReportEnergysTructure item2,Integer year,String epc){
		CcIndirect item=new CcIndirect();
		item.setYear(year);
		item.setEnterpriseCode(epc);
		CcIndirect cc=ccIndirectService.getOne(Wrappers.query(item));
		if (cc==null){
			if (item2.getEnergyCode().intValue()==32){
				item.setHot(new BigDecimal(Double.toString(item2.getConsumeSum())));
				item.setHotCo2(new BigDecimal("0.11"));//tCo2/GJ
			}else if (item2.getEnergyCode().intValue()==33){
				item.setEltric(new BigDecimal(Double.toString(item2.getConsumeSum())));
				item.setElitricCo2(new BigDecimal("0.5271"));//kg/kWh
			}
			ccIndirectService.save(item);
		}else{
			if (item2.getEnergyCode().intValue()==32){
				cc.setHot(new BigDecimal(Double.toString(item2.getConsumeSum())));
				cc.setHotCo2(new BigDecimal("0.11"));//tCo2/GJ
			}else if (item2.getEnergyCode().intValue()==33){
				cc.setEltric(new BigDecimal(Double.toString(item2.getConsumeSum())));
				cc.setElitricCo2(new BigDecimal("0.5271"));//kg/kWh
			}
			ccIndirectService.updateById(cc);
		}
	}
}
