package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.BudgetSettleBean;
import cn.palmte.work.bean.EstimateSettleBean;
import cn.palmte.work.bean.FormerBean;
import cn.palmte.work.bean.SettleBean;
import cn.palmte.work.model.*;
import cn.palmte.work.service.ProjectBudgetService;
import cn.palmte.work.service.ProjectEstimateService;
import cn.palmte.work.service.ProjectService;
import cn.palmte.work.service.ProjectSettleService;
import cn.palmte.work.utils.DateKit;
import cn.palmte.work.utils.FreeMarkerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.number.NumberStyleFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import top.jfunc.common.utils.CollectionUtil;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Yuanping Zhang
 * @date 2021/11/15
 */
@Controller
@RequestMapping("/project/settle")
public class ProjectSettleController extends BaseController{

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ProjectEstimateService projectEstimateService;

    @Autowired
    private ProjectBudgetService projectBudgetService;

    @Autowired
    private ProjectSettleService projectSettleService;

    @Autowired
    private ProjectSettleIncomeRepository projectSettleIncomeRepository;

    @Autowired
    private ProjectUserTimeRepository projectUserTimeRepository;

    @RequestMapping("/add")
    public String add(@RequestParam("id") int id, Map<String, Object> model) {
        String time = null;
        Project project = projectService.getProject(id);
        List<ProjectBudgetPlanDetail> projectBudgetPlanDetails = projectBudgetService.getProjectBudgetPlanDetails(project);
        ProjectSettleIncome projectSettleIncome = projectSettleIncomeRepository.findNewByProjectId(id);
        if (projectSettleIncome != null) {
            String former = projectSettleIncome.getTime();
            Date date = DateKit.getDate(former, DateKit.DATE_FORMAT_YEAR_MONTH2);
            Calendar instance = Calendar.getInstance();
            instance.setTime(date);
            instance.set(Calendar.MONTH, instance.get(Calendar.MONTH) + 1);
            Date current = instance.getTime();
            time = DateKit.toStr(current, DateKit.DATE_FORMAT_YEAR_MONTH2);
            model.put("time", time);
            model.put("formerBean", projectSettleService.getFormerSettle(project, time));
        } else {
            time = DateKit.toStr(project.getStartDate(), DateKit.DATE_FORMAT_YEAR_MONTH2);

            model.put("time", time);
            model.put("formerBean", new FormerBean());
        }

        model.put("project", project);
        model.put("estimateBean", projectEstimateService.getEstimate(project));
        model.put("budgetBean", projectBudgetService.getBudget(project));
        List<ProjectUserTime> projectUserTimes = projectUserTimeRepository.findByProjectIdAndTime(project.getId(), time);
        if(CollectionUtil.isNotEmpty(projectUserTimes)){
            BigDecimal result = projectUserTimes.stream().map((ProjectUserTime t) -> t.getUserCost().multiply(t.getUserSalary())).reduce(BigDecimal.ZERO, BigDecimal::add);
            model.put("salary", result);
        } else {
            model.put("salary", new BigDecimal(0));
        }
        //现金表
        model.put("cashFlowBean", projectBudgetService.getCashFlowBean(project, projectBudgetPlanDetails));
        //freemarker可以利用的静态方法
        model.put("Utils", FreeMarkerUtil.fromStaticPackage("cn.palmte.work.utils.Utils"));
        return "admin/project_settle_add";
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam("id") int id, Map<String, Object> model) {
        Project project = projectService.getProject(id);
        ProjectSettleIncome projectSettleIncome = projectSettleIncomeRepository.findNewByProjectId(id);
        List<ProjectBudgetPlanDetail> projectBudgetPlanDetails = projectBudgetService.getProjectBudgetPlanDetails(project);
        String time = projectSettleIncome.getTime();
        model.put("time", time);
        model.put("project", project);
        model.put("estimateBean", projectEstimateService.getEstimate(project));
        model.put("budgetBean", projectBudgetService.getBudget(project));
        model.put("formerBean", projectSettleService.getFormerSettle(project, time));
        model.put("monthBean", projectSettleService.getMonthSettle(project, time));
        model.put("currentBean", projectSettleService.getCurrentSettle(project, time));
        List<ProjectUserTime> projectUserTimes = projectUserTimeRepository.findByProjectIdAndTime(project.getId(), time);
        if(CollectionUtil.isNotEmpty(projectUserTimes)){
            BigDecimal result = projectUserTimes.stream().map((ProjectUserTime t) -> t.getUserCost().multiply(t.getUserSalary())).reduce(BigDecimal.ZERO, BigDecimal::add);
            model.put("salary", result);
        } else {
            model.put("salary", new BigDecimal(0));
        }
        //现金表
        model.put("cashFlowBean", projectBudgetService.getCashFlowBean(project, projectBudgetPlanDetails));
        //freemarker可以利用的静态方法
        model.put("Utils", FreeMarkerUtil.fromStaticPackage("cn.palmte.work.utils.Utils"));
        return "admin/project_settle_edit";
    }

    @RequestMapping("/save")
    public String save(Project project, SettleBean settleBean, BudgetSettleBean budgetBean, EstimateSettleBean estimateBean, String time) {
        projectSettleService.save(project, settleBean, budgetBean, estimateBean, time);
        return "redirect:/project/list";
    }

    /**
     * 保存并提交审批
     * @param project
     * @param settleBean
     * @param budgetBean
     * @param estimateBean
     * @param time
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveAndApprove")
    public String saveAndApprove(Project project, SettleBean settleBean, BudgetSettleBean budgetBean, EstimateSettleBean estimateBean, String time) throws Exception{
        projectSettleService.saveAndApprove(project, settleBean, budgetBean, estimateBean, time);
        return "redirect:/project/list";
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
        webDataBinder.addCustomFormatter(new NumberStyleFormatter());
    }
}
