package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.EnterpriseInfoService;
import com.nantian.cloud.jljc.service.TReportEnergyProjectService;
import com.nantian.cloud.jljc.service.TReportEnterpriseService;
import com.nantian.cloud.jljc.service.TReportService;
import com.nantian.cloud.jljc.vo.TReportEnergyJsonVo;
import com.nantian.cloud.jljc.vo.TReportEnergyQuery;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 报表1-5项目表
 * @date 2020-09-16
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportEnergyProject")
@Api(value = "tReportEnergyProject", tags = "报表1-5项目表")
public class TReportEnergyProjectController {

    final private TReportService tReportService;
    final private TReportEnergyProjectService tReportEnergyProjectService;
    final private TReportEnterpriseService tReportEnterpriseService;
    final private EnterpriseInfoService enterpriseInfoService;


    /**
     * 初始化报表1-5项目表的能源列表（企业端）
     */
    @GetMapping("/initializeEnergy")
    @SysLog("初始化报表1-5项目表的能源列表（企业端）")
    @ApiOperation(value = "初始化报表1-5项目表的能源列表（企业端）", notes = "初始化报表1-5项目表的能源列表（企业端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "string", paramType = "path")
    })
    public R initialize(String year,String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("查询失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        String energyInfoStr = tReportEnterpriseService.getEnergyInfo(enterpriseCode, year);
        if (energyInfoStr == null) {
            return R.ok();
        } else { //json转换
            List<EnergyInfo> energyInfoList = (List<EnergyInfo>) JSONArray.parseArray(energyInfoStr, EnergyInfo.class);
            List<TReportEnergyJsonVo> energyJsonVoList =  new ArrayList<>();
            for (EnergyInfo energyInfo : energyInfoList) {
                if("true".equals(energyInfo.getCompBuyEnergy())||"true".equals(energyInfo.getProcessEnergy())||"true".equals(energyInfo.getCraftEnergy())){
                    TReportEnergyJsonVo reportEnergyJsonVo = new TReportEnergyJsonVo();
                    reportEnergyJsonVo.setEnergyName(energyInfo.getEnergyName());
                    reportEnergyJsonVo.setNum("0");
                    reportEnergyJsonVo.setUnit(energyInfo.getUnit());
                    if(energyInfo.getEquivalentMarks()!=null){
                        reportEnergyJsonVo.setEquivalentMarks(energyInfo.getEquivalentMarks());
                    }else{
                        //企业没有设置折标系数，就用参考的折标系数
                        reportEnergyJsonVo.setEquivalentMarks(energyInfo.getEqualModulus());
                    }
                    energyJsonVoList.add(reportEnergyJsonVo);
                }
            }
            return R.ok(energyJsonVoList);
        }
    }


    /**
     *  节能减排项目管理分页查询
     *
     * @param page      分页对象
     * @param tReportEnergyQuery  节能减排项目管理
     * @return
     */
    @SysLog("查询节能减排项目管理（带数据权限）")
    @ApiOperation(value = "查询 节能减排项目管理（带数据权限）",notes = "条件查询 节能减排项目管理（带数据权限）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "TReportEnergyQuery", value = " 节能减排项目管理", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    @GetMapping("/queryList")
    public R queryList(Page page, TReportEnergyQuery tReportEnergyQuery) {
        //tReportEnergyProject.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportEnergyProjectService.getPageScope(page,tReportEnergyProject));
        if(null==tReportEnergyQuery.getModelYear()){
            return R.ok(null,"查询条件年度不能为空，请检查！");
        }
        return R.ok(tReportEnergyProjectService.queryList(page, tReportEnergyQuery));
    }

    /**
     * 通过年份查询报表1-5节能减排项目管理
     */
    @GetMapping("/getByYear")
    @SysLog("通过年份查询报表1-5节能减排项目管理")
    @ApiOperation(value = "通过年份查询报表1-5节能减排项目管理", notes = "通过年份查询报表1-5节能减排项目管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
    })
    public R getByYear(String year,String enterpriseCode, Page page) {
        if (year == null || "".equals(year)) {
            return R.failed("查询节能改造项目情况表失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("查询节能改造项目情况表失败，企业社会信用编码不能为空");
        }
        //获取能源报表信息
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "5");
        if (report == null) {
            return R.ok();
        }
        //获取节能减排项目信息
        /*TReportEnergyProject tReportEnergyProject  = new TReportEnergyProject();
        tReportEnergyProject.setReportId(report.getId());
        tReportEnergyProject.setDelFlag("1");
        List<TReportEnergyProject> list = tReportEnergyProjectService.list( Wrappers.query(tReportEnergyProject));*/
        //IPage<TReportEnergyProject> list = tReportEnergyProjectService.getProjectByReportId( page, report.getId());
        //return R.ok(list);
        TReportEnergyQuery tReportEnergyQuery  = new TReportEnergyQuery();
        tReportEnergyQuery.setReportId(report.getId());
        tReportEnergyQuery.setModelYear(Integer.parseInt(year));
        //return R.ok(tReportEnergyProjectService.queryList(page, tReportEnergyQuery));
        return R.ok(tReportEnergyProjectService.getByYear(page, tReportEnergyQuery));
    }
    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param tReportEnergyProject 报表1-5项目表
     * @return
     */
    @SysLog("查询报表1-5项目表")
    @ApiOperation(value = "查询报表1-5项目表",notes = "条件查询报表1-5项目表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tReportEnergyProject", value = "报表1-5项目表", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    @GetMapping("/page")
    public R getcheckGaugesPage(Page page, TReportEnergyProject tReportEnergyProject) {
        tReportEnergyProject.setDelFlag("1"); //查询未删除数据
        //return R.ok(tReportEnergyProjectService.getPageScope(page,tReportEnergyProject));
        return R.ok(tReportEnergyProjectService.page(page, Wrappers.query(tReportEnergyProject)));
    }


    /**
     * 信息
     *
     * @param tReportEnergyProjectId
     * @return R
     */
    @SysLog("通过ID查询报表1-5项目表")
    @ApiOperation(value = "通过ID查询报表1-5项目表",notes = "通过ID查询报表1-5项目表")
    @ApiImplicitParam(name ="tReportEnergyProjectId",value = "报表1-5项目表id",required = true,paramType = "path",dataType = "int")
    @GetMapping("/{tReportEnergyProjectId}")
    public R getById(@PathVariable("tReportEnergyProjectId") Integer tReportEnergyProjectId) {
        return R.ok(tReportEnergyProjectService.getById(tReportEnergyProjectId));
    }

    /**
     * 保存
     *
     * @param s
     * @return R
     */
    @SysLog("保存报表1-5项目表")
    @ApiOperation(value = "保存报表1-5项目表",notes = "新增报表1-5项目表")
    @ApiImplicitParam(name ="s",value = "报表1-5项目表",required = true,dataType = "json",paramType = "path")
    @PostMapping("/save")
    @Transactional
    public R save(@RequestBody String s) {
        JSONObject json = JSONObject.parseObject(s);
        TReport tReport = JSONObject.parseObject(json.getString("report"),TReport.class);
        TReportEnergyProject tReportEnergyProject= JSONObject.parseObject(json.getString("energyProject"),TReportEnergyProject.class);
        if(tReport==null || tReport.getYear()==null){
            return R.failed("报表年度不能为空，请检查！");
        }
        /*if(StringUtils.isBlank(tReport.getEnterpriseCode())){
            return R.failed("报表企业代码不能为空，请检查！");
        }*/
        ScUser u= SecurityUtils.getUser();
        if(u.getId()!=null){
            tReportEnergyProject.setUserid(u.getId());
        }
        //tReportEnergyProject.setDeptId(u.getDeptId());
        String enterpriseCode = StringUtils.isNotEmpty(tReport.getEnterpriseCode()) ? tReport.getEnterpriseCode() : u.getEnterpriseCode();
        //获取企业信息
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(enterpriseCode);
        //企业端新增信息，添加deptid
        tReportEnergyProject.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        tReportEnergyProject.setDelFlag("1");
        tReportEnergyProject.setUpdateTime(new Date());
        TReport q=new TReport();
        q.setEnterpriseCode(enterpriseCode);
        q.setYear(tReport.getYear());
        q.setType("5");
        q.setDelFlag("1");
        TReport o = tReportService.getOne(Wrappers.query(q));
        if(o!=null){
            tReport.setId(o.getId());
            tReportEnergyProject.setReportId(o.getId());
        }else {
            tReport.setType("5");
            tReport.setEnterpriseCode(enterpriseCode);
        }
        tReport.setUpdateTime(new Date());
        tReport.setReportStatus("2");
        Integer deptId = info != null && info.getRegionCode()!=null? Integer.parseInt(info.getRegionCode()) : u.getDeptId();
        tReport.setDeptId(deptId);
        if("530000".equals(deptId.toString())){ //企业区域直属省级
            tReport.setProvStatus("1"); //企业所填报表，省级可直接查看、审核
        }
        tReportService.saveOrUpdate(tReport);
        if(o==null){
            //TReport n = tReportService.getOne(Wrappers.query(tReport));
            tReportEnergyProject.setReportId(tReport.getId());
        }

        //return R.ok(tReportEnergyProjectService.saveOrUpdate(tReportEnergyProject));
        boolean update = tReportEnergyProjectService.saveOrUpdate(tReportEnergyProject);
        if (update) {
            //只有报表5更新成功，才能更新报表信息
            //return R.ok(tReportService.saveOrUpdate(tReport));
            return R.ok();
        }else{
            return R.failed();
        }
    }

    /**
     * 企业端预览报表1-5项目表
     */
    @GetMapping("/preview")
    @SysLog("企业端预览报表1-5项目表")
    @ApiOperation(value = "企业端预览报表1-5项目表", notes = "企业端预览报表1-5项目表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R getByReportId(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("预览报表1-5项目表失败，年度不能为空");
        }
        if (StringUtils.isEmpty(enterpriseCode)) {
            enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
        }
        return previewReport(year, enterpriseCode);
    }

    /**
     * 政府端预览报表1-5项目表
     */
    @GetMapping("/previewGov")
    @SysLog("政府端预览报表1-5项目表")
    @ApiOperation(value = "政府端预览报表1-5项目表", notes = "政府端预览报表1-5项目表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
    })
    public R getByReportIdGov(String year, String enterpriseCode) {
        if (year == null || "".equals(year)) {
            return R.failed("预览报表1-5项目表失败，年度不能为空");
        }
        if (enterpriseCode == null || "".equals(enterpriseCode)) {
            return R.failed("预览报表1-5项目表失败，企业社会信用编码不能为空");
        }
        return previewReport(year, enterpriseCode);
    }

    /**
     * 预览报表1-5项目表
     */
    private R previewReport(String year, String enterpriseCode) {

        //获取能源报表信息
        TReport report = tReportService.getInfoByType(enterpriseCode, year, "5");
        if(report==null){
            return R.ok();
        }

        //获取企业信息
        TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);

        //获取项目表信息
        TReportEnergyProject tReportEnergyProject  = new TReportEnergyProject();
        tReportEnergyProject.setReportId(report.getId());
        tReportEnergyProject.setDelFlag("1");
        List<TReportEnergyProject> projectList = tReportEnergyProjectService.list(Wrappers.query(tReportEnergyProject));

        Map<String, Object> map = new HashMap();
        map.put("enterprise", enterprise);
        map.put("report", report);
        map.put("project", projectList);

        return R.ok(map);
    }

    /**
     * 上传
     *
     * @param tReport
     * @return R
     */
    @SysLog("上报报表1-5项目表")
    @ApiOperation(value = "上报报表1-5项目表",notes = "上报报表1-5项目表")
    @ApiImplicitParam(name ="tReport",value = "报表1-5项目表",required = true,dataType = "json",paramType = "path")
    @PostMapping("/submit")
    public R submit(@RequestBody TReport tReport) {
        if(tReport.getYear()==null){
            return R.failed("报表年度不能为空，请检查！");
        }
        ScUser u= SecurityUtils.getUser();
        String enterpriseCode = StringUtils.isEmpty(tReport.getEnterpriseCode()) ? u.getEnterpriseCode() : tReport.getEnterpriseCode();

        TReport q=new TReport();
        q.setEnterpriseCode(enterpriseCode);
        q.setYear(tReport.getYear());
        q.setType("5");
        q.setDelFlag("1");
        TReport o = tReportService.getOne(Wrappers.query(q));
        if(o==null){
            tReport.setDeptId(u.getDeptId());
            tReport.setDelFlag("1");
            tReport.setType("5");
            tReport.setEnterpriseCode(u.getEnterpriseCode());
            if (tReport.getDate()==null || "".equals(tReport.getDate())){
                tReport.setDate(new Date());
            }
        }else {
            tReport.setId(o.getId());
        }
        tReport.setAuditStatus("1");
        tReport.setAuditStatus2("1");
        tReport.setAuditStatus3("1");
        tReport.setUpdateTime(new Date());
        tReport.setReportStatus("3");
        return R.ok(tReportService.saveOrUpdate(tReport));
    }

    /**
     * 修改
     *
     * @param tReportEnergyProject
     * @return R
     */
    @SysLog("修改报表1-5项目表信息")
    @ApiOperation(value = "修改报表1-5项目表信息",notes = "修改报表1-5项目表信息")
    @ApiImplicitParam(name ="tReportEnergyProject",value = "报表1-5项目表",required = true,dataType = "json",paramType = "path")
    @PutMapping
    public R updateById(@RequestBody TReportEnergyProject tReportEnergyProject) {
        ScUser u= SecurityUtils.getUser();
        if(u.getId()!=null){
            tReportEnergyProject.setUserid(u.getId());
        }
        tReportEnergyProject.setUpdateTime(new Date());
        return R.ok(tReportEnergyProjectService.updateById(tReportEnergyProject));
    }

    /**
     * 删除
     *
     * @param tReportEnergyProjectId
     * @return R
     */
    @SysLog("删除报表1-5项目表")
    @ApiOperation(value = "删除报表1-5项目表",notes = "删除报表1-5项目表信息")
    @ApiImplicitParam(name ="tReportEnergyProjectId",value = "报表1-5项目表信息ID",required = true,dataType = "int",paramType = "path")
    @DeleteMapping("/{tReportEnergyProjectId}")
    public R removeById(@PathVariable("tReportEnergyProjectId") Long tReportEnergyProjectId) {
        TReportEnergyProject tReportEnergyProject = tReportEnergyProjectService.getById(tReportEnergyProjectId);
        ScUser u= SecurityUtils.getUser();
        if(u.getId()!=null){
            tReportEnergyProject.setUserid(u.getId());
        }
        tReportEnergyProject.setDelFlag("4");
        tReportEnergyProject.setUpdateTime(new Date());
        return R.ok(tReportEnergyProjectService.updateById(tReportEnergyProject));
    }
    @ApiOperation(value = "能源项目类型",notes = "能源项目类型")
    @GetMapping("/projectTypeList")
    public R projectTypeList(){
        return R.ok(tReportEnergyProjectService.getProjectTypeList());
    }


}