package com.steerinfo.ems.emsprodplanyear.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.emsprodplanmonth.mapper.EmsProdplanMonthMapper;
import com.steerinfo.ems.emsprodplanmonth.model.EmsProdplanMonth;
import com.steerinfo.ems.emsprodplanmonth.service.IEmsProdplanMonthService;
import com.steerinfo.ems.emsprodplanyear.mapper.EmsProdplanYearMapper;
import com.steerinfo.ems.emsprodplanyear.model.EmsProdplanYear;
import com.steerinfo.ems.emsprodplanyear.service.IEmsProdplanYearService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    IEmsProdplanYearService emsProdplanYearService;

    @Autowired
   private  EmsProdplanYearMapper emsProdplanYearMapper;

    @Autowired
    private EmsProdplanMonthMapper emsProdplanMonthMapper;

    @Autowired
    private IEmsProdplanMonthService emsProdplanMonthService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })

    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<EmsProdplanYear> list = emsProdplanYearService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    /**
     * 根据前端传参，获取页面数据
     * @RequiresPermissions("emsprodplanyear:view")
     * @param parmas 参数列表
     * @param pageNum 开始页码
     * @param pageSize 一页多少
     * @return 返回一个带有分页信息的集合
     */
    @GetMapping(value = "/getList")
    public RESTfulResult getlist(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        // 因为页面产品/工序数量不同，所以获取;
        Integer parentNum = parmas.get("parentNum") == null ? 4: Integer.valueOf(parmas.get("parentNum").toString().trim());
        pageSize = pageSize * parentNum;
        PageList<EmsProdplanYear> list = emsProdplanYearService.queryForPage(parmas, pageNum, pageSize);
        // 根据月份汇总数据
        Map<String,List<EmsProdplanYear>> stringListMap =
                (HashMap<String, List<EmsProdplanYear>>) list.getList().stream().collect(
                Collectors.groupingBy(EmsProdplanYear::getYearmonth)
        );
        // HashMap无序，所以这里要转LinkedHashMap，并返回有序列表
        Map<String,List<EmsProdplanYear>> sortListMap = new LinkedHashMap<>();
        stringListMap.entrySet().stream().sorted(
                Map.Entry.comparingByKey()).forEachOrdered(x-> sortListMap.put(x.getKey(),x.getValue())
        );
        // 返回实际行数
        list.setTotal((long) Math.ceil(list.getTotal()/(double)parentNum));
        List mapList = new ArrayList<>();
        //数据，进行组装
        mapList.add(sortListMap);
        list.setList(mapList);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })

    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<EmsProdplanYear> list = emsProdplanYearService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据EmsProdplanYear对象创建")
    @ApiImplicitParam(name = "emsProdplanYear", value = "详细实体emsProdplanYear", required = true, dataType = "EmsProdplanYear")
    @PostMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult add(@RequestBody EmsProdplanYear[] models) throws ParseException {
        String userId = JwtUtil.getUseridByToken();
        Calendar c = Calendar.getInstance();
        for (int i = 0; i < models.length; i++) {
            EmsProdplanYear model = models[i];
            Boolean lineBool = (model.getLine() == null || model.getLine().equals(""))
                    && (model.getProductid() == null || model.getProductid().equals(""));
            if(lineBool){
                return  failed(null,"工序为空");
            }
            if(model.getYearmonth() == null){
                return  failed(null,"请选择时间");
            }
            if (model.getUnit() == null || model.getUnit().equals("")) {
                model.setUnit("吨");
            }
            Map map = new HashMap(16);
            map.put("line",model.getLine());
            map.put("yearmonth",new SimpleDateFormat("yyyy-MM").format(model.getYearmonth()));
            map.put("productid",model.getProductid());
            List list = emsProdplanYearService.getDateForProduct((HashMap<String, Object>) map);
            if (list.size()>0){
                return  failed(null,"该月时间段数据已生成,无法再次生成");
            }
            model.setCjr(userId);
            model.setCjsj(new Date());
            emsProdplanYearService.add(model);
            int dayMax = emsProdplanYearService.getDaysOfMonth(model.getYearmonth());
            Integer sumWeight = 0;
            EmsProdplanMonth maxSqno =  emsProdplanMonthService.getMaxSqno();
            String unit = "008";
            String productid = "";
            String workProcid = "";
            switch (model.getParentid()) {
                case "LG":
                    sumWeight = model.getWeight().intValue();
                    productid="钢坯";
                    unit="008";
                    workProcid = "AT2004";
                    break;
                case "LT":
                    sumWeight = model.getWeight().intValue();
                    productid="生铁";
                    unit="008";
                    break;
                case "SJ":
                    sumWeight = model.getWeight().intValue();
                    productid="烧结矿";
                    unit="008";
                    break;
                case "ZG" :
                    sumWeight = model.getWeight().intValue();
                    productid="线材";
                    if(model.getLine().equals("AT2007")) {
                        productid="H型钢";
                    }
                    unit="008";
                    break;
                case "FDC" :
                    sumWeight = model.getWeight().intValue();
                    productid="发电量";
                    unit="006";
                    break;
                case "JCS" :
                    sumWeight = model.getWeight().intValue();
                    productid="白灰";
                    unit="008";
                    break;
                case "JCW" :
                    sumWeight = model.getWeight().intValue();
                    productid="矿渣粉";
                    unit="008";
                    workProcid = model.getProductid();
                    break;
                case "JJZ" :
                    sumWeight = model.getWeight1().intValue() + model.getWeight2().intValue();
                    productid="焦炭";
                    unit="008";
                    workProcid = "AT1007";
                    break;
                case "JJF" :
                    sumWeight = model.getWeight().intValue();
                    productid="焦油";
                    if(model.getLine().equals("AT3009")){
                        productid="粗苯";
                    }
                    if(model.getLine().equals("AT3010")){
                        productid="硫铵";
                    }
                    unit="008";
                    //workProcid = "AT1007";
                    break;
                default: break;
            }
            int[] avgWeight = emsProdplanYearService.avgWeight(sumWeight,dayMax);
            for (int k = 0;k < dayMax;k++) {
                EmsProdplanMonth monModel = new EmsProdplanMonth();
                c.setTime(model.getYearmonth());
                c.add(Calendar.DATE, k);
                monModel.setMay(c.getTime());
                monModel.setUnit(unit);
                monModel.setProductid(productid);
                monModel.setWeightMonth(model.getWeight());
                if (workProcid.equals("")) {
                    monModel.setWorkprocid(model.getLine());
                } else {
                    monModel.setWorkprocid(workProcid);
                    monModel.setWeightMonth(BigDecimal.valueOf(sumWeight));
                }
                monModel.setWeightDay(BigDecimal.valueOf(avgWeight[k]));
                monModel.setKxf_weight(BigDecimal.valueOf(avgWeight[k]));
                monModel.setYxf_weight(BigDecimal.valueOf(0));
                monModel.setJxdays("0");
                monModel.setMemo("根据年计划，系统自动生成。");
                monModel.setCreateman("系统");
                monModel.setCreatetime(new Date());
                monModel.setSqno(maxSqno.getSqno()+k);
                Map monMap = new HashMap();
                monMap.put("may",new SimpleDateFormat("yyyy-MM-dd").format(monModel.getMay()));
                monMap.put("workprocid","'"+monModel.getWorkprocid()+"'");
                monMap.put("productid",monModel.getProductid());
                monMap.put("startTime",new SimpleDateFormat("yyyy-MM-dd").format(monModel.getMay()));
                monMap.put("endTime",new SimpleDateFormat("yyyy-MM-dd").format(monModel.getMay()));
                List<EmsProdplanMonth> monList = emsProdplanMonthMapper.selectByParameters(monMap);
                if(monList.size()<=0){
                    EmsProdplanMonth emsProdplanMonth = emsProdplanMonthService.add(monModel);
                } else {
                    if(model.getParentid().equals("LG") || model.getParentid().equals("JJZ")) {
                        monModel.setKxf_weight(monList.get(0).getKxf_weight().add(monModel.getKxf_weight()));
                        monModel.setWeightMonth(monList.get(0).getWeightMonth().add(monModel.getWeightMonth()));
                        monModel.setWeightDay(monList.get(0).getWeightDay().add(monModel.getWeightDay()));
                        monModel.setId(monList.get(0).getId());
                        emsProdplanMonthService.modify(monModel);
                    }
                }
            }
        }
        return success();
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")

    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        EmsProdplanYear emsProdplanYear = emsProdplanYearService.getById(id);
        return success(emsProdplanYear);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的emsProdplanYear信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "emsProdplanYear", value = "详细实体emsProdplanYear", required = true, dataType = "EmsProdplanYear")
    })

    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody EmsProdplanYear model){
        model.setId(id);
        EmsProdplanYear emsProdplanYear = emsProdplanYearService.modify(model);
        return success(emsProdplanYear);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")

    @DeleteMapping(value = "/delete", produces  = "application/json;charset=UTF-8")
    public RESTfulResult delete(@RequestBody EmsProdplanYear[] models){
        if(models.length >= 1) {
            for (int i = 0; i < models.length; i++) {
                EmsProdplanYear m = models[i];
                if(m==null || m.getNo() ==null || m.getNo().isEmpty()){
                    return failed(null, "请传入数据ID");
                }
                EmsProdplanYear tv = emsProdplanYearService.getById(m.getNo());
                if (tv == null){
                    return failed(null, "数据已经删除，请重新查询数据");
                }
            }
        } else {
            return failed(null, "请输入要删除的数据");
        }
        for (int i = 0; i< models.length; i++) {
            emsProdplanYearService.delete(models[i].getId());
        }
        return success();
    }
//   //年计划 炼钢厂获取编辑页面
//    @ApiOperation(value = "查询",notes = "根据时间来生成数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
//            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
//    })
//    @GetMapping(value = "/getDateEditForPage")
//    public RESTfulResult getDateEditForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
//            if(parmas.get("parentid") == null){
//            return failed(null, "请选择工序站所");
//        }
//        if(parmas.get("yearmonth")==null || parmas.get("yearmonth")==null){
//            return failed(null, "请选择生成时间");
//        }
//        try {
//            Date end = new SimpleDateFormat("yyyy-MM-dd").parse(parmas.get("jzsj").toString());
//            Date start = new SimpleDateFormat("yyyy-MM-dd").parse(parmas.get("cjsj").toString());
//            if ((end.getTime()-start.getTime()) / (24 * 60 * 60 * 1000) > 366){
//                return failed(null, "生成时间跨度不得超过1年");
//            }
//        } catch (ParseException e) {
//            return failed(null, "时间格式错误");
//        }
//        PageList<Map<String, Object>> list = emsProdplanYearService.getDateEditForPage(parmas, pageNum, pageSize);
//        if(list == null) {
//            return failed(null, "日期格式有误");
//        }
//        return success(list);
//    }

    @PutMapping(value = "/batchupdateList", produces  = "application/json;charset=UTF-8")
    public RESTfulResult updateList(@RequestBody EmsProdplanYear[] models) {
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i < models.length; i++) {
            EmsProdplanYear model = models[i];
            if (model.getNo() == null || model.getNo().equals("")) {
                return failed(null, "id为空");
            }
            if (model.getParentid() == null || model.getNo().equals("")) {
                return failed(null, "parentid为空");
            }
            // 因为一行数据由多条数据组成，所以这里为了确保数据准确性，应该再根据编号查询一次新的数据
            EmsProdplanYear emsProdplanYear = emsProdplanYearService.getById(model.getNo());
            emsProdplanYear.setWeight(model.getWeight());
            emsProdplanYear.setWeight1(model.getWeight1());
            emsProdplanYear.setWeight2(model.getWeight2());
            emsProdplanYear.setMemo(model.getMemo());
            emsProdplanYear.setXgr(userId);
            emsProdplanYear.setXgsj(new Date());
            emsProdplanYearMapper.updateByPrimaryKey(emsProdplanYear);
        }
        return success();
    }

    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody EmsProdplanYear[] models){
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i< models.length; i++) {
            EmsProdplanYear model = models[i];
            if(model.getNo() == null || model.getNo().equals("")) {
                return  failed(null,"id为空");
            }
            if(model.getParentid() == null || model.getNo().equals("")){
                return  failed(null,"parentid为空");
            }
            model.setXgr(userId);
            model.setXgsj(new Date());
            emsProdplanYearMapper.updateByPrimaryKey(model);
        }
//        if(!failmsg.isEmpty()){
//            return failed(null, "序号 [" + failmsg.substring(0, failmsg.length()-1) + "] 已审核，不允许修改");
//        }
//        for (int i = 0; i< models.length; i++) {
//            EmsProdplanYear model = models[i];
//            if(model.getCjsj() == null || model.getJzsj() == null){
//                return failed(null, "数据请传入时间");
//            }
//            if(model.getLine() == null || model.getLine().isEmpty()){
//                return failed(null, "数据请传入位置");
//            }
//            if(model.getWeight() == null || model.getWeight() == null){
//                return failed(null, "请填写完整数据");
//            }
//                String strDateFormat = "yyyy-MM-dd";
//                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
//                Map map =  new HashMap();
//                map.put("line",model.getLine());
//                map.put("cjsj",sdf.format(model.getCjsj()));
//                map.put("jzsj",sdf.format(model.getJzsj()));
//                EmsProdplanYear byId = emsProdplanYearService.getByParams(map);
//            if(model.getNo() != null && !model.getNo().equals("")){
//                model.setXgr(userId);
//                model.setXgsj(new Date());
//                emsProdplanYearMapper.updateByPrimaryKey(model);
//            }
//            else if(byId != null && byId.getZt().equals("1")){
//                return failed(null, ""+byId.getLine()+"在该期间数据已经生成，无法再次生成");
//            }
//            else  {
//                model.setCjr(userId);
//                model.setCjsj(new Date());
//                model.setZt("1");
//                model.setCjr(userId);
//                emsProdplanYearService.add(model);
//            }
//        }
        return success();
    }
}
