package com.steerinfo.ems.emsprodplanmonth.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
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.service.IEmsProdplanRoundService;
import com.steerinfo.ems.trmworkproc.mapper.TRmWorkprocMapper;
import com.steerinfo.ems.trmworkproc.model.TRmWorkproc;
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 io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

    @Autowired
    private   IEmsProdplanMonthService emsProdplanMonthService;

    @Autowired
    private EmsProdplanMonthMapper emsProdplanMonthMapper;

    @Autowired
    private TRmWorkprocMapper tRmWorkprocMapper;

    @Autowired
    private IEmsProdplanRoundService emsProdplanRoundService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("emsprodplanmonth:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize) throws ParseException {
        if(parmas.containsKey("workprocid") && parmas.get("workprocid") != null && !"".equals(parmas.get("workprocid").toString())){
        String  workprocid =  parmas.get("workprocid").toString();
        if(!workprocid.startsWith(",")){
            workprocid = "'"+workprocid.replaceAll(",", "','").replaceAll("，", "','")+"'";
        }
            parmas.put("workprocid",workprocid);
        }
        parmas.put("startTime",parmas.get("startTime")+"-01");
        parmas.put("endTime",parmas.get("endTime").toString()+DateUtils.getDaysOfMonth(parmas.get("endTime").toString()));
        PageList<EmsProdplanMonth> list = emsProdplanMonthService.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("emsprodplanmonth:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<EmsProdplanMonth> list = emsProdplanMonthService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据EmsProdplanMonth对象创建")
    @ApiImplicitParam(name = "emsProdplanMonth", value = "详细实体emsProdplanMonth", required = true, dataType = "EmsProdplanMonth")
    //@RequiresPermissions("emsprodplanmonth:create")
    @PostMapping(value = "/", produces  = "application/json;charset=UTF-8")
    @Transactional
    public RESTfulResult add(@RequestBody EmsProdplanMonth[] models){
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i < models.length; i++) {
            EmsProdplanMonth model = models[i];
            model.setCreateman(userId);
            model.setCreatetime(new Date());
            Map map = new HashMap();
            map.put("may",new SimpleDateFormat("yyyy-MM-dd").format(model.getMay()));
            map.put("workprocid","'"+model.getWorkprocid()+"'");
            map.put("productid",model.getProductid());
            map.put("startTime",new SimpleDateFormat("yyyy-MM-dd").format(model.getMay()));
            map.put("endTime",new SimpleDateFormat("yyyy-MM-dd").format(model.getMay()));
            List list = emsProdplanMonthMapper.selectByParameters(map);
            if(list.size()>0){
                return failed(null,"该日数据已生成,无法再次生成");
            }
            EmsProdplanMonth maxSqno = emsProdplanMonthService.getMaxSqno();
            model.setSqno(maxSqno.getSqno());
            EmsProdplanMonth emsProdplanMonth = emsProdplanMonthService.add(model);
        }
        return success();
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("emsprodplanmonth:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        EmsProdplanMonth emsProdplanMonth = emsProdplanMonthService.getById(id);
        return success(emsProdplanMonth);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的emsProdplanMonth信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "emsProdplanMonth", value = "详细实体emsProdplanMonth", required = true, dataType = "EmsProdplanMonth")
    })
    //@RequiresPermissions("emsprodplanmonth:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody EmsProdplanMonth model){
        model.setId(id);
        EmsProdplanMonth emsProdplanMonth = emsProdplanMonthService.modify(model);
        return success(emsProdplanMonth);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @Transactional
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("emsprodplanmonth:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  emsProdplanMonthService.delete(ids);
    	}
      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("may")==null){
            return failed(null, "请选择生成时间");
        }
        else {
            String  may = (String) parmas.get("may");
            may = may.substring(0,7);
            may+="-01";
            parmas.put("may",may);
        }
        PageList<Map<String, Object>> list = emsProdplanMonthService.getDateEditForPage(parmas, pageNum, pageSize);
        if(list == null) {
            return failed(null, "日期格式有误");
        }
        return success(list);
    }

    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public  RESTfulResult batchupdate(@RequestBody EmsProdplanMonth [] models ){
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i< models.length; i++) {
            EmsProdplanMonth  model = models[i];
                if(model.getWeightDay() == null || model.getWeightMonth() == null){
                    return failed(null, "ID为‘"+model.getId()+"行年目标计划量或者日目标计划量为空");
                }
                if(model.getJxdays() == null ){
                    return  failed(null,"ID为‘"+model.getId()+"行请填写检修天数");
                }
                    model.setUpdatetime(new Date());
                    model.setUpdateman(userId);
                    emsProdplanMonthMapper.updateByPrimaryKey(model);
        }
                    return success();
    }
    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("emsprodplanyear:delete")
    @DeleteMapping(value = "/delete", produces  = "application/json;charset=UTF-8")//String
    public RESTfulResult delete(@RequestBody EmsProdplanMonth[] models){
        if(models.length >= 1) {
            for (int i = 0; i < models.length; i++) {
                EmsProdplanMonth m = models[i];
                if(m==null || m.getId() ==null || m.getId().isEmpty()){
                    return failed(null, "请传入数据ID");
                }
                Map map = new HashMap();
                map.put("parentid",m.getId());
                List query = emsProdplanRoundService.query(map);
                if(query.size()>0){
                    return  failed(null,"序号为'"+m.getSqno()+"'在当前月已有轮次计划,无法删除");
                }
                EmsProdplanMonth tv = emsProdplanMonthService.getById(m.getId());
                if (tv == null){
                    return failed(null, "数据已经删除，请重新查询数据");
                }

            }
        } else {
            return failed(null, "请输入要删除的数据");
        }
        for (int i = 0; i< models.length; i++) {
            emsProdplanMonthService.delete(models[i].getId());
        }
        return success();
    }
        @ApiOperation(value="查询", notes="获取指定工序列表")
        @GetMapping(value = "/getWorkprocs")
        public RESTfulResult getWorkprocs (){
            List<TRmWorkproc> tRmWorkprocs = tRmWorkprocMapper.queryPlanMoth();
            return success(tRmWorkprocs);
        }
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDates")
    public RESTfulResult getDates(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList dateLc = emsProdplanMonthService.getDateLc(parmas, pageNum, pageSize);
        return success(dateLc);
    }

}
