package org.jeecg.modules.plan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.plan.entity.BuCheckPlan;
import org.jeecg.modules.plan.entity.BuCheckRecord;
import org.jeecg.modules.plan.modal.PlanStatistics;
import org.jeecg.modules.plan.service.IBuCheckPlanService;
import org.jeecg.modules.plan.service.IBuCheckRecordService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

 /**
 * @Description: 检查记录表
 * @Author:
 * @Date:   2020-12-14
 * @Version: V1.0
 */
@Api(tags="检查记录表")
@RestController
@RequestMapping("/plan/buCheckRecord")
@Slf4j
public class BuCheckRecordController extends JeecgController<BuCheckRecord, IBuCheckRecordService> {
	@Autowired
	private IBuCheckRecordService buCheckRecordService;
	@Autowired
	private IBuCheckPlanService buCheckPlanService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserDepartService sysUserDepartService;
	@Autowired
	private ISysDepartService sysDepartService;

	/**
	 * 分页列表查询
	 *
	 * @param buCheckRecord;
	 * @param pageNo;
	 * @param pageSize;
	 * @param req;
	 * @return
	 */
	@AutoLog(value = "检查记录表-分页列表查询")
	@ApiOperation(value="检查记录表-分页列表查询", notes="检查记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BuCheckRecord buCheckRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BuCheckRecord> queryWrapper = QueryGenerator.initQueryWrapper(buCheckRecord, req.getParameterMap());
		Page<BuCheckRecord> page = new Page<BuCheckRecord>(pageNo, pageSize);
		IPage<BuCheckRecord> pageList = buCheckRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/selectList")
	 public Result<?> selectList(@RequestParam(name="startDate", required = true) String startDate,
								 @RequestParam(name="endDate", required = true) String endDate) {
		BuCheckRecord buCheckRecord = buCheckRecordService.getDataByDate(startDate,endDate);
		return Result.OK(buCheckRecord);
	 }

	/**
	 *   添加
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "检查记录表-添加")
	@ApiOperation(value="检查记录表-添加", notes="检查记录表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BuCheckPlan buCheckPlan) throws ParseException {
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			SysUser userData = sysUserService.getUserByName(buCheckPlan.getPerformId());
		    SysUserDepart sysUserDepart = sysUserDepartService.getDepartByUser(userData.getId());

		if(buCheckPlan.getPlanType().equals("2")) {
			BuCheckRecord buCheckRecord = new BuCheckRecord();
			buCheckRecord.setPlanId(buCheckPlan.getPlanName());
			buCheckRecord.setPlanType(buCheckPlan.getPlanType());
			buCheckRecord.setDeviceId(buCheckPlan.getDeviceRange());
			buCheckRecord.setPlanCreateTime(new Date());
			buCheckRecord.setPlanStatus("1");
			buCheckRecord.setBeginTime(buCheckPlan.getStartTime());
			buCheckRecord.setPlanEndTime(buCheckPlan.getPlanEndTime());
			buCheckRecord.setInitiateId(user.getId());
			buCheckRecord.setCheckType(buCheckPlan.getCheckType());
			buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
			buCheckRecord.setCheckId(buCheckPlan.getPerformId());
			buCheckRecord.setOrgCode(sysUserDepart.getDepId());
			buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
			buCheckRecordService.save(buCheckRecord);
			buCheckPlanService.save(buCheckPlan);
		}else if(buCheckPlan.getPlanType().equals("1")){
			Calendar a = Calendar.getInstance();
			int month = a.get(Calendar.MONTH)+1;
			while (month<=12) {
				BuCheckRecord buCheckRecord = new BuCheckRecord();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				int year = a.get(Calendar.YEAR);
				Date startDate = sdf.parse(year +"-"+ month+"-01");
				buCheckRecord.setPlanId(buCheckPlan.getPlanName());
				buCheckRecord.setPlanType(buCheckPlan.getPlanType());
				buCheckRecord.setDeviceId(buCheckPlan.getDeviceRange());
				buCheckRecord.setPlanCreateTime(new Date());
				buCheckRecord.setPlanStatus("1");
				buCheckRecord.setBeginTime(startDate);
				buCheckRecord.setPlanEndTime(buCheckPlan.getPlanEndTime());
				buCheckRecord.setInitiateId(user.getId());
				buCheckRecord.setCheckType(buCheckPlan.getCheckType());
				buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
				buCheckRecord.setCheckId(buCheckPlan.getPerformId());
				buCheckRecord.setOrgCode(sysUserDepart.getDepId());
				buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
				buCheckRecordService.save(buCheckRecord);
				month=month + 1;
			}
			buCheckPlanService.save(buCheckPlan);
		}else if(buCheckPlan.getPlanType().equals("0")){

			Calendar b = Calendar.getInstance();
			b.set(Calendar.MONTH,11);
			b.set(Calendar.DAY_OF_MONTH,31);;
			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH)+1;
			int day = c.get(Calendar.DAY_OF_MONTH);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date startDate = sdf.parse(year+"-"+month+"-"+day);
			Date endDate = sdf.parse(year+"-12-31");
			b.setTime(endDate);
			c.setTime(startDate);
			while (c.compareTo(b)<=0) {
				BuCheckRecord buCheckRecord = new BuCheckRecord();
				buCheckRecord.setPlanId(buCheckPlan.getPlanName());
				buCheckRecord.setPlanType(buCheckPlan.getPlanType());
				buCheckRecord.setDeviceId(buCheckPlan.getDeviceRange());
				buCheckRecord.setPlanCreateTime(new Date());
				buCheckRecord.setPlanStatus("1");
				buCheckRecord.setBeginTime(c.getTime());
				buCheckRecord.setPlanEndTime(buCheckPlan.getPlanEndTime());
				buCheckRecord.setInitiateId(user.getId());
				buCheckRecord.setCheckType(buCheckPlan.getCheckType());
				buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
				buCheckRecord.setCheckId(buCheckPlan.getPerformId());
				buCheckRecord.setOrgCode(sysUserDepart.getDepId());
				buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
				buCheckRecordService.save(buCheckRecord);
				c.add(Calendar.DAY_OF_MONTH,1);
			}
			buCheckPlanService.save(buCheckPlan);
		}else{
			return Result.error("请选择计划类型");
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buCheckRecord
	 * @return
	 */
	@AutoLog(value = "检查记录表-编辑")
	@ApiOperation(value="检查记录表-编辑", notes="检查记录表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BuCheckRecord buCheckRecord) {
		buCheckRecordService.updateById(buCheckRecord);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  下发
	  *
	  * @param buCheckPlan
	  * @return
	  */
	 @AutoLog(value = "检查计划-下发")
	 @ApiOperation(value="检查计划-下发", notes="检查计划-下发")
	 @PutMapping(value = "/issue")
	 public Result<?> issue(@RequestBody BuCheckPlan buCheckPlan) {
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 SysUser userData = sysUserService.getUserByName(buCheckPlan.getPerformId());
		 SysUserDepart sysUserDepart = sysUserDepartService.getDepartByUser(userData.getId());
		 SysDepart sysDepart = sysDepartService.getDepartById(sysUserDepart.getDepId());
		 BuCheckRecord buCheckRecord =new BuCheckRecord();
			buCheckRecord.setPlanId(buCheckPlan.getPlanName());
			buCheckRecord.setPlanType(buCheckPlan.getPlanType());
			buCheckRecord.setDeviceId(buCheckPlan.getDeviceRange());
			buCheckRecord.setPlanCreateTime(new Date());
			buCheckRecord.setPlanStatus("1");
			buCheckRecord.setBeginTime(buCheckPlan.getStartTime());
			buCheckRecord.setPlanEndTime(buCheckPlan.getPlanEndTime());
		 	buCheckRecord.setInitiateId(user.getId());
		    buCheckRecord.setCheckType(buCheckPlan.getCheckType());
		    buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
		    buCheckRecord.setCheckId(buCheckPlan.getPerformId());
		    buCheckRecord.setOrgCode(sysDepart.getDepartName());
		    buCheckRecord.setPlanContent(buCheckPlan.getPlanContent());
			buCheckRecordService.save(buCheckRecord);

		 buCheckPlanService.updateById(buCheckPlan);
		 return Result.OK("下发成功!");
	 }

//	 /**
//	  *   派工
//	  *
//	  * @param
//	  * @return
//	  */
//	 @AutoLog(value = "检查记录表-派工")
//	 @ApiOperation(value = "检查记录表-派工", notes = "检查记录表-派工")
//	 @PutMapping(value = "/dispatch")

	 /**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检查记录表-通过id删除")
	@ApiOperation(value="检查记录表-通过id删除", notes="检查记录表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		buCheckRecordService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "检查记录表-批量删除")
	@ApiOperation(value="检查记录表-批量删除", notes="检查记录表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buCheckRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检查记录表-通过id查询")
	@ApiOperation(value="检查记录表-通过id查询", notes="检查记录表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BuCheckRecord buCheckRecord = buCheckRecordService.getById(id);
		if(buCheckRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buCheckRecord);
	}
	 // 检查计划（按年统计）
	 @GetMapping(value="/yearStatistics")
	 public Result<?> yearStatistics(){
		List<PlanStatistics> yearStatisticsList = buCheckRecordService.yearStatistics();
		return Result.OK(yearStatisticsList);
	 }
	 // 检查计划（按月统计）
	 @GetMapping(value="/monthStatistics")
	 public Result<?> monthStatistics(@RequestParam(name="queryYear",required = true) String queryYear){
		List<PlanStatistics> monthStatisticsList = buCheckRecordService.monthStatistics(queryYear);
		return Result.OK(monthStatisticsList);
	 }
	 // 检查计划（按工班统计）
	 @GetMapping(value="/workStatistics")
	 public Result<?> workStatistics(){
		List<PlanStatistics> workStatisticsList = buCheckRecordService.workStatistics();
		return Result.OK(workStatisticsList);
	 }


    /**
    * 导出excel
    *
    * @param request
    * @param buCheckRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuCheckRecord buCheckRecord) {
        return super.exportXls(request, buCheckRecord, BuCheckRecord.class, "检查记录表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BuCheckRecord.class);
    }

}
