package com.ruoyi.web.controller.oa;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
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.oa.domain.CmcSettle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.ICmcSettleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * cmc结算审批Controller
 * 
 * @author cmc
 * @date 2024-04-29
 */
@RestController
@RequestMapping("/oa/settle")
public class CmcSettleController extends BaseController
{
    @Autowired
    private ICmcSettleService cmcSettleService;

    @Value("${cmc.profile}")
    private String profile;
    /**
     * 查询cmc结算审批列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcSettle cmcSettle)
    {
        startPage();
        List<CmcSettle> list = cmcSettleService.selectCmcSettleList(cmcSettle);
        return getDataTable(list);
    }

    /**
     * 导出cmc结算审批列表
     */
    @Log(title = "cmc结算审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcSettle cmcSettle)
    {
        List<CmcSettle> list = cmcSettleService.selectCmcSettleList(cmcSettle);
        ExcelUtil<CmcSettle> util = new ExcelUtil<CmcSettle>(CmcSettle.class);
        util.exportExcel(response, list, "cmc结算审批数据");
    }

    /**
     * 上传结算excel文件
     */
    @PostMapping("/uploadSheet")
    public AjaxResult uploadSettleSheet(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("文件内容为空！");
        }
        else {
            File profilePath = new File(profile + "/upload/项目结算/导入数据");
            if (!profilePath.exists())
                profilePath.mkdirs();
            File transferFile = new File( profilePath + "/" + file.getOriginalFilename());
            file.transferTo(transferFile);
            InputStream in = new FileInputStream(transferFile);
            XSSFSheet sheetAt = null;
            int rowNumber = 0;
            if (file.getOriginalFilename() != null) {
                sheetAt = new XSSFWorkbook(in).getSheetAt(0);
                rowNumber = sheetAt.getPhysicalNumberOfRows();
            }
            JSONArray jsonArray = new JSONArray();
            for (int i = 1; i < rowNumber - 1;) {
                JSONObject jsonObject = new JSONObject();
                i++;
                String column0 = getStringCellValue(sheetAt.getRow(i).getCell(0));
                if (column0 != null && !column0.equals("")) {
                    jsonObject.put("priceId", column0);
                    jsonObject.put("content", getStringCellValue(sheetAt.getRow(i).getCell(1)));
                    jsonObject.put("workload", getStringCellValue(sheetAt.getRow(i).getCell(4)));
                    jsonObject.put("groundType", getStringCellValue(sheetAt.getRow(i).getCell(5)));
                    jsonObject.put("coefficient", getStringCellValue(sheetAt.getRow(i).getCell(7)));
                    jsonObject.put("remark", getStringCellValue(sheetAt.getRow(i).getCell(8)));
                    jsonArray.add(jsonObject);
                }
            }
            in.close();
            return AjaxResult.success(jsonArray);
        }
    }

    /**
     * 获取cmc结算审批详细信息
     */
    @GetMapping(value = "/{settleId}")
    public AjaxResult getInfo(@PathVariable("settleId") String settleId)
    {
        return success(cmcSettleService.selectCmcSettleBySettleId(settleId));
    }

    /**
     * 获取cmc结算审批详细信息
     */
    @GetMapping("/statistic")
    public AjaxResult getSettleStatistic(CmcSettle cmcSettle) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearArray = new JSONArray();
        JSONObject yearObject = new JSONObject();
        JSONArray amountArray = new JSONArray();
        JSONObject amountObject = new JSONObject();
        JSONArray typeArray = new JSONArray();
        JSONObject typeObject = new JSONObject();
        JSONArray typeAmountArray = new JSONArray();
        JSONObject typeAmountObject = new JSONObject();
        JSONArray yearProjectCountArray = new JSONArray();
        JSONObject yearProjectCountObject = new JSONObject();
        JSONArray yearProjectAmountArray = new JSONArray();
        JSONObject yearProjectAmountObject = new JSONObject();
        JSONArray monthArray = new JSONArray();
        JSONObject monthObject = new JSONObject();
        JSONArray monthAmountArray = new JSONArray();
        JSONObject monthAmountObject = new JSONObject();
        //每年结算数量和金额
        if (cmcSettle.getGmTime() == null) {
            for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                cmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse(String.valueOf(i)));
                yearObject.put(String.valueOf(i), cmcSettleService.selectCmcSettleList(cmcSettle).size());
                BigDecimal amount = new BigDecimal(0);
                for (CmcSettle settle : cmcSettleService.selectCmcSettleList(cmcSettle)) {
                    if (settle.getAmount() != null)
                        amount = amount.add(settle.getAmount());
                }
                amountObject.put(String.valueOf(i), amount);
            }
            cmcSettle.setGmTime(null);
        }
        else {
            String yearStr = new SimpleDateFormat("yyyy").format(cmcSettle.getGmTime());
            cmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse(yearStr));
            List<CmcSettle> yearList = cmcSettleService.selectCmcSettleList(cmcSettle);
            yearObject.put(yearStr, yearList.size());
            BigDecimal amount = new BigDecimal(0);
            for (CmcSettle settle : yearList) {
                if (settle.getAmount() != null)
                    amount = amount.add(settle.getAmount());
            }
            amountObject.put(yearStr, amount);
            
            //月度统计
            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");
                cmcSettle.setParams(params);
                cmcSettle.setGmTime(new SimpleDateFormat("yyyy-MM").parse(beginTimeString));
                
                List<CmcSettle> monthList = cmcSettleService.selectCmcSettleList(cmcSettle);
                monthObject.put(monthKey, monthList.size());
                BigDecimal monthAmount = new BigDecimal(0);
                for (CmcSettle settle : monthList) {
                    if (settle.getAmount() != null)
                        monthAmount = monthAmount.add(settle.getAmount());
                }
                monthAmountObject.put(monthKey, monthAmount);
                cmcSettle.setParams(null);
            }
        }
        getSettleTypeStatistic(cmcSettle, typeObject, typeAmountObject, yearProjectCountObject, yearProjectAmountObject);
        cmcSettle.setGmTime(null);
        yearArray.add(yearObject);
        amountArray.add(amountObject);
        typeArray.add(typeObject);
        typeAmountArray.add(typeAmountObject);
        yearProjectCountArray.add(yearProjectCountObject);
        yearProjectAmountArray.add(yearProjectAmountObject);
        monthArray.add(monthObject);
        monthAmountArray.add(monthAmountObject);
        jsonObject.put("year", yearArray);
        jsonObject.put("amount", amountArray);
        jsonObject.put("type", typeArray);
        jsonObject.put("typeAmount", typeAmountArray);
        jsonObject.put("yearProjectCount", yearProjectCountArray);
        jsonObject.put("yearProjectAmount", yearProjectAmountArray);
        jsonObject.put("month", monthArray);
        jsonObject.put("monthAmount", monthAmountArray);
        return success(jsonObject);
    }

    /**
     * 新增cmc结算审批
     */
    @Log(title = "cmc结算审批", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcSettle cmcSettle)
    {
        cmcSettle.setReportDept(getLoginUser().getDeptId());
        if (cmcSettle.getProjectId() != null && cmcSettle.getXmName() == null)
            cmcSettle.setXmName(" ");
        if (cmcSettle.getProjectId() == null && cmcSettle.getXmName() != null)
            cmcSettle.setProjectId("0");
        return toAjax(cmcSettleService.insertCmcSettle(cmcSettle));
    }

    /**
     * 修改cmc结算审批
     */
    @Log(title = "cmc结算审批", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcSettle cmcSettle)
    {
        return toAjax(cmcSettleService.updateCmcSettle(cmcSettle));
    }

    /**
     * 删除cmc结算审批
     */
    @Log(title = "cmc结算审批", businessType = BusinessType.DELETE)
	@DeleteMapping("/{settleIds}")
    public AjaxResult remove(@PathVariable String[] settleIds)
    {
        return success(cmcSettleService.deleteCmcSettleBySettleIds(settleIds));
    }

    //各用途结算次数
    public void getSettleTypeStatistic(CmcSettle cmcSettle, JSONObject typeObject, JSONObject typeAmountObject, JSONObject yearProjectCountObject, JSONObject yearProjectAmountObject) throws ParseException {
        cmcSettle.setXmName(" ");
        if (cmcSettle.getGmTime() == null)
            cmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
        typeObject.put("项目结算", cmcSettleService.selectCmcSettleList(cmcSettle).size());
        BigDecimal pAmount = new BigDecimal(0);
        for (CmcSettle settle : cmcSettleService.selectCmcSettleList(cmcSettle)) {
            if (settle.getAmount() != null)
                pAmount = pAmount.add(settle.getAmount());
        }
        typeAmountObject.put("项目结算", pAmount);
        for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
            BigDecimal pyAmount = new BigDecimal(0);
            int count = 0;
            for (CmcSettle settle : cmcSettleService.selectCmcSettleList(cmcSettle)) {
                if (settle.getAmount() != null && settle.getProjectNumber() != null && settle.getProjectNumber().contains(String.valueOf(i))) {
                    pyAmount = pyAmount.add(settle.getAmount());
                    count ++;
                }
            }
            yearProjectCountObject.put(i + "项目", count);
            yearProjectAmountObject.put(i + "项目", pyAmount);
        }
        cmcSettle.setXmName(null);
        cmcSettle.setProjectId("0");
        typeObject.put("其他结算", cmcSettleService.selectCmcSettleList(cmcSettle).size());
        BigDecimal oAmount = new BigDecimal(0);
        for (CmcSettle settle : cmcSettleService.selectCmcSettleList(cmcSettle)) {
            if (settle.getAmount() != null)
                oAmount = oAmount.add(settle.getAmount());
        }
        typeAmountObject.put("其他结算", oAmount);
    }

    public String getStringCellValue(XSSFCell xssfCell) {
        if (xssfCell == null) {
            return "";
        }
        if (xssfCell.getCellType() == CellType.NUMERIC) {
            return String.valueOf(xssfCell.getNumericCellValue());
        } else if (xssfCell.getCellType() == CellType.BOOLEAN) {
            return String.valueOf(xssfCell.getBooleanCellValue());
        } else {
            return xssfCell.getStringCellValue();
        }
    }
}
