package com.steerinfo.ems.trmdfvalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.tcm035.model.TCm035;
import com.steerinfo.ems.trmactitem.mapper.TRmActItemMapper;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmdfvalue.mapper.TRmDfValueMapper;
import com.steerinfo.ems.trmdfvalue.model.TRmDfValue;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.ibatis.annotations.Delete;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * TRmDfValue RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-10-30 10:34
 * 类描述
 * 修订历史：
 * 日期：2020-10-30
 * 作者：generator
 * 参考：
 * 描述：TRmDfValue RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmdfvalues")
public class TRmDfValueController extends BaseRESTfulController {

    private static final Logger logger = LoggerFactory.getLogger(TRmDfValueController.class);

    /**
     * 文件保存路径
     */
    public static final String FILE_DIR = "/static/df/";

    @Autowired
    ITRmDfValueService tRmDfValueService;

    @Autowired
    ITRmActItemService tRmActItemService;

    @Autowired
    private TRmActItemMapper tRmActItemMapper;

    @Autowired
    private IFormulaService formulaService;
    @Autowired
    private TRmDfValueMapper tRmDfValueMapper;

    @ApiOperation(value = "获取列表", notes = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmdfvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageList<TRmDfValue> list = tRmDfValueService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "获取列表", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmdfvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageList<TRmDfValue> list = tRmDfValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "创建", notes = "根据TRmDfValue对象创建")
    @ApiImplicitParam(name = "tRmDfValue", value = "详细实体tRmDfValue", required = true, dataType = "TRmDfValue")
    //@RequiresPermissions("trmdfvalue:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmDfValue model) {
        TRmDfValue tRmDfValue = tRmDfValueService.add(model);
        return success(tRmDfValue);
    }

    @ApiOperation(value = "更新详细信息", notes = "根据url的id来指定更新对象，并根据传过来的TRmDfValue信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "TRmDfValue", value = "详细实体tRmDfValue", required = true, dataType = "TRmDfValue")
    })
    //@RequiresPermissions("trmactvalue:update")
    @PutMapping(value = "/batchUpdate", produces = "application/json;charset=UTF-8")
    public RESTfulResult batchUpdate(@RequestBody TRmDfValue[] models) {
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        for (int i = 0; i < models.length; i++) {
            TRmDfValue model = models[i];
            if (model.getApportwvalue() == null) {
                continue;
            }
            try {
                tRmDfValueService.modifyByApv(model);
                formulaService.reCalculate(model.getItemid(), model.getClock(), model.getTimegranid(), model.getClock());
            } catch (Exception e) {
                failnum++;
                failmsgs.add(model.getItemid());
                logger.error("数据修改出现错误,错误原因是" + e + ",id是" + model.getItemid());
            }
            if (failnum > 0) {
                logger.info("本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条");
                return success(failmsgs, "101", "本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条,失败的id:" + failmsgs.toString());
            }
        }
        return success();
    }

    @ApiOperation(value = "查询上报产量数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping("/getProjectwData")
    public RESTfulResult getProjectwData(@RequestParam HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        if (parmas.get("workprocid") != null && !parmas.get("workprocid").toString().isEmpty()) {
            String workprocid = parmas.get("workprocid").toString();
            if (!workprocid.startsWith("'")) {
                workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("workprocid", workprocid);
        }
        if (parmas.get("energyid") != null && !parmas.get("energyid").toString().isEmpty()) {
            String energyid = parmas.get("energyid").toString();
            if (!energyid.startsWith("'")) {
                energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
        if (parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()) {
            String propertyid = parmas.get("propertyid").toString();
            if (!propertyid.startsWith("'")) {
                propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
        if (parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())) {
            String itemid = parmas.get("itemid").toString();
            if (!itemid.startsWith("'")) {
                itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
        if (parmas.containsKey("startDate") && parmas.get("startDate") != null && !"".equals(parmas.get("startDate").toString()) &&
                parmas.containsKey("endDate") && parmas.get("endDate") != null && !"".equals(parmas.get("endDate").toString())) {
            String begin = parmas.get("startDate").toString();
            String end = parmas.get("endDate").toString();
            parmas.put("clock", begin);
            parmas.put("clocke", end);
        }
        PageList<Map<String, Object>> blist = tRmDfValueService.getProjectwDataForPage(parmas, pageNum, pageSize);
        return success(blist);
    }

    @ApiOperation(value = "批量重新计算", notes = "根据url的id来指定更新对象，并根据传过来的TRmDfValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmDfValue", value = "详细实体TRmDfValue", required = true, dataType = "TRmDfValue")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmDfValue[] model) {
        if (model.length < 1) {
            return failed(null, "请勾选数据");
        }
        for (int i = 0; i < model.length; i++) {
            HashMap<String,Object> id = new HashMap<String, Object>();
            id.put("itemid",model[i].getItemid());
            id.put("clock",model[i].getClock());
            id.put("timegranid",model[i].getTimegranid());
            TRmDfValue df = tRmDfValueMapper.selectByPrimaryKey(id);
            if (df!=null){
            	if(df.getApportwvalue()==null || df.getApportwvalue().intValue()==0){
            		tRmDfValueService.restatData(df.getItemid(), df.getClock(), df.getTimegranid(), JwtUtil.getUseridByToken(), null, "");
            	}else{
            		return failed(null, "财务最终值未清零则无法重新计算");
            	}
            }else{
            	return failed(null,"数据已不存在");
            }

        }
        return success();
    }

    @ApiOperation(value = "上传财务数据", notes = "根据excel文件上传数据")
    @ApiImplicitParam(name = "file", value = "excel文件", required = true, dataType = "file")
    //@RequiresPermissions("tcm035:update")
    @PutMapping(value = "/uploadExl")
    public RESTfulResult uploadExl(@ModelAttribute MultipartFile file) {
        try {
            // 上传文件
            if (file != null) {
                File dir = new File(FILE_DIR);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 上传文件名
                String fileName = file.getOriginalFilename();
                // 服务器端保存的文件对象
                File serverFile = new File(FILE_DIR, fileName);
                file.transferTo(serverFile);
                logger.info("上传excel财务数据，文件名：" + fileName + ",文件大小：" + serverFile.length() / 1024 + "KB");
                String res = tRmDfValueService.updateByExl(serverFile);
                if (!res.startsWith("2")) {
                    return failed(null, "更新财务上报数据失败：" + res);
                } else {
                    return success(res);
                }
            } else {
                return failed(null, "文件不存在");
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            return failed(null, "文件上传失败");
        } catch (IllegalStateException e) {
            logger.error(e.getMessage());
            return failed(null, "文件上传失败了");
        } catch (Exception e) {
            // e.printStackTrace();
            return failed(null, "数据上传失败：" + e.getMessage());
        }
    }

    @PutMapping(value = "/del")
    public RESTfulResult del(@RequestBody TRmDfValue[] model) {

        for (int i = 0; i < model.length; i++) {
                String Itemid = model[i].getItemid();
                String Clock = model[i].getClock();
                String Timegranid = model[i].getTimegranid();
                tRmDfValueService.delApportwvalue(Itemid, Clock, Timegranid);
            }
        return success();
    }

    @ApiOperation(value = "重新计算项目数据")
    @GetMapping(value = "/reData")
    public RESTfulResult reData(@RequestParam HashMap<String, Object> parmas, String clock,String clocke,String timegranid, String itemtype) {
        if (clock == null || clock.isEmpty()) {
            return failed(null, "请传入起始时间");
        }
        if (clocke == null || clocke.isEmpty()) {
            return failed(null, "请传入结束时间");
        }
        if (timegranid == null || timegranid.isEmpty()) {
            return failed(null, "请传入时间粒度");
        }
        if (itemtype == null || itemtype.isEmpty()) {
            return failed(null, "请传入项目类型");
        }
        if (parmas.get("workprocid") != null && !parmas.get("workprocid").toString().isEmpty()) {
            String workprocid = parmas.get("workprocid").toString();
            if (!workprocid.startsWith("'")) {
                workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("workprocid", workprocid);
        }
        if (parmas.get("energyid") != null && !parmas.get("energyid").toString().isEmpty()) {
            String energyid = parmas.get("energyid").toString();
            if (!energyid.startsWith("'")) {
                energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
        if (parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()) {
            String propertyid = parmas.get("propertyid").toString();
            if (!propertyid.startsWith("'")) {
                propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
        if (parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())) {
            String itemid = parmas.get("itemid").toString();
            if (!itemid.startsWith("'")) {
                itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
        String res = "";
        parmas.put("itemtype", itemtype);
        parmas.put("useflag", "1");
        // 查询需要统计的项目信息
        List<TRmDfValue> l = tRmDfValueMapper.selectLikeByParameters(parmas);
        int size = l.size();
        for (int i = 0; i < l.size(); i++) {
            if (res.isEmpty()) {
                //res = formulaService.reItemVal(l.get(i).getItemid(), clock, timegranid, clocke);
                 tRmDfValueService.restatData(l.get(i).getItemid(), clock, timegranid,JwtUtil.getUseridByToken(), null, "");
            } else {
               // formulaService.reItemVal(l.get(i).getItemid(), clock, timegranid, clocke);
               tRmDfValueService.restatData(l.get(i).getItemid(), clock, timegranid,JwtUtil.getUseridByToken(), null, "");
            }
            logger.info("剩下要处理的项目数：" + (size - 1 - i) + "(" + size + ")");
        }
        if (!res.isEmpty()) {
            return success(null, res);
        }
        return success();
    }
}
