package org.jeecg.modules.repair.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.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.modules.device.model.TimesStatistics;
import org.jeecg.modules.device.service.IBuDeviceLifeCircleService;
import org.jeecg.modules.plan.modal.PlanStatistics;
import org.jeecg.modules.plan.service.IBuCheckRecordService;
import org.jeecg.modules.repair.entity.BuRepairRecord;
import org.jeecg.modules.repair.model.YearFaultModel;
import org.jeecg.modules.repair.service.IBuRepairRecordService;
import org.jeecg.modules.sensor.model.TableNameStatistics;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
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.ArrayList;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 维修记录表
 * @Author: jeecg-boot
 * @Date:   2020-12-22
 * @Version: V1.0
 */
@Api(tags="维修记录表")
@RestController
@RequestMapping("/repair/buRepairRecord")
@Slf4j
public class BuRepairRecordController extends JeecgController<BuRepairRecord, IBuRepairRecordService> {
	@Autowired
	private IBuRepairRecordService buRepairRecordService;
	@Autowired
	private IBuCheckRecordService buCheckRecordService;
	@Autowired
	private IBuDeviceLifeCircleService buDeviceLifeCircleService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysUserService sysUserService;

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

	/**
	 *   添加
	 *
	 * @param buRepairRecord
	 * @return
	 */
	@AutoLog(value = "维修记录表-添加")
	@ApiOperation(value="维修记录表-添加", notes="维修记录表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BuRepairRecord buRepairRecord) {
//		System.out.println(buRepairRecord.getAssignerId());
		buRepairRecord.setRepairStatus("0");
		SysUser sysUser = sysUserService.getUserByName(buRepairRecord.getAssignerId());
		SysDepart sysDepart = sysDepartService.getDepartsByOrgCode(sysUser.getOrgCode());
		buRepairRecord.setOrgCode(sysDepart.getDepartName());
		buRepairRecordService.save(buRepairRecord);
		return Result.OK("添加成功！");
	}

	 /**
	  *   派工
	  *
	  * @param buRepairRecord
	  * @return
	  */
	 @AutoLog(value = "维修记录表-派工")
	 @ApiOperation(value="维修记录表-派工", notes="维修记录表-派工")
	 @PostMapping(value = "/dispatch")
	 public Result<?> dispatch(@RequestBody BuRepairRecord buRepairRecord) {
	 	if (buRepairRecord.getRepairStatus().equals("0")) {
//	 		if (oConvertUtils.isNotEmpty(buRepairRecord.getMaintainerId())){
//				SysUser sysUser = sysUserService.getUserByName(buRepairRecord.getAssignerId());
//				SysDepart sysDepart = sysDepartService.getDepartsByOrgCode(sysUser.getOrgCode());
//				buRepairRecord.setOrgCode(sysDepart.getDepartName());
//			}else{
//	 			return Result.error("无维修人信息");
//			}
			buRepairRecord.setRepairStatus("1");
			buRepairRecord.setAssignTime(new Date());
			buRepairRecordService.updateById(buRepairRecord);
			return Result.OK("派工成功!");
		}
	 	 else {
			 return Result.error("不是计划下发工单，无法派工");
		 }
	 }

	 /**
	  *   维修
	  *
	  * @param buRepairRecord
	  * @return
	  */
	 @AutoLog(value = "维修记录表-维修")
	 @ApiOperation(value="维修记录表-维修", notes="维修记录表-维修")
	 @PostMapping(value = "/repair")
	 public Result<?> repair(@RequestBody BuRepairRecord buRepairRecord){
	 	buRepairRecord.setRepairStatus("2");
	 	buRepairRecord.setStartTime(new Date());
	 	buRepairRecordService.updateById(buRepairRecord);
	 	return Result.OK("开始维修");
	 }


	/**
	 *  编辑
	 *
	 * @param buRepairRecord
	 * @return
	 */
	@AutoLog(value = "维修记录表-编辑")
	@ApiOperation(value="维修记录表-编辑", notes="维修记录表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BuRepairRecord buRepairRecord) {
		SysUser sysUser = sysUserService.getUserByName(buRepairRecord.getMaintainerId());
		SysDepart sysDepart = sysDepartService.getDepartsByOrgCode(sysUser.getOrgCode());
		buRepairRecord.setOrgName(sysDepart.getDepartName());
		buRepairRecord.setRepairStatus("4");
		buRepairRecordService.updateById(buRepairRecord);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过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) {
		buRepairRecordService.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.buRepairRecordService.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) {
		BuRepairRecord buRepairRecord = buRepairRecordService.getById(id);
		if(buRepairRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buRepairRecord);
	}
	 // 按年筛选故障数据
	 @GetMapping(value="/yearStatistics")
	 public Result<?> yearStatistics(){
		 List<PlanStatistics> yearStatisticsList = buRepairRecordService.yearStatistics();
		 return Result.OK(yearStatisticsList);
	 }
	// 按月筛选故障数据
	 @GetMapping(value="/monthStatistics")
	 public Result<?> monthStatistics(@RequestParam(name="queryYear",required = true) String queryYear){
		 List<PlanStatistics> monthStatisticsList = buRepairRecordService.monthStatistics(queryYear);
		 return Result.OK(monthStatisticsList);
	 }
	// 按工班筛选故障数据
	 @GetMapping(value="/workStatistics")
	 public Result<?> workStatistics(){
		 List<PlanStatistics> workStatisticsList = buRepairRecordService.workStatistics();
		 return Result.OK(workStatisticsList);
	 }
	 // 按故障种类筛选故障数据
	 @GetMapping(value="/gradeStatistics")
	 public Result<?> gradeStatistics(){
		 List<PlanStatistics> gradeStatisticsList = buRepairRecordService.gradeStatistics();
		 return Result.OK(gradeStatisticsList);
	 }
	 // 按故障系统筛选故障数据
	 @GetMapping(value="/systemStatistics")
	 public Result<?> systemStatistics(){
		 List<PlanStatistics> systemStatisticsList = buRepairRecordService.systemStatistics();
		 return Result.OK(systemStatisticsList);
	 }
	 // 按故障类型筛选故障数据
	 @GetMapping(value="/typeStatistics")
	 public Result<?> typeStatistics(){
		 List<PlanStatistics> typeStatisticsList = buRepairRecordService.typeStatistics();
		 return Result.OK(typeStatisticsList);
	 }

	 // 首页不同设备故障数据统计折线图
	 @PostMapping(value="/getDeviceRepair")
	 public Result<?> getDeviceRepair(){
		 List<String> result = new ArrayList<>();
		 for (int i = 1;i<13;i++){
		 	String str = String.valueOf(i);
			 result.add(str);
		 }
		 List<YearFaultModel> yearFaultModels = buRepairRecordService.getDeviceRepair(result);
		 return Result.OK(yearFaultModels);
	 }
	 // 获取所有设备名称首页折线
	 @GetMapping(value="/getDeviceName")
	 public Result<?> getDeviceName(){
		 List<TableNameStatistics> tableNameStatistics = buRepairRecordService.getDeviceName();
		 return Result.OK(tableNameStatistics);
	 }

	 // 当前设备最后一次维修信息
	 @GetMapping(value="/getEndRepair")
	 public Result<?> getEndRepair(@RequestParam(name="deviceId",required = true) String deviceId){
		 BuRepairRecord buRepairRecord = buRepairRecordService.getEndTimeByDeviceId(deviceId);
		 return Result.OK(buRepairRecord);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param buRepairRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuRepairRecord buRepairRecord) {
        return super.exportXls(request, buRepairRecord, BuRepairRecord.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, BuRepairRecord.class);
    }

    // 通过前端双击触发事件，根据设备id获取点检和维修的总次数
	 @GetMapping(value="/getTimes")
	 public Result<?> getTimes(@RequestParam(name="deviceId",required=true) String deviceId){
		 List<TimesStatistics> timesStatistics1 = buCheckRecordService.getTimesByDeviceId(deviceId);
		 List<TimesStatistics> timesStatistics2 = buRepairRecordService.getTimesByDeviceId(deviceId);
		 Map<Integer, TimesStatistics> timesStatistics2Map = timesStatistics2.stream().collect(Collectors.toMap(TimesStatistics::getMonth, timesStatistics -> timesStatistics));
		 timesStatistics1.forEach(item->{
			 item.setRepairTimes(timesStatistics2Map.get(item.getMonth()).getRepairTimes());
		 });

		 return Result.OK(timesStatistics1);
	 }

	 // 根据设备id获取故障次数，计算故障率返回
	 @GetMapping(value="/getFaultRate")
	 public Result<?> getFaultRate(@RequestParam(name="deviceId",required=true) String deviceId) throws ParseException {
		 int times = buRepairRecordService.getTimesById(deviceId);
		 String startTime = buDeviceLifeCircleService.getTimeByDeviceId(deviceId);
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Date nowDate = new Date();
		 Date oldDate = sdf.parse(startTime);
		 double day = (double)((nowDate.getTime() - oldDate.getTime())/1000/60/60/24);
		 double array = (double)times/day;
		 return Result.OK(array);
	 }


}
