package com.ruoyi.web.controller.oa;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.oa.domain.CmcCarApproval;
import com.ruoyi.oa.service.ICmcCarApprovalService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.oa.domain.CmcCar;
import com.ruoyi.oa.service.ICmcCarService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc车辆信息Controller
 *
 * @author cmc
 * @date 2024-02-23
 */
@RestController
@RequestMapping("/oa/car")
public class CmcCarController extends BaseController
{
    @Autowired
    private ICmcCarService cmcCarService;

    @Autowired
    private ICmcCarApprovalService cmcCarApprovalService;

    /**
     * 查询cmc车辆信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcCar cmcCar)
    {
        startPage();
        List<CmcCar> list = cmcCarService.selectCmcCarList(cmcCar);
        return getDataTable(list);
    }

    /**
     * 导出cmc车辆信息列表
     */
    @Log(title = "cmc车辆信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcCar cmcCar)
    {
        List<CmcCar> list = cmcCarService.selectCmcCarList(cmcCar);
        ExcelUtil<CmcCar> util = new ExcelUtil<CmcCar>(CmcCar.class);
        util.exportExcel(response, list, "cmc车辆信息数据");
    }

    /**
     * 获取cmc车辆信息详细信息
     */
    @GetMapping(value = "/{carId}")
    public AjaxResult getInfo(@PathVariable("carId") Integer carId)
    {
        return success(cmcCarService.selectCmcCarByCarId(carId));
    }

    /**
     * 获取设备统计信息
     */
    @GetMapping(value = "/statistic")
    public AjaxResult getCarStatistic(CmcCarApproval cmcCarApproval) throws ParseException
    {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearArray = new JSONArray();
        JSONObject yearObject = new JSONObject();
        JSONArray statusArray = new JSONArray();
        JSONObject statusObject = new JSONObject();
        JSONArray usageArray = new JSONArray();
        JSONObject usageObject = new JSONObject();
        JSONArray approvalArray = new JSONArray();
        JSONArray dayArray = new JSONArray();
        JSONArray monthArray = new JSONArray();
        JSONObject monthObject = new JSONObject();
        CmcCar cmcCar = new CmcCar();
        cmcCar.setIsRent("0");
        cmcCar.setStatus("0");
        statusObject.put("已派出", cmcCarService.selectCmcCarList(cmcCar).size());
        cmcCar.setStatus("1");
        statusObject.put("可使用", cmcCarService.selectCmcCarList(cmcCar).size());
        cmcCar.setStatus("2");
        statusObject.put("维修中", cmcCarService.selectCmcCarList(cmcCar).size());
//        cmcCar.setStatus("3");
//        statusObject.put("已还车", cmcCarService.selectCmcCarList(cmcCar).size());
        cmcCar.setStatus("4");
        statusObject.put("已报废", cmcCarService.selectCmcCarList(cmcCar).size());
        //整体
        if (cmcCarApproval.getApplyDate() == null) {
            //每年派车次数
            for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                //总数
                cmcCarApproval.setApplyDate(new SimpleDateFormat("yyyy").parse(String.valueOf(i)));
                List<CmcCarApproval> yearList = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
                yearObject.put(String.valueOf(i), yearList.size());
                getCarUsageStatistic(cmcCarApproval, usageObject);
            }
            cmcCarApproval.setApplyDate(null);
        }
        //年度
        else {
            String yearStr = new SimpleDateFormat("yyyy").format(cmcCarApproval.getApplyDate());
            //输入年份派车次数
            cmcCarApproval.setApplyDate(new SimpleDateFormat("yyyy").parse(yearStr));
            List<CmcCarApproval> yearList = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
            yearObject.put(yearStr, yearList.size());
            
            //月度统计
            for (int i = 1; i <= 12; i++) {
                String monthStr = String.format("%02d", i);
                String monthKey = yearStr + "-" + monthStr;
                String beginTimeString = monthKey + "-01";
                
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTimeString + " 00:00:00");
                cmcCarApproval.setParams(params);
                cmcCarApproval.setApplyDate(new SimpleDateFormat("yyyy-MM").parse(beginTimeString));
                
                List<CmcCarApproval> monthList = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
                monthObject.put(monthKey, monthList.size());
                cmcCarApproval.setParams(null);
            }
        }
        getCarUsageStatistic(cmcCarApproval, usageObject);
        getCarApprovalStatistic(cmcCarApproval, approvalArray);
        getCarDayStatistic(cmcCarApproval, dayArray);
        cmcCarApproval.setApplyDate(null);
        yearArray.add(yearObject);
        statusArray.add(statusObject);
        usageArray.add(usageObject);
        monthArray.add(monthObject);
        jsonObject.put("year", yearArray);
        jsonObject.put("status", statusArray);
        jsonObject.put("usage", usageArray);
        jsonObject.put("approval", approvalArray);
        jsonObject.put("day", dayArray);
        jsonObject.put("month", monthArray);
        jsonObject.getJSONArray("approval").sort((a,b)->((JSONObject)b).getIntValue("count") - ((JSONObject)a).getIntValue("count"));
        jsonObject.getJSONArray("day").sort((a,b)->((JSONObject)b).getIntValue("count") - ((JSONObject)a).getIntValue("count"));
        return success(jsonObject);
    }

    /**
     * 新增cmc车辆信息
     */
    @Log(title = "cmc车辆信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcCar cmcCar)
    {
        cmcCar.setStatus("1");
//        if (cmcCar.getAcquisitionTime() != null && cmcCar.getCost() != null && cmcCar.getDayCost() == null) {
//            // 年数总和法折旧
//            int acquisitionYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcCar.getAcquisitionTime()));
//            int life = cmcCar.getExpectLife() == null ? 0 : cmcCar.getExpectLife();
//            int total = 0;
//            for (int i = 0; i < life + 1; i++)
//                total += i;
//            if (total > 0) {
//                int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(DateUtils.getNowDate()));
//                int num = life - (currentYear - acquisitionYear) + 1;
//                BigDecimal estimateCost = new BigDecimal(num  * 0.95 / total / 365).multiply(cmcCar.getCost());
//                cmcCar.setDayCost(estimateCost);
//            }
//        }
        return toAjax(cmcCarService.insertCmcCar(cmcCar));
    }

    /**
     * 修改cmc车辆信息
     */
    @Log(title = "cmc车辆信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcCar cmcCar)
    {
//        if (cmcCar.getAcquisitionTime() != null && cmcCar.getCost() != null && cmcCar.getDayCost() == null) {
//            // 年数总和法折旧
//            int acquisitionYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcCar.getAcquisitionTime()));
//            int life = cmcCar.getExpectLife() == null ? 0 : cmcCar.getExpectLife();
//            int total = 0;
//            for (int i = 0; i < life + 1; i++)
//                total += i;
//            if (total > 0) {
//                int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(DateUtils.getNowDate()));
//                int num = life - (currentYear - acquisitionYear) + 1;
//                BigDecimal estimateCost = new BigDecimal(num  * 0.95 / total / 365).multiply(cmcCar.getCost());
//                cmcCar.setDayCost(estimateCost);
//            }
//        }
        return toAjax(cmcCarService.updateCmcCar(cmcCar));
    }

    /**
     * 删除cmc车辆信息
     */
    @Log(title = "cmc车辆信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{carIds}")
    public AjaxResult remove(@PathVariable Long[] carIds)
    {
        return success(cmcCarService.deleteCmcCarByCarIds(carIds));
    }

    //各车辆派出次数
    public void getCarApprovalStatistic(CmcCarApproval cmcCarApproval, JSONArray approvalArray) {
        CmcCar car = new CmcCar();
        car.setIsRent("0");
        for (CmcCar cmcCar : cmcCarService.selectCmcCarList(car)) {
            cmcCarApproval.setCars(cmcCar.getCarId().toString());
            int count = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size();
            if (count > 0) {
                JSONObject approvalObject = new JSONObject();
                approvalObject.put("name", cmcCar.getLicensePlate());
                approvalObject.put("count", count);
                approvalArray.add(approvalObject);
            }
        }
    }

    //各车辆派出天数
    public void getCarDayStatistic(CmcCarApproval cmcCarApproval, JSONArray dayArray) {
        CmcCar car = new CmcCar();
        car.setIsRent("0");
        for (CmcCar cmcCar : cmcCarService.selectCmcCarList(car)) {
            cmcCarApproval.setCars(cmcCar.getCarId().toString());
            long days = 0;
            for (CmcCarApproval carApproval : cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval)) {
                if (carApproval.getDays() < 1) {
                    carApproval.setDays(1L);
                }
                days = days + carApproval.getDays();
            }
            JSONObject dayObject = new JSONObject();
            dayObject.put("name", cmcCar.getLicensePlate());
            dayObject.put("count", days);
            dayArray.add(dayObject);
        }
    }

    //各用途车辆派出次数
    public void getCarUsageStatistic(CmcCarApproval cmcCarApproval, JSONObject usageObject) {
        cmcCarApproval.setCarUsage("0");
        usageObject.put("项目用车", cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size());
        cmcCarApproval.setCarUsage("1");
        usageObject.put("非项目用车", cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size());
        cmcCarApproval.setCarUsage("2");
        usageObject.put("工会用车", cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size());
        cmcCarApproval.setCarUsage("3");
        usageObject.put("党委用车", cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size());
        cmcCarApproval.setCarUsage("4");
        usageObject.put("团委用车", cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval).size());
        cmcCarApproval.setCarUsage(null);
    }

}
