package com.yeejoin.equipmanage.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 com.yeejoin.equipmanage.common.dto.WlCarMileageDto;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.entity.dto.CarTravelDto;
import com.yeejoin.equipmanage.common.utils.NameUtils;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.utils.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 车量里程表
 *
 * @author duanwei
 * @date 2023-02-01
 */
@RestController
@Api(tags = "车量里程表Api")
@RequestMapping(value = "/wl-car-mileage", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WlCarMileageController {

	@Autowired
	IWlCarMileageService iWlCarMileageService;

	/**
	 * 新增车量里程表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增车量里程表", notes = "新增车量里程表")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public boolean saveWlCarMileage(HttpServletRequest request, @RequestBody WlCarMileage wlCarMileage) {
		return iWlCarMileageService.save(wlCarMileage);
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public boolean deleteById(HttpServletRequest request, @PathVariable Long id) {
		return iWlCarMileageService.removeById(id);
	}

	/**
	 * 修改车量里程表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "修改车量里程表", notes = "修改车量里程表")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public boolean updateByIdWlCarMileage(HttpServletRequest request, @RequestBody WlCarMileage wlCarMileage) {
		return iWlCarMileageService.updateById(wlCarMileage);
	}

	/**
	 * 根据id查询
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public WlCarMileage selectById(HttpServletRequest request, @PathVariable Long id) {
		return iWlCarMileageService.getById(id);
	}

	/**
	 * 列表分页查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public IPage<WlCarMileage> listPage(String pageNum, String pageSize, WlCarMileage wlCarMileage) {
		Page<WlCarMileage> pageBean;
		QueryWrapper<WlCarMileage> wlCarMileageQueryWrapper = new QueryWrapper<>();
		Class<? extends WlCarMileage> aClass = wlCarMileage.getClass();
		Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
			try {
				field.setAccessible(true);
				Object o = field.get(wlCarMileage);
				if (o != null) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(wlCarMileage);
						wlCarMileageQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Long.class)) {
						Long fileValue = (Long) field.get(wlCarMileage);
						wlCarMileageQueryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(wlCarMileage);
						wlCarMileageQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Date.class)) {
						Date fileValue = (Date) field.get(wlCarMileage);
						wlCarMileageQueryWrapper.eq(name, fileValue);
					} else {
						String fileValue = (String) field.get(wlCarMileage);
						wlCarMileageQueryWrapper.eq(name, fileValue);
					}
				}
			} catch (Exception e) {
			}
		});
		IPage<WlCarMileage> page;
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = iWlCarMileageService.page(pageBean, wlCarMileageQueryWrapper);
		return page;
	}

	/**
	 * 列表分页查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public CarTravelDto page(Integer pageNum, Integer pageSize, WlCarMileage wlCarMileage) {
		Page<WlCarMileage> pageBean;
		if (pageNum == null || pageSize == null) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(pageNum, pageSize);
		}
		//只查询已完成的轨迹
		wlCarMileage.setComplete(true);
		Page<WlCarMileage> page = iWlCarMileageService.page(pageBean, wlCarMileage);

		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
		CarTravelDto carTravelDto = new CarTravelDto();
		carTravelDto.setTotal(page.getTotal());
		long totalTime = 0;
		double totalTravel = 0;
		List<WlCarMileageDto> list = new ArrayList<WlCarMileageDto>();
		for (WlCarMileage wl : page.getRecords()) {
			WlCarMileageDto wlCarMileageDto = new WlCarMileageDto();
			wl.setTime(millisToStringShort(wl.getTakeTime()));
			totalTravel += wl.getTravel();
			totalTime += wl.getTakeTime();
			BeanUtil.copyPropertiesIgnoreNull(wl, wlCarMileageDto);
			wlCarMileageDto.setStartTime(sdf.format(wl.getStartTime()));
			wlCarMileageDto.setEndTime(sdf.format(wl.getEndTime()));
			list.add(wlCarMileageDto);
		}
		carTravelDto.setRecords(list);
//		// 初始化format格式
//		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//		// 设置时区，跳过此步骤会默认设置为"GMT+08:00" 得到的结果会多出来8个小时
//		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
//
//		String timeStr = dateFormat.format(totalTime);
		carTravelDto.setTotalTime(millisToStringShort(totalTime));
		BigDecimal two = BigDecimal.valueOf(totalTravel);
		double result = two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		carTravelDto.setTotalTravel(result);
		return carTravelDto;
	}

	public String millisToStringShort(long millis) {
		StringBuffer strBuilder = new StringBuffer();
		long temp = millis;
		long hper = 60 * 60 * 1000;
		long mper = 60 * 1000;
		long sper = 1000;
		if (temp / hper > 0) {
			if ((temp / hper) < 10) {
				strBuilder.append(0);
			}
			strBuilder.append(temp / hper).append(":");
		} else {
			strBuilder.append("00").append(":");
		}
		temp = temp % hper;
		if (temp / mper > 0) {
			if ((temp / mper) < 10) {
				strBuilder.append(0);
			}
			strBuilder.append(temp / mper).append(":");
		} else {
			strBuilder.append("00").append(":");
		}
		temp = temp % mper;
		if (temp / sper > 0) {
			if ((temp / sper) < 10) {
				strBuilder.append(0);
			}
			strBuilder.append(temp / sper);
		} else {
			strBuilder.append("00");
		}
		return strBuilder.toString();

	}

	/**
	 * 获取轨迹
	 * 
	 * @return
	 */
	@RequestMapping(value = "/travel", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取轨迹", notes = "获取轨迹")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public List<Coordinate> travel(long id) {
		return iWlCarMileageService.getCoordinateList(id);
	}

	/**
	 * 获取日历
	 *
	 * @return
	 */
	@RequestMapping(value = "/calendar", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取日历", notes = "获取日历")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public Map<String, Boolean> calendar(@RequestParam("id") long id,
										 @DateTimeFormat(pattern = "yyyy-MM") @RequestParam("date") Date date) {
		return iWlCarMileageService.getCalender(id, date);
	}


	/**
	 * 里程切分
	 */
	@RequestMapping(value = "/mileageSegmentation", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "里程切分", notes = "里程切分")
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	public void mileageSegmentation() {
		 iWlCarMileageService.mileageSegmentation();
	}


}
