package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
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.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oa.domain.CmcSubContract;
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.service.ICmcSubContractService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc分包合同评审Controller
 * 
 * @author cmc
 * @date 2024-04-18
 */
@RestController
@RequestMapping("/oa/subContract")
public class CmcSubContractController extends BaseController
{
    @Autowired
    private ICmcSubContractService cmcSubContractService;

    /**
     * 查询cmc分包合同评审列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcSubContract cmcSubContract)
    {
        startPage();
        List<CmcSubContract> list = cmcSubContractService.selectCmcSubContractListP(cmcSubContract);
        return getDataTable(list);
    }

    /**
     * 导出cmc分包合同评审列表
     */
    @Log(title = "cmc分包合同评审", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcSubContract cmcSubContract)
    {
        List<CmcSubContract> list = cmcSubContractService.selectCmcSubContractList(cmcSubContract);
        ExcelUtil<CmcSubContract> util = new ExcelUtil<CmcSubContract>(CmcSubContract.class);
        util.exportExcel(response, list, "cmc分包合同评审数据");
    }

    /**
     * 导出选择字段cmc分包合同评审列表
     */
    @Log(title = "cmc分包合同评审", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelectFields")
    public void export(HttpServletResponse response, CmcSubContract cmcSubContract, String selectFields)
    {
        List<CmcSubContract> list = cmcSubContractService.selectCmcSubContractList(cmcSubContract);
        List<String> selectFieldList = Arrays.asList(selectFields.split(","));
        ExcelUtil<CmcSubContract> util = new ExcelUtil<CmcSubContract>(CmcSubContract.class);
        util.exportExcel(response, selectFieldList, list, "cmc分包合同评审数据", StringUtils.EMPTY);
    }

    /**
     * 获取cmc分包合同评审详细信息
     */
    @GetMapping(value = "/{subContractId}")
    public AjaxResult getInfo(@PathVariable("subContractId") String subContractId)
    {
        return success(cmcSubContractService.selectCmcSubContractBySubContractId(subContractId));
    }

    /**
     * 获取cmc分包合同统计信息
     */
    @GetMapping("/statistic")
    public AjaxResult getSubContractStatistic(CmcSubContract cmcSubContract) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearCountArray = new JSONArray();
        JSONObject yearCountObject = new JSONObject();
        JSONArray monthCountArray = new JSONArray();
        JSONObject monthCountObject = new JSONObject();
        JSONArray sourceCountArray = new JSONArray();
        JSONObject sourceCountObject = new JSONObject();
        JSONArray yearAmountArray = new JSONArray();
        JSONObject yearAmountObject = new JSONObject();
        JSONArray monthAmountArray = new JSONArray();
        JSONObject monthAmountObject = new JSONObject();
        JSONArray sourceAmountArray = new JSONArray();
        JSONObject sourceAmountObject = new JSONObject();
        JSONArray paidYearCountArray = new JSONArray();
        JSONObject paidYearCountObject = new JSONObject();
        JSONArray paidMonthCountArray = new JSONArray();
        JSONObject paidMonthCountObject = new JSONObject();
        JSONArray paidSourceCountArray = new JSONArray();
        JSONObject paidSourceCountObject = new JSONObject();
        JSONArray paidYearAmountArray = new JSONArray();
        JSONObject paidYearAmountObject = new JSONObject();
        JSONArray paidMonthAmountArray = new JSONArray();
        JSONObject paidMonthAmountObject = new JSONObject();
        JSONArray paidSourceAmountArray = new JSONArray();
        JSONObject paidSourceAmountObject = new JSONObject();
        int totalCount = 0;
        int paidTotalCount = 0;
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal paidTotalAmount = new BigDecimal(0);
        String beginTime = "";
        String endTime = "";
        //每年合同数量及金额
        if (cmcSubContract.getSignDate() == null) {
            if (cmcSubContract.getParams().size() == 0) {
                for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                    cmcSubContract.setSignDate(new SimpleDateFormat("yyyy").parse(String.valueOf(i)));
                    List<CmcSubContract> yearContractList = cmcSubContractService.selectCmcSubContractList(cmcSubContract);
                    int yearCountI = yearContractList.size();
                    int paidYearCountI = 0;
                    BigDecimal yearAmountI = new BigDecimal(0);
                    BigDecimal paidAmountI = new BigDecimal(0);
                    for (CmcSubContract contract : yearContractList) {
                        if (contract.getSubAmount() != null) {
                            yearAmountI = yearAmountI.add(contract.getSubAmount());
                            if (contract.getPaidAmount() != null) {
                                paidAmountI = paidAmountI.add(contract.getPaidAmount());
                                paidYearCountI++;
                            }
                        }
                    }
                    totalCount += yearCountI;
                    paidTotalCount += paidYearCountI;
                    totalAmount = totalAmount.add(yearAmountI);
                    paidTotalAmount = paidTotalAmount.add(paidAmountI);
                    yearCountObject.put(String.valueOf(i), yearCountI);
                    paidYearCountObject.put(String.valueOf(i), paidYearCountI);
                    yearAmountObject.put(String.valueOf(i), yearAmountI);
                    paidYearAmountObject.put(String.valueOf(i), paidAmountI);
                }
            }
            else {
                beginTime = (String) cmcSubContract.getParams().get("beginTime");
                endTime = (String) cmcSubContract.getParams().get("endTime");
                List<String> monthList = DateUtils.getMonthBetweenDate(beginTime, endTime);
                for (int i = 0; i < monthList.size(); i++) {
                    String beginTimeString = monthList.get(i) + "-01";
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.YEAR, Integer.parseInt(monthList.get(i).split("-")[0]));
                    calendar.set(Calendar.MONTH, Integer.parseInt(monthList.get(i).split("-")[1]) - 1);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                    String endTimeString = monthList.get(i) + "-" + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    Map<String, Object> params = new HashMap<>();
                    params.put("beginTime", beginTimeString + " 00:00:00");
                    params.put("endTime", endTimeString + " 23:59:59");
                    cmcSubContract.setParams(params);
                    List<CmcSubContract> monthContractList = cmcSubContractService.selectCmcSubContractListByRange(cmcSubContract);
                    int monthCount = monthContractList.size();
                    int paidMonthCount = 0;
                    BigDecimal monthAmount = new BigDecimal(0);
                    BigDecimal paidMonthAmount = new BigDecimal(0);
                    for (CmcSubContract contract : monthContractList) {
                        if (contract.getSubAmount() != null) {
                            monthAmount = monthAmount.add(contract.getSubAmount());
                            if (contract.getPaidAmount() != null) {
                                paidMonthAmount = paidMonthAmount.add(contract.getPaidAmount());
                                paidMonthCount++;
                            }
                        }
                    }
                    totalCount += monthCount;
                    paidTotalCount += paidMonthCount;
                    totalAmount = totalAmount.add(monthAmount);
                    paidTotalAmount = paidTotalAmount.add(paidMonthAmount);
                    monthCountObject.put(monthList.get(i), monthCount);
                    monthAmountObject.put(monthList.get(i),monthAmount);
                    paidMonthCountObject.put(monthList.get(i), paidMonthCount);
                    paidMonthAmountObject.put(monthList.get(i), paidMonthAmount);
                }
            }
            cmcSubContract.setSignDate(null);
        }
        else if (cmcSubContract.getSignDate() != null) {
            //输入年份合同数量及金额
            totalCount = cmcSubContractService.selectCmcSubContractList(cmcSubContract).size();
            yearCountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()), totalCount);
            for (int i = 1; i <= 12; i++) {
                String month = i < 10 ? "0" + i : String.valueOf(i);
                String beginTimeString = new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month + "-01";
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate())));
                calendar.set(Calendar.MONTH, i - 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                String endTimeString = new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month + "-" + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTimeString + " 00:00:00");
                params.put("endTime", endTimeString + " 23:59:59");
                cmcSubContract.setParams(params);
                List<CmcSubContract> monthContractList = cmcSubContractService.selectCmcSubContractListByRange(cmcSubContract);
                int monthCount = monthContractList.size();
                int paidMonthCount = 0;
                BigDecimal monthAmount = new BigDecimal(0);
                BigDecimal paidMonthAmount = new BigDecimal(0);
                for (CmcSubContract contract : monthContractList) {
                    if (contract.getSubAmount() != null) {
                        monthAmount = monthAmount.add(contract.getSubAmount());
                        if (contract.getPaidAmount() != null) {
                            paidMonthAmount = paidMonthAmount.add(contract.getPaidAmount());
                            paidMonthCount++;
                        }
                    }
                }
                monthCountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month, monthCount);
                monthAmountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month,monthAmount);
                paidMonthCountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month, paidMonthCount);
                paidMonthAmountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()) + "-" + month, paidMonthAmount);
            }
            for (CmcSubContract contract : cmcSubContractService.selectCmcSubContractList(cmcSubContract)) {
                if (contract.getSubAmount() != null) {
                    totalAmount = totalAmount.add(contract.getSubAmount());
                    if (contract.getPaidAmount() != null) {
                        paidTotalAmount = paidTotalAmount.add(contract.getPaidAmount());
                        paidTotalCount++;
                    }
                }
            }
            paidYearCountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()), paidTotalCount);
            yearAmountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()), totalAmount);
            paidYearAmountObject.put(new SimpleDateFormat("yyyy").format(cmcSubContract.getSignDate()), paidTotalAmount);
        }
        if (!endTime.equals("")) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, Integer.parseInt(endTime.split("-")[0]));
            calendar.set(Calendar.MONTH, Integer.parseInt(endTime.split("-")[1]) - 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            endTime = endTime.split("-")[0] + "-" + endTime.split("-")[1] + "-"
                    + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        getProjectSourceStatistic(cmcSubContract, sourceCountObject, paidSourceCountObject, sourceAmountObject, paidSourceAmountObject, totalCount, paidTotalCount, totalAmount, paidTotalAmount, beginTime, endTime);
        yearCountArray.add(yearCountObject);
        monthCountArray.add(monthCountObject);
        sourceCountArray.add(sourceCountObject);
        yearAmountArray.add(yearAmountObject);
        monthAmountArray.add(monthAmountObject);
        sourceAmountArray.add(sourceAmountObject);
        paidYearCountArray.add(paidYearCountObject);
        paidMonthCountArray.add(paidMonthCountObject);
        paidSourceCountArray.add(paidSourceCountObject);
        paidYearAmountArray.add(paidYearAmountObject);
        paidMonthAmountArray.add(paidMonthAmountObject);
        paidSourceAmountArray.add(paidSourceAmountObject);
        jsonObject.put("yearCount", yearCountArray);
        jsonObject.put("monthCount", monthCountArray);
        jsonObject.put("sourceCount", sourceCountArray);
        jsonObject.put("yearAmount", yearAmountArray);
        jsonObject.put("monthAmount", monthAmountArray);
        jsonObject.put("sourceAmount", sourceAmountArray);
        jsonObject.put("paidYearCount", paidYearCountArray);
        jsonObject.put("paidMonthCount", paidMonthCountArray);
        jsonObject.put("paidSourceCount", paidSourceCountArray);
        jsonObject.put("paidYearAmount", paidYearAmountArray);
        jsonObject.put("paidMonthAmount", paidMonthAmountArray);
        jsonObject.put("paidSourceAmount", paidSourceAmountArray);
        return success(jsonObject);
    }

    /**
     * 新增cmc分包合同评审
     */
    @Log(title = "cmc分包合同评审", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcSubContract cmcSubContract)
    {
        return toAjax(cmcSubContractService.insertCmcSubContract(cmcSubContract));
    }

    /**
     * 修改cmc分包合同评审
     */
    @Log(title = "cmc分包合同评审", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcSubContract cmcSubContract)
    {
        return toAjax(cmcSubContractService.updateCmcSubContract(cmcSubContract));
    }

    /**
     * 删除cmc分包合同评审
     */
    @Log(title = "cmc分包合同评审", businessType = BusinessType.DELETE)
	@DeleteMapping("/{subContractIds}")
    public AjaxResult remove(@PathVariable String[] subContractIds)
    {
        return success(cmcSubContractService.deleteCmcSubContractBySubContractIds(subContractIds));
    }

    //院内外项目数量及金额
    public void getProjectSourceStatistic(CmcSubContract cmcSubContract, JSONObject sourceCountObject, JSONObject paidSourceCountObject, JSONObject sourceAmountObject, JSONObject paidSourceAmountObject,
                                          int totalCount, int paidTotalCount, BigDecimal totalAmount, BigDecimal paidTotalAmount, String beginTime, String endTime) {
        int cCount;
        int wCount;
        int nCount;
        int paidCCount = 0;
        int paidWCount = 0;
        int paidNCount;
        BigDecimal cAmount = new BigDecimal(0);
        BigDecimal wAmount = new BigDecimal(0);
        BigDecimal nAmount;
        BigDecimal paidCAmount = new BigDecimal(0);
        BigDecimal paidWAmount = new BigDecimal(0);
        BigDecimal paidNAmount;
        cmcSubContract.setProjectSource("1");
        List<CmcSubContract> sourceList;
        if (beginTime.equals(""))
            sourceList = cmcSubContractService.selectCmcSubContractListP(cmcSubContract);
        else {
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
            cmcSubContract.setParams(params);
            sourceList = cmcSubContractService.selectCmcSubContractListByRange(cmcSubContract);
        }
        wCount = sourceList.size();
        for (CmcSubContract contract : sourceList) {
            if (contract.getSubAmount() != null) {
                wAmount = wAmount.add(contract.getSubAmount());
                if (contract.getPaidAmount() != null) {
                    paidWAmount = paidWAmount.add(contract.getPaidAmount());
                    if (contract.getPaidAmount().compareTo(contract.getSubAmount()) >= 0)
                        paidWCount++;
                }
            }
        }
        nCount = totalCount - wCount;
        paidNCount = paidTotalCount - wCount;
        nAmount = totalAmount.subtract(wAmount);
        paidNAmount = paidTotalAmount.subtract(paidWAmount);
        sourceCountObject.put("院外项目", wCount);
        paidSourceCountObject.put("已完成付款院外项目", paidWCount);
        sourceAmountObject.put("院外项目分包金额", wAmount);
        paidSourceAmountObject.put("院外项目付款金额", paidWAmount);
        cmcSubContract.setProjectSource("0");
        if (beginTime.equals(""))
            sourceList = cmcSubContractService.selectCmcSubContractListP(cmcSubContract);
        else {
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
            cmcSubContract.setParams(params);
            sourceList = cmcSubContractService.selectCmcSubContractListByRange(cmcSubContract);
        }
        cCount = sourceList.size();
        for (CmcSubContract contract : sourceList) {
            if (contract.getSubAmount() != null) {
                cAmount = cAmount.add(contract.getSubAmount());
                if (contract.getPaidAmount() != null) {
                    paidCAmount = paidCAmount.add(contract.getPaidAmount());
                    if (contract.getPaidAmount().compareTo(contract.getSubAmount()) >= 0)
                        paidCCount++;
                }
            }
        }
        nCount = nCount - cCount;
        paidNCount = paidNCount - cCount;
        nAmount = nAmount.subtract(cAmount);
        paidNAmount = paidNAmount.subtract(paidCAmount);
        sourceCountObject.put("院内项目", cCount);
        paidSourceCountObject.put("已完成付款院内项目", paidCCount);
        sourceAmountObject.put("院内项目分包金额", cAmount);
        paidSourceAmountObject.put("院内项目付款金额", paidCAmount);
        cmcSubContract.setProjectSource(null);
        sourceCountObject.put("未关联项目", nCount);
        paidSourceCountObject.put("已完成付款未关联项目", paidNCount);
        sourceAmountObject.put("未关联项目分包金额", nAmount);
        paidSourceAmountObject.put("未关联项目付款金额", paidNAmount);
    }

}
