package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
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.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
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.CmcRepair;
import com.ruoyi.oa.service.impl.ICmcRepairService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 维修审批Controller
 * 
 * @author cmc
 * @date 2026-07-01
 */
@RestController
@RequestMapping("/oa/repair")
public class CmcRepairController extends BaseController
{
    @Autowired
    private ICmcRepairService cmcRepairService;

    /**
     * 查询维修审批列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcRepair cmcRepair)
    {
        startPage();
        List<CmcRepair> list = cmcRepairService.selectCmcRepairList(cmcRepair);
        return getDataTable(list);
    }

    /**
     * 导出维修审批列表
     */
    @Log(title = "维修审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcRepair cmcRepair)
    {
        List<CmcRepair> list = cmcRepairService.selectCmcRepairList(cmcRepair);
        ExcelUtil<CmcRepair> util = new ExcelUtil<CmcRepair>(CmcRepair.class);
        util.exportExcel(response, list, "维修审批数据");
    }

    /**
     * 获取维修审批统计信息
     */
    @GetMapping("/statistic")
    public AjaxResult getRepairStatistic(CmcRepair cmcRepair) throws ParseException
    {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearCountArray = new JSONArray();
        JSONObject yearCountObject = new JSONObject();
        JSONArray yearAmountArray = new JSONArray();
        JSONObject yearAmountObject = new JSONObject();
        JSONArray monthCountArray = new JSONArray();
        JSONObject monthCountObject = new JSONObject();
        JSONArray monthAmountArray = new JSONArray();
        JSONObject monthAmountObject = new JSONObject();
        JSONArray usageCountArray = new JSONArray();
        JSONObject usageCountObject = new JSONObject();
        JSONArray usageAmountArray = new JSONArray();
        JSONObject usageAmountObject = new JSONObject();

        if (cmcRepair.getApplyDate() == null)
        {
            int currentYear = Calendar.getInstance().get(Calendar.YEAR);
            Integer minYear = cmcRepairService.selectMinApplyYear();
            int startYear = minYear != null ? minYear : currentYear;
            for (int i = startYear; i <= currentYear; i++)
            {
                CmcRepair query = new CmcRepair();
                Map<String, Object> params = new HashMap<>();
                params.put("statYear", String.valueOf(i));
                query.setParams(params);
                List<CmcRepair> yearList = cmcRepairService.selectCmcRepairList(query);
                yearCountObject.put(String.valueOf(i), yearList.size());
                yearAmountObject.put(String.valueOf(i), sumRepairMoney(yearList));
            }
        }
        else
        {
            String year = new SimpleDateFormat("yyyy").format(cmcRepair.getApplyDate());
            CmcRepair yearQuery = new CmcRepair();
            Map<String, Object> yearParams = new HashMap<>();
            yearParams.put("statYear", year);
            yearQuery.setParams(yearParams);
            List<CmcRepair> yearList = cmcRepairService.selectCmcRepairList(yearQuery);
            yearCountObject.put(year, yearList.size());
            yearAmountObject.put(year, sumRepairMoney(yearList));

            for (int i = 1; i <= 12; i++)
            {
                String monthKey = year + "-" + String.format("%02d", i);
                CmcRepair monthQuery = new CmcRepair();
                Map<String, Object> monthParams = new HashMap<>();
                monthParams.put("statMonth", monthKey);
                monthQuery.setParams(monthParams);
                List<CmcRepair> monthList = cmcRepairService.selectCmcRepairList(monthQuery);
                monthCountObject.put(monthKey, monthList.size());
                monthAmountObject.put(monthKey, sumRepairMoney(monthList));
            }
            fillUsageStatistic(yearQuery, usageCountObject, usageAmountObject);
        }

        if (cmcRepair.getApplyDate() == null)
        {
            CmcRepair allQuery = new CmcRepair();
            fillUsageStatistic(allQuery, usageCountObject, usageAmountObject);
        }

        yearCountArray.add(yearCountObject);
        yearAmountArray.add(yearAmountObject);
        monthCountArray.add(monthCountObject);
        monthAmountArray.add(monthAmountObject);
        usageCountArray.add(usageCountObject);
        usageAmountArray.add(usageAmountObject);
        jsonObject.put("yearCount", yearCountArray);
        jsonObject.put("yearAmount", yearAmountArray);
        jsonObject.put("monthCount", monthCountArray);
        jsonObject.put("monthAmount", monthAmountArray);
        jsonObject.put("usageCount", usageCountArray);
        jsonObject.put("usageAmount", usageAmountArray);
        return success(jsonObject);
    }

    private BigDecimal sumRepairMoney(List<CmcRepair> list)
    {
        BigDecimal amount = BigDecimal.ZERO;
        for (CmcRepair repair : list)
        {
            if (repair.getRepairMoney() != null)
            {
                amount = amount.add(repair.getRepairMoney());
            }
        }
        return amount;
    }

    private void fillUsageStatistic(CmcRepair baseQuery, JSONObject usageCountObject, JSONObject usageAmountObject)
    {
        String[][] types = {{"0", "电脑"}, {"1", "打印机"}, {"2", "其他"}, {"3", "仪器设备"}};
        for (String[] type : types)
        {
            CmcRepair query = new CmcRepair();
            query.setParams(baseQuery.getParams());
            query.setRepairUsage(type[0]);
            List<CmcRepair> list = cmcRepairService.selectCmcRepairList(query);
            usageCountObject.put(type[1], list.size());
            usageAmountObject.put(type[1], sumRepairMoney(list));
        }
    }

    /**
     * 获取维修审批详细信息
     */
    @GetMapping(value = "/{repairId}")
    public AjaxResult getInfo(@PathVariable("repairId") String repairId)
    {
        return success(cmcRepairService.selectCmcRepairByRepairId(repairId));
    }

    /**
     * 新增维修审批
     */
    @Log(title = "维修审批", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcRepair cmcRepair)
    {
        return toAjax(cmcRepairService.insertCmcRepair(cmcRepair));
    }

    /**
     * 修改维修审批
     */
    @Log(title = "维修审批", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcRepair cmcRepair)
    {
        return toAjax(cmcRepairService.updateCmcRepair(cmcRepair));
    }

    /**
     * 删除维修审批
     */
    @Log(title = "维修审批", businessType = BusinessType.DELETE)
	@DeleteMapping("/{repairIds}")
    public AjaxResult remove(@PathVariable String[] repairIds)
    {
        return toAjax(cmcRepairService.deleteCmcRepairByRepairIds(repairIds));
    }
}
