package com.steerinfo.ems.emsprodplanround.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.emsgmpcjh.mapper.EmsGmPcJhMapper;
import com.steerinfo.ems.emsgmpcjh.model.EmsGmPcJh;
import com.steerinfo.ems.emslog.mapper.EmsLogMapper;
import com.steerinfo.ems.emslog.model.EmsLog;
import com.steerinfo.ems.emslog.service.IEmsLogService;
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.emsprodplanround.mapper.EmsProdplanRoundMapper;
import com.steerinfo.ems.emsprodplanweightadjustment.model.EmsProdplanWeightAdjustment;
import com.steerinfo.ems.emsprodplanyear.model.EmsProdplanYear;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.ems.emsprodplanround.model.EmsProdplanRound;
import com.steerinfo.ems.emsprodplanround.service.IEmsProdplanRoundService;
import com.steerinfo.framework.utils.misc.IdGenerator;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.ant.taskdefs.Get;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    IEmsProdplanRoundService emsProdplanRoundService;
    @Autowired
    EmsGmPcJhMapper emsGmPcJhMapper;
    @Autowired
    EmsProdplanRoundMapper emsProdplanRoundMapper;
    @Autowired
    IEmsProdplanMonthService emsProdplanMonthService;
    @Autowired
    IEmsLogService emsLogService;
    @Autowired
    IdGenerator idGenerator;
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("emsprodplanround:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<EmsProdplanRound> list = emsProdplanRoundService.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("emsprodplanround:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<EmsProdplanRound> list = emsProdplanRoundService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据EmsProdplanRound对象创建")
    @ApiImplicitParam(name = "emsProdplanRound", value = "详细实体emsProdplanRound", required = true, dataType = "EmsProdplanRound")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody EmsProdplanRound [] models){
        String userId = JwtUtil.getUseridByToken();
        String maxid = null;
        for (EmsProdplanRound model : models) {
            if (model.getParentid() == null ){
                return failed(null,"请点击选择左边计划!!!");
            }
            EmsGmPcJh emsGmPcJh = emsGmPcJhMapper.selectByPrimaryKey(model.getParentid());
            if(emsGmPcJh.getState().equals("0")){
                return failed(null,"排产计划编号为"+emsGmPcJh.getId()+"做了取消下发操作，无法做新增操作");
            }
            if(model.getWorkprocType() == null || model.getWorkprocType().equals("")){
                return  failed(null,"工序或者时间为空");
            }
            if (model.getParentid().substring(0,1).equals("G")){
                maxid = emsProdplanRoundService.getMaxidAsGm(model);
                model.setAscription("0");
            }
            else {
                maxid = emsProdplanRoundService.getMaxidAsSC(model);
                model.setAscription("1");
            }
            model.setId(maxid);
            model.setPlanWeight(model.getPlanWeight());
            model.setMsgFlag("I");
            model.setReadFlag("N");
            model.setState("0");
            model.setCreatetime(new Date());
            model.setCreateman(userId);
            model.setWorkprocType(model.getWorkprocType());
            emsProdplanRoundService.add(model);
            emsGmPcJh.setState("3");
            emsGmPcJh.setReceiveTime(new Date());
            emsGmPcJhMapper.updateByPrimaryKeySelective(emsGmPcJh);
        }
        return success();
    }
//    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
//    public  RESTfulResult batchupdate(@RequestBody EmsProdplanRound [] models ){
//        String userId = JwtUtil.getUseridByToken();
//        for (int i = 0; i < models.length; i++) {
//            EmsProdplanRound  model = models[i];
//            HashMap<String,Object> map =  new HashMap();
//            String strDateFormat = "yyyy-MM";
//            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
//            map.put("id",model.getParentid());
//            map.put("may",sdf.format(model.getMay()));
//            EmsProdplanMonth emsProdplanMonth = emsProdplanMonthMapper.getBymayAndWorkprocid(map);
//            Long weightMonth = emsProdplanMonth.getWeightMonth();
//            Long kxf_weight = emsProdplanMonth.getKxf_weight();
//            Long yxf_weight = emsProdplanMonth.getYxf_weight();
//            yxf_weight = model.getPlanWeight()+yxf_weight;
//            kxf_weight = weightMonth-yxf_weight;
//            if(yxf_weight>weightMonth){
//                return  failed(null,"可下发重量不足");
//            }
//            emsProdplanMonth.setKxf_weight(kxf_weight);
//            emsProdplanMonth.setYxf_weight(yxf_weight);
//            emsProdplanMonthMapper.updateByPrimaryKey(emsProdplanMonth);
//            emsProdplanRoundMapper.updateByPrimaryKey(model);
//        }
//        return  success();
//    }
    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("emsprodplanround:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        EmsProdplanRound emsProdplanRound = emsProdplanRoundService.getById(id);
        return success(emsProdplanRound);
    }

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

    @PutMapping(value = "batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody EmsProdplanRound[] models){
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound  model = models[i];
            if(model.getState().equals("1") || model.getState().equals("2")){
                return failed(null,"存在已经下发或者审核的计划,无法做修改");
            }
            model.setUpdateman(userId);
            model.setUpdatetime(new Date());
            emsProdplanRoundMapper.updateByPrimaryKey(model);
         }
        return  success();
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的emsProdplanRound信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "emsProdplanRound", value = "详细实体emsProdplanRound", required = true, dataType = "EmsProdplanRound")
    })
    //@RequiresPermissions("emsprodplanround:update")
    @PutMapping(value = "ForcedUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult ForcedUpdate(@RequestBody EmsProdplanRound[] models) {
        String userId = JwtUtil.getUseridByToken();
        EmsLog emsLog =  new EmsLog();
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound  model = models[i];
            model.setUpdateman(userId);
            model.setUpdatetime(new Date());
            String str = "{修改前的数据为:"+emsProdplanRoundMapper.selectByPrimaryKey(model.getId())+"修改后的数据为:"+model+"}";
            emsProdplanRoundMapper.updateByPrimaryKey(model);
            emsLog.setCode(str);
            emsLog.setOperator(userId);
            emsLog.setUpdatetable("ems_prodplan_round");
            emsLog.setOperatortime(new Date());
            emsLog.setId(idGenerator.getNextStr());
            emsLogService.add(emsLog);
        }
           return  success();
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("emsprodplanround:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id ,@RequestBody EmsProdplanRound[] models){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  emsProdplanRoundService.delete(ids);
    	}
      return success();
    }
    @ApiOperation(value="下发", notes="根据models修改对象")
    @ApiImplicitParam(name = "emsProdplanRounds", value = "", required = true, dataType = "EmsProdplanRounds")
    @PostMapping(value = "/issue")
    @Transactional
    public RESTfulResult issue(@RequestBody EmsProdplanRound [] models){
        List id = new ArrayList();
        String monthid = "";
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound model = models[i];
            id.add(model.getId());
            monthid = model.getParentid();
            model.setIssuedTime(new Date());
            if(model.getState().equals("1")){
                return  failed(null,"存在已下发的计划,无法再次做下发");
            }
            if (model.getState().equals("3")) {
                return  failed(null,"存在审核不通过的计划, 无法下发");
            }
            model.setState("1");
            emsProdplanRoundMapper.updateByPrimaryKey(model);
        }
        EmsProdplanRound sumPlanWeight = emsProdplanRoundService.getSumPlanWeight(id);
        EmsGmPcJh emsGmPcJh = emsGmPcJhMapper.selectByPrimaryKey(monthid);
        emsGmPcJh.setKxfWeight(emsGmPcJh.getPlanWeight().subtract(emsGmPcJh.getYxfWeight().add(sumPlanWeight.getPlanWeight())));
        emsGmPcJh.setYxfWeight(emsGmPcJh.getYxfWeight().add(sumPlanWeight.getPlanWeight()));
        emsGmPcJhMapper.updateByPrimaryKey(emsGmPcJh);
        return  success();
    }
    @ApiOperation(value="取消下发", notes="根据models修改对象")
    @ApiImplicitParam(name = "emsProdplanRounds", value = "", required = true, dataType = "EmsProdplanRounds")
    @PostMapping(value = "/offissue")
    @Transactional
    public RESTfulResult offissue(@RequestBody EmsProdplanRound [] models){
        List id = new ArrayList();
        String monthid = "";
        String state  ="";
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound model = models[i];
            id.add(model.getId());
            monthid = model.getParentid();
            model.setIssuedTime(new Date());
            if(model.getState().equals("0")){
                return  failed(null,"没有下发过的轮次计划无法做取消下发操作");
            }
            EmsProdplanRound emsProdplanRound = emsProdplanRoundMapper.selectByPrimaryKey(model.getId());
            if(emsProdplanRound.getState().equals("2")){
                return failed(null,"存在已经接收的计划,无法做取消下发操作,请重新刷新页面");
            }
            model.setState("0");
            emsProdplanRoundMapper.updateByPrimaryKey(model);
        }
        EmsProdplanRound sumPlanWeight = emsProdplanRoundService.getSumPlanWeight(id);
        EmsGmPcJh emsGmPcJh = emsGmPcJhMapper.selectByPrimaryKey(monthid);
        // 取消下发操作
        emsGmPcJh.setKxfWeight(emsGmPcJh.getKxfWeight().add(sumPlanWeight.getPlanWeight()));
        emsGmPcJh.setYxfWeight(emsGmPcJh.getYxfWeight().subtract(sumPlanWeight.getPlanWeight()));
        emsGmPcJhMapper.updateByPrimaryKey(emsGmPcJh);
        return  success();
    }


    @ApiImplicitParam(name = "emsProdplanRounds", value = "", required = true, dataType = "EmsProdplanRounds")
    @PostMapping(value = "/delete")
    public RESTfulResult delete(@RequestBody EmsProdplanRound [] models){
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound model = models[i];
            if (model.getState().equals("1") || model.getState().equals("2")) {
                return failed(null, "数据已下发或者被接收，无法删除");
            }
             emsProdplanRoundMapper.deleteByPrimaryKey(model.getId());
             updateNbjh(model);
        }
        return  success();
    }

    @ApiOperation(value="获取详细信息", notes="根据url获取长度*宽度")
    @GetMapping(value = "getbasespecbillet")
    public RESTfulResult getlengthTimesWidth(){
        List<EmsProdplanRound> emsProdplanRounds = emsProdplanRoundService.getbasespecbillet();
        return success(emsProdplanRounds);
    }

    @ApiOperation(value="获取详细信息", notes="根据url获取断面")
    @GetMapping(value = "getiateralArea")
    public RESTfulResult getiateralArea(){
        List<EmsProdplanRound> emsProdplanRounds = emsProdplanRoundService.getiateralArea();
        return success(emsProdplanRounds);
    }

    @ApiOperation(value="获取详细信息", notes="根据url获取截取面积")
    @GetMapping(value = "getdimension")
    public RESTfulResult getdimension(){
        List<EmsProdplanRound> emsProdplanRounds = emsProdplanRoundService.getdimension();
        return success(emsProdplanRounds);
    }

    @ApiOperation(value="获取详细信息", notes="根据url获取断面")
    @GetMapping(value = "getsurfaceStandard")
    public RESTfulResult getsurfaceStandard(){
        List<EmsProdplanRound> emsProdplanRounds = emsProdplanRoundService.getsurfaceStandard();
        return success(emsProdplanRounds);
    }

    public void updateNbjh(EmsProdplanRound emsProdplanRound) {
            if (emsProdplanRound.getParentid() != null || !emsProdplanRound.getParentid().equals("")) {
                Map<String,Object> map =  new HashMap();
                map.put("parentid",emsProdplanRound.getParentid());
                List list = emsProdplanRoundMapper.selectByParameters(map);
                if (list.size()<1) {
                    EmsGmPcJh emsGmPcJh = emsGmPcJhMapper.selectByPrimaryKey(emsProdplanRound.getParentid());
                     emsGmPcJh.setState("2");
                     emsGmPcJhMapper.updateByPrimaryKeySelective(emsGmPcJh);
                }
            }
    }


    @ApiOperation(value="获取列表", notes="审核页面分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("emsprodplanround:view")
    @GetMapping(value = "/getAuditDate")
    //获取未审核的数据
    public RESTfulResult getAuditDateForPage (@RequestParam HashMap parmas,Integer pageNum, Integer pageSize) {
        PageList list = emsProdplanRoundService.getAuditDateForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="审核页面修改")
    @PutMapping(value = "updateAuditState", produces  = "application/json;charset=UTF-8")
    public RESTfulResult updateAuditState(@RequestBody EmsProdplanRound[] models){
        for (int i = 0; i < models.length; i++) {
            EmsProdplanRound  model = models[i];
            if(model.getState().equals("2")){
                return failed(null,"操作失败,存在已经下发或者接收的计划");
            }
            EmsProdplanRound emsProdplanRound = emsProdplanRoundMapper.selectByPrimaryKey(model.getId());
            if (emsProdplanRound.getAuditState().equals("1")){
                return failed(null,"编号为"+model.getId()+"已经再审核中,请勿重复操作");
            }
            if (emsProdplanRound.getAuditState().equals("2")){
                return  failed(null,"编号为"+model.getId()+"已经审核通过,请勿重复操作");
            }
            if(emsProdplanRound.getAuditState().equals("3")){
                return failed(null,"编号为"+model.getId()+"审核失败,请勿重复操作");
            }
            model.setAuditState("1");
             emsProdplanRoundService.updateAuditState(model);
        }
            return  success();
    }
    @ApiOperation(value="修改列表", notes="审核页面修改")
    @PutMapping(value = "updateAudit", produces  = "application/json;charset=UTF-8")
    public RESTfulResult updateAudit(@RequestBody EmsProdplanRound[] models){
        for (EmsProdplanRound model : models) {
            if (model.getState().equals("2")) {
                return failed("操作失败，编号为"+model.getId()+"已经接收");
            }
            emsProdplanRoundService.updateAuditState(model);
        }
        return success();
    }
    @ApiOperation(value="获取子节点", notes="销售订单重量调整")
    @GetMapping(value = "/getRounds")
    public RESTfulResult getRounds(@RequestParam HashMap parmas){
        EmsProdplanRound emsProdplanRound =  new EmsProdplanRound();
        emsProdplanRound.setParentid(parmas.get("parentid").toString());
        List<EmsProdplanRound> rounds = emsProdplanRoundService.getRounds(emsProdplanRound);
        Map<String,List<EmsProdplanRound>> stringListMap =
                (HashMap<String, List<EmsProdplanRound>>) rounds.stream().collect(
                        Collectors.groupingBy(EmsProdplanRound::getParentid)
                );
        List mapList = new ArrayList<>();
        //数据，进行组装
        mapList.add(stringListMap);
        return success(mapList);
    }

    @PutMapping(value = "/addSave", produces  = "application/json;charset=UTF-8")
    public RESTfulResult addSave(@RequestBody EmsProdplanRound model){
       if (model.getId() != null ) {
           EmsProdplanRound emsProdplanRound = emsProdplanRoundMapper.selectByPrimaryKey(model.getId());
            emsProdplanRound.setPlanWeight(model.getPlanWeight());
            emsProdplanRoundMapper.updateByPrimaryKey(emsProdplanRound);
            return success();
       }
       return failed();
    }
    @GetMapping("getstdchem")
    public RESTfulResult getstdchem(){
        List<EmsProdplanRound> emsProdplanRounds = emsProdplanRoundService.getchemicalStandard();
        return success(emsProdplanRounds);
    }

}
