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 com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
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.CmcBorrow;
import com.ruoyi.oa.service.ICmcBorrowService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc借款申请Controller
 * 
 * @author cmc
 * @date 2024-04-07
 */
@RestController
@RequestMapping("/oa/borrow")
public class CmcBorrowController extends BaseController
{
    @Autowired
    private ICmcBorrowService cmcBorrowService;

    /**
     * 查询cmc借款申请列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcBorrow cmcBorrow)
    {
        startPage();
        List<CmcBorrow> list = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
        return getDataTable(list);
    }

    /**
     * 导出cmc借款申请列表
     */
    @Log(title = "cmc借款申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcBorrow cmcBorrow)
    {
        List<CmcBorrow> list = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
        ExcelUtil<CmcBorrow> util = new ExcelUtil<CmcBorrow>(CmcBorrow.class);
        util.exportExcel(response, list, "cmc借款申请数据");
    }

    /**
     * 获取cmc借款申请详细信息
     */
    @GetMapping(value = "/{borrowId}")
    public AjaxResult getInfo(@PathVariable("borrowId") String borrowId)
    {
        return success(cmcBorrowService.selectCmcBorrowByBorrowId(borrowId));
    }

    /**
     * 获取cmc借款统计信息
     */
    @GetMapping("/statistic")
    public AjaxResult getBorrowStatistic(CmcBorrow cmcBorrow) throws ParseException
    {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearArray = new JSONArray();
        JSONObject yearObject = new JSONObject();
        JSONArray monthArray = new JSONArray();
        JSONObject monthObject = new JSONObject();
        JSONArray monthAmountArray = new JSONArray();
        JSONObject monthAmountObject = new JSONObject();
        JSONArray amountArray = new JSONArray();
        JSONObject amountObject = new JSONObject();
        
        JSONArray usageArray = new JSONArray();
        JSONObject usageObject = new JSONObject();
        JSONArray usageAmountArray = new JSONArray();
        JSONObject usageAmountObject = new JSONObject();
        JSONArray yearProjectCountArray = new JSONArray();
        JSONObject yearProjectCountObject = new JSONObject();
        JSONArray yearProjectAmountArray = new JSONArray();
        JSONObject yearProjectAmountObject = new JSONObject();
        //整体
        if (cmcBorrow.getLendTime() == null) {
            //每年借款金额
            for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                cmcBorrow.setLendTime(new SimpleDateFormat("yyyy").parse(String.valueOf(i)));
                List<CmcBorrow> yearList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
                yearObject.put(String.valueOf(i), yearList.size());
                BigDecimal amount = new BigDecimal(0);
                for (CmcBorrow borrow : yearList) {
                    if (borrow.getManagerAmount() != null)
                        amount = amount.add(borrow.getManagerAmount());
                }
                amountObject.put(String.valueOf(i), amount);
            }
            cmcBorrow.setLendTime(null);
        }
        //年度
        else {
            String year = new SimpleDateFormat("yyyy").format(cmcBorrow.getLendTime());
            //该年借款次数
            cmcBorrow.setLendTime(new SimpleDateFormat("yyyy").parse(year));
            List<CmcBorrow> yearList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
            yearObject.put(year, yearList.size());
            BigDecimal yearAmount = new BigDecimal(0);
            for (CmcBorrow borrow : yearList) {
                if (borrow.getManagerAmount() != null)
                    yearAmount = yearAmount.add(borrow.getManagerAmount());
            }
            amountObject.put(year, yearAmount);
            
            //按月份统计
            for (int i = 1; i <= 12; i++) {
                String monthStr = String.format("%02d", i);
                String monthKey = year + "-" + monthStr;
                String beginTimeString = monthKey + "-01";
                
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTimeString + " 00:00:00");
                cmcBorrow.setParams(params);
                cmcBorrow.setLendTime(new SimpleDateFormat("yyyy-MM").parse(beginTimeString));
                List<CmcBorrow> monthBorrowList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
                monthObject.put(monthKey, monthBorrowList.size());
                
                BigDecimal monthAmount = new BigDecimal(0);
                for (CmcBorrow borrow : monthBorrowList) {
                    if (borrow.getManagerAmount() != null)
                        monthAmount = monthAmount.add(borrow.getManagerAmount());
                }
                monthAmountObject.put(monthKey, monthAmount);
            }
            cmcBorrow.setParams(null);
        }
        getBorrowUsageStatistic(cmcBorrow, usageObject, usageAmountObject, yearProjectCountObject, yearProjectAmountObject);
        yearArray.add(yearObject);
        monthArray.add(monthObject);
        monthAmountArray.add(monthAmountObject);
        amountArray.add(amountObject);
        usageArray.add(usageObject);
        usageAmountArray.add(usageAmountObject);
        yearProjectCountArray.add(yearProjectCountObject);
        yearProjectAmountArray.add(yearProjectAmountObject);
        jsonObject.put("year", yearArray);
        jsonObject.put("month", monthArray);
        jsonObject.put("monthAmount", monthAmountArray);
        jsonObject.put("amount", amountArray);
        jsonObject.put("usage", usageArray);
        jsonObject.put("usageAmount", usageAmountArray);
        jsonObject.put("yearProjectCount", yearProjectCountArray);
        jsonObject.put("yearProjectAmount", yearProjectAmountArray);
        return success(jsonObject);
    }

    /**
     * 新增cmc借款申请
     */
    @Log(title = "cmc借款申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcBorrow cmcBorrow)
    {
        cmcBorrow.setApplyDept(getLoginUser().getDeptId());
        return toAjax(cmcBorrowService.insertCmcBorrow(cmcBorrow));
    }

    /**
     * 修改cmc借款申请
     */
    @Log(title = "cmc借款申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcBorrow cmcBorrow)
    {
        return toAjax(cmcBorrowService.updateCmcBorrow(cmcBorrow));
    }

    /**
     * 删除cmc借款申请
     */
    @Log(title = "cmc借款申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{borrowIds}")
    public AjaxResult remove(@PathVariable String[] borrowIds)
    {
        return success(cmcBorrowService.deleteCmcBorrowByBorrowIds(borrowIds));
    }

    //各用途借款次数
    public void getBorrowUsageStatistic(CmcBorrow cmcBorrow, JSONObject usageObject, JSONObject usageAmountObject, JSONObject yearProjectCountObject, JSONObject yearProjectAmountObject) throws ParseException {
        cmcBorrow.setBorrowUsage("0");
        if (cmcBorrow.getLendTime() == null)
            cmcBorrow.setLendTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
        List<CmcBorrow> usageList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
        usageObject.put("项目借款", usageList.size());
        BigDecimal pAmount = new BigDecimal(0);
        for (CmcBorrow borrow : usageList) {
            if (borrow.getManagerAmount() != null)
                pAmount = pAmount.add(borrow.getManagerAmount());
        }
        usageAmountObject.put("项目借款", pAmount);
        for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
            BigDecimal pyAmount = new BigDecimal(0);
            int count = 0;
            for (CmcBorrow borrow : usageList) {
                if (borrow.getManagerAmount() != null && borrow.getProjectNumber() != null && borrow.getProjectNumber().contains(String.valueOf(i))) {
                    pyAmount = pyAmount.add(borrow.getManagerAmount());
                    count ++;
                }
            }
            yearProjectCountObject.put(i + "项目", count);
            yearProjectAmountObject.put(i + "项目", pyAmount);
        }
        cmcBorrow.setBorrowUsage("1");
        usageList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
        usageObject.put("非项目借款", usageList.size());
        BigDecimal oAmount = new BigDecimal(0);
        for (CmcBorrow borrow : usageList) {
            if (borrow.getManagerAmount() != null)
                oAmount = oAmount.add(borrow.getManagerAmount());
        }
        usageAmountObject.put("非项目借款", oAmount);
        cmcBorrow.setBorrowUsage("3");
        usageList = cmcBorrowService.selectCmcBorrowList(cmcBorrow);
        usageObject.put("党委借款", usageList.size());
        BigDecimal dAmount = new BigDecimal(0);
        for (CmcBorrow borrow : usageList) {
            if (borrow.getManagerAmount() != null)
                dAmount = dAmount.add(borrow.getManagerAmount());
        }
        usageAmountObject.put("党委借款", dAmount);
    }

}
