package com.ruoyi.pay.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.ruoyi.pay.domain.PayButie;
import com.ruoyi.pay.domain.PayEmployeeInfo;
import com.ruoyi.pay.domain.bo.PayButieBo;
import com.ruoyi.pay.domain.bo.PayEmployeeInfoBo;
import com.ruoyi.pay.domain.vo.*;
import com.ruoyi.pay.service.IPayButieService;
import com.ruoyi.pay.service.IPayEmployeeInfoService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pay.domain.bo.PayButieEmplyeeBo;
import com.ruoyi.pay.service.IPayButieEmplyeeService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 补贴和员工联系
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pay/butieEmplyee")
public class PayButieEmplyeeController extends BaseController {

    private final IPayButieEmplyeeService iPayButieEmplyeeService;
    private final IPayEmployeeInfoService employeeInfoService;
    private final IPayButieService butieService;

    /**
     * 查询补贴和员工联系列表
     */
    @SaCheckPermission("pay:butieEmplyee:list")
    @GetMapping("/list")
    public TableDataInfo<PayButieEmplyeeVo> list(PayButieEmplyeeBo bo, PageQuery pageQuery) {
        return iPayButieEmplyeeService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出补贴和员工联系列表
     */
    @SaCheckPermission("pay:butieEmplyee:export")
    @Log(title = "补贴和员工联系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(PayButieEmplyeeBo bo, HttpServletResponse response) {
        List<PayButieEmplyeeVo> list = iPayButieEmplyeeService.queryList(bo);
        ExcelUtil.exportExcel(list, "补贴和员工联系", PayButieEmplyeeVo.class, response);
    }

    /**
     * 获取补贴和员工联系详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("pay:butieEmplyee:query")
    @GetMapping("/{id}")
    public R<PayButieEmplyeeVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iPayButieEmplyeeService.queryById(id));
    }

    /**
     * 新增补贴和员工联系
     */
    @SaCheckPermission("pay:butieEmplyee:add")
    @Log(title = "补贴和员工联系", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PayButieEmplyeeBo bo) {
        return toAjax(iPayButieEmplyeeService.insertByBo(bo));
    }

    /**
     * 修改补贴和员工联系
     */
    @SaCheckPermission("pay:butieEmplyee:edit")
    @Log(title = "补贴和员工联系", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PayButieEmplyeeBo bo) {
        return toAjax(iPayButieEmplyeeService.updateByBo(bo));
    }
    /**
     * 修改员工对应月份所有的补贴类型的费用
     */
    @SaCheckPermission("pay:butieEmplyee:alledit")
    @Log(title = "月度补贴修改", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/allbt")
    public R<Void> updateAllBtempByDate(@RequestBody ButieUpdateVo vo) {
        return iPayButieEmplyeeService.updateAllBtempByDate(vo);
    }

    /**
     * 删除补贴和员工联系
     *
     * @param ids 主键串
     */
    @SaCheckPermission("pay:butieEmplyee:remove")
    @Log(title = "补贴和员工联系", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iPayButieEmplyeeService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 说明：获取员工名称列表，用于工单选择工人
     *
     * @return EmployeeInfoVo 列表
     */
    @SaCheckPermission("pay:butieEmplyee:gen")
    @Log(title = "月度补贴生成", businessType = BusinessType.INSERT)
    @PostMapping("/gen")
    public R<Void> generateBuTieEmpByMonth(@RequestBody JSONObject object) {
        return iPayButieEmplyeeService.generateBuTieEmpByMonth(object.get("month", String.class), object.get("cover", Boolean.class),object.get("tenantId", Long.class));
    }

    @PostMapping("/check")
    public R<Void> checkDataExist(@RequestBody JSONObject object) {
        return iPayButieEmplyeeService.checkDataExist(object.get("month", String.class),object.get("tenantId", Long.class));
    }

    /**
     * 查询员工补贴列表
     *
     */
    @SaCheckPermission("pay:butieEmplyee:list")
    @GetMapping("/summary")
    public TableDataInfo<ButieSummaryVo> summary(PayButieEmplyeeBo bo, PageQuery pageQuery) {
        List<ButieSummaryVo> butieSummaryVos = new ArrayList<>();
        String date;
        if (null==(bo.getDate())) { // 默认查询本月的数据
            date = DateUtil.format(new Date(), "yyyy-MM");
        } else {
            date = bo.getDate();
        }
        PayEmployeeInfoBo employeeInfo = new PayEmployeeInfoBo();
        employeeInfo.setId(bo.getEmployeeId());
        employeeInfo.setTenantId(bo.getTenantId());
        TableDataInfo<PayEmployeeInfoVo> payEmployeeTableDataInfo = employeeInfoService.queryPageList(employeeInfo, pageQuery);
        if(payEmployeeTableDataInfo.getRows()!=null&&payEmployeeTableDataInfo.getRows().size()>0){
            butieSummaryVos = this.buildEmployeeInfo(payEmployeeTableDataInfo.getRows(), date);
        }
        return TableDataInfo.build(butieSummaryVos);
    }

    private List<ButieSummaryVo> buildEmployeeInfo(List<PayEmployeeInfoVo> list, String date) {
        PayButieBo pb = new PayButieBo();
        pb.setTenantId(list.get(0).getTenantId());
        List<PayButieVo> sgrButies = butieService.queryList(pb);
        ArrayList<ButieSummaryVo> summaryVos = new ArrayList<>();
        list.parallelStream().forEachOrdered(emp -> {
            ButieSummaryVo butieSummaryVo = new ButieSummaryVo();
            butieSummaryVo.setEmpName(emp.getName());
            butieSummaryVo.setDate(date);
            HashMap<String, Object> map = new HashMap<>();
            for (PayButieVo butie : sgrButies) {
                BigDecimal money = new BigDecimal(0);
                PayButieEmplyeeBo query = new PayButieEmplyeeBo();
                query.setEmployeeId(emp.getId());
                query.setButieId(butie.getId());
                query.setDate(date);
                List<PayButieEmplyeeVo> butieEmplyeeVos = iPayButieEmplyeeService.queryList(query);
                if(butieEmplyeeVos!=null&&butieEmplyeeVos.size()>0){
                    money=butieEmplyeeVos.get(0).getMoney();
                    HashMap<String, Object> inMap = new HashMap<>();
                    inMap.put("btid", butie.getId());
                    inMap.put("money",money);
                    map.put(butie.getName(), inMap);
                }
            }
            if(map.isEmpty()){
            //没找到员工查询月的补贴数据 ，不添加数据
            }else{
                butieSummaryVo.setButieMap(map);
                butieSummaryVo.setEdit(false);
                butieSummaryVo.setEmpId(emp.getId());
                summaryVos.add(butieSummaryVo);
            }
        });
        return summaryVos;
    }

}
