package com.ruoyi.web.controller.finance;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.AmountStatics;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Shawn
 */
@RestController
@RequestMapping("/finance")
public class StaticsController {

    @Autowired
    private SysDeptMapper deptMapper;

    @PreAuthorize("@ss.hasPermi('finance:statics')")
    @GetMapping("/getAllUnits")
    public List<String> getAllUnits(){
        List<String> list = deptMapper.selectUnitsList();
        return list;
    }


    @PreAuthorize("@ss.hasPermi('finance:statics')")
    @GetMapping("/getDayFinanceStatics")
    public AjaxResult getDayFinanceStatics(){
        List<String> units = deptMapper.selectUnitsList();
        List<String> monthsBetween = DateUtils.getMonthsBetween(DateUtils.getFullYear() + "-01", DateUtils.getFullYearAndMonth().substring(0, 4) + "-" + DateUtils.getFullYearAndMonth().substring(4, 6));
        String allStaticsInfo = getAllStaticsInfo();
        List<AmountStatics> amountStaticsList = JSONObject.parseArray(allStaticsInfo, AmountStatics.class);
        List<AmountStatics> finalAmountStatics = new ArrayList<>();
        for (String unit : units) {
            AmountStatics amountStatics = new AmountStatics();
            amountStatics.setCost(new BigDecimal(0));
            amountStatics.setIncome(new BigDecimal(0));
            amountStatics.setYearMonth(DateUtils.getFullYear()+"年01月"+"至"+DateUtils.getFullYearAndMonth().substring(0,4)+"年"+DateUtils.getFullYearAndMonth().substring(4,6)+"月");
            amountStatics.setUnit(unit);
            for (String month : monthsBetween) {
                month = month.replace("-","");
                for (AmountStatics amountStatics1 : amountStaticsList) {
                    if (amountStatics1.getYearMonth().equals(month) && amountStatics1.getUnit().equals(unit)){
                        amountStatics.setCost(amountStatics.getCost().add(amountStatics1.getCost()));
                        amountStatics.setIncome(amountStatics.getIncome().add(amountStatics1.getIncome()));
                    }
                }
            }
            amountStatics.setNetProfit(amountStatics.getIncome().subtract(amountStatics.getCost()));
            if (amountStatics.getIncome().doubleValue() == 0){
                amountStatics.setNetProfitPrecent(new BigDecimal(0));
            }else{
                amountStatics.setNetProfitPrecent(amountStatics.getIncome().subtract(amountStatics.getCost()).divide(amountStatics.getIncome(),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
            }
            finalAmountStatics.add(amountStatics);
        }
        return AjaxResult.success(finalAmountStatics);
    }

    @PreAuthorize("@ss.hasPermi('finance:statics')")
    @GetMapping("/getFinanceStatics/{unitId}/{fromTo}")
    public AjaxResult getFinanceStatics(@PathVariable String unitId,@PathVariable String fromTo){
        List<String> monthBetween = getMonthBetween(fromTo.split(",")[0], fromTo.split(",")[1]).stream().peek(x -> x = x.replace("-", "")).collect(Collectors.toList());
        List<String> finalMonthBetween = new ArrayList<>();
        List<AmountStatics> finalAmount = new ArrayList<>();
        for (String s : monthBetween) {
            finalMonthBetween.add(s.replace("-",""));
        }
        int flag = 0;
        for (String s : finalMonthBetween) {
            if (Integer.parseInt(s) > Integer.parseInt(DateUtils.getFullYearAndMonth())){
                return AjaxResult.error("不能查询未来的数据");
            }
            flag++;
        }
        if(flag <= 12){

            String allStaticsInfo = getAllStaticsInfo();
            List<AmountStatics> amountStaticsList = JSONObject.parseArray(allStaticsInfo, AmountStatics.class);
//            System.out.println(amountStaticsList);

            for (String unit : unitId.split(",")) {
                AmountStatics amountStatics = new AmountStatics();
                amountStatics.setCost(new BigDecimal(0));
                amountStatics.setIncome(new BigDecimal(0));
                amountStatics.setYearMonth(DateUtils.getFullYear()+"年01月"+"至"+DateUtils.getFullYearAndMonth().substring(0,4)+"年"+DateUtils.getFullYearAndMonth().substring(4,6)+"月");
                amountStatics.setUnit(unit);
                for (String month : finalMonthBetween) {
                    month = month.replace("-","");
                    for (AmountStatics amountStatics1 : amountStaticsList) {
                        if (amountStatics1.getYearMonth().equals(month) && amountStatics1.getUnit().equals(unit)){
                            amountStatics.setCost(amountStatics.getCost().add(amountStatics1.getCost()));
                            amountStatics.setIncome(amountStatics.getIncome().add(amountStatics1.getIncome()));
                        }
                    }
                }
                amountStatics.setNetProfit(amountStatics.getIncome().subtract(amountStatics.getCost()));
                if (amountStatics.getIncome().doubleValue() == 0){
                    amountStatics.setNetProfitPrecent(new BigDecimal(0));
                }else{
                    amountStatics.setNetProfitPrecent(amountStatics.getIncome().subtract(amountStatics.getCost()).divide(amountStatics.getIncome(),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
                }
                finalAmount.add(amountStatics);
            }

            return AjaxResult.success(finalAmount);
        }else{
            return AjaxResult.error("只能查询一年以内的数据");
        }
    }

    public static String getAllStaticsInfo(){
//        Path path = Paths.get("H:\\AllStatics.txt");
        Path path = Paths.get("/usr/local/src/AllStatics.txt");
        byte[] data = new byte[0];
        try {
            data = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = new String(data, StandardCharsets.UTF_8);
        return result;
    }


    public static List<String> getMonthBetween(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
        try {
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();

            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }

            // 实现排序方法
            Collections.sort(result, new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    String str1 = (String) o1;
                    String str2 = (String) o2;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                    Date date1 = null;
                    Date date2 = null;
                    try {
                        date1 = format.parse(str1);
                        date2 = format.parse(str2);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if (date2.compareTo(date1) > 0) {
                        return -1;
                    }
                    return 1;
                }
            });
        }catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }


}
