package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

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.CmcWage;
import com.ruoyi.oa.service.ICmcWageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 员工工资Controller
 * 
 * @author cmc
 * @date 2024-09-19
 */
@RestController
@RequestMapping("/oa/wage")
public class CmcWageController extends BaseController
{
    @Autowired
    private ICmcWageService cmcWageService;

    /**
     * 查询员工工资列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcWage cmcWage)
    {
        startPage();
        List<CmcWage> list = cmcWageService.selectCmcWageList(cmcWage);
        return getDataTable(list);
    }

    /**
     * 导出员工工资列表
     */
    @Log(title = "员工工资", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcWage cmcWage)
    {
        List<CmcWage> list = cmcWageService.selectCmcWageList(cmcWage);
        ExcelUtil<CmcWage> util = new ExcelUtil<CmcWage>(CmcWage.class);
        util.exportExcel(response, list, "员工工资数据");
    }

    /**
     * 获取员工工资详细信息
     */
    @GetMapping(value = "/{wageId}")
    public AjaxResult getInfo(@PathVariable("wageId") Integer wageId)
    {
        return success(cmcWageService.selectCmcWageByWageId(wageId));
    }

    /**
     * 获取员工社保公积金日均值
     */
    @GetMapping(value = "/userDayValue")
    public AjaxResult getUserDayValue(CmcWage cmcWage)
    {
        String queryYear = new SimpleDateFormat("yyyy").format(cmcWage.getPayMonth());
        cmcWage.setPayMonth(null);
        List<CmcWage> cmcWageList = cmcWageService.selectCmcWageList(cmcWage);
        BigDecimal houseFundTotal = new BigDecimal(0);
        BigDecimal socialSecurityUnitTotal = new BigDecimal(0);
        int month = 0;
        int days = 0;
        if (cmcWageList.size() > 0) {
            // 2025年4月至12月，按月除实际天数
            if (cmcWageList.size() < 9) {
                for (CmcWage wage : cmcWageList) {
                    String payMonth = new SimpleDateFormat("yyyy-MM").format(wage.getPayMonth());
                    houseFundTotal = houseFundTotal.add(wage.getHouseFund());
                    socialSecurityUnitTotal = socialSecurityUnitTotal.add(wage.getSocialSecurityUnit());
                    month ++;
                    days += YearMonth.of(2025, Integer.parseInt(payMonth.split("-")[1])).lengthOfMonth();
                }
            }
            // 2026年起，取上年日均值
            else {
                for (CmcWage wage : cmcWageList) {
                    String payMonth = new SimpleDateFormat("yyyy-MM").format(wage.getPayMonth());
                    int lastYear = Integer.parseInt(queryYear) - 1;
                    if (payMonth.split("-")[0].equals(String.valueOf(lastYear))) {
                        houseFundTotal = houseFundTotal.add(wage.getHouseFund());
                        socialSecurityUnitTotal = socialSecurityUnitTotal.add(wage.getSocialSecurityUnit());
                        month ++;
                        days += YearMonth.of(Integer.parseInt(payMonth.split("-")[0]), Integer.parseInt(payMonth.split("-")[1])).lengthOfMonth();
                    }
                }
            }
            if (month > 0) {
                cmcWage.setHouseFund(houseFundTotal.divide(new BigDecimal(days), RoundingMode.CEILING));
                cmcWage.setSocialSecurityUnit(socialSecurityUnitTotal.divide(new BigDecimal(days), RoundingMode.CEILING));
            }
        }
        return success(cmcWage);
    }

    /**
     * 新增员工工资
     */
    @Log(title = "员工工资", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcWage cmcWage)
    {
        return toAjax(cmcWageService.insertCmcWage(cmcWage));
    }

    /**
     * 上传工资excel文件
     */
    @PostMapping("/uploadSheet")
    public AjaxResult uploadWageSheet(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("文件内容为空！");
        }
        else {
            ExcelUtil<CmcWage> util = new ExcelUtil<CmcWage>(CmcWage.class);
            List<CmcWage> cmcWageList = util.importExcel(file.getInputStream());
            for (CmcWage cmcWage : cmcWageList) {
                cmcWage.setUserId(cmcWage.getUserId() + 1);
                CmcWage wage = new CmcWage();
                wage.setUserId(cmcWage.getUserId());
                wage.setPayMonth(cmcWage.getPayMonth());
                List<CmcWage> wageList = cmcWageService.selectCmcWageList(wage);
                if (wageList.size() > 0) {
                    wage.setWageId(wageList.get(0).getWageId());
                    wage.setSocialSecurityUnit(cmcWage.getSocialSecurityUnit());
                    wage.setHouseFund(cmcWage.getHouseFund());
                    cmcWageService.updateCmcWage(wage);
                }
                else
                    cmcWageService.insertCmcWage(cmcWage);
            }
            return AjaxResult.success("上传成功");
        }
    }

    /**
     * 修改员工工资
     */
    @Log(title = "员工工资", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcWage cmcWage)
    {
        return toAjax(cmcWageService.updateCmcWage(cmcWage));
    }

    /**
     * 删除员工工资
     */
    @Log(title = "员工工资", businessType = BusinessType.DELETE)
	@DeleteMapping("/{wageIds}")
    public AjaxResult remove(@PathVariable Integer[] wageIds)
    {
        return success(cmcWageService.deleteCmcWageByWageIds(wageIds));
    }

    /**
     * 删除员工工资
     */
    @Log(title = "员工工资", businessType = BusinessType.DELETE)
	@DeleteMapping("/batch/{performanceIds}")
    public AjaxResult removeBatch(@PathVariable String[] performanceIds)
    {
        return success(cmcWageService.deleteCmcWageByPerformanceIds(performanceIds));
    }
}
