package com.ruoyi.web.controller.buyerapi;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ruoyi.buyerapi.domain.*;
import com.ruoyi.buyerapi.service.IBuyerEmpWorkhourMonthService;
import com.ruoyi.buyerapi.service.IBuyerProjectService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
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.buyerapi.service.IBuyerEmpWorkhourService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 员工工时分摊记录Controller
 *
 * @author ruoyi
 * @date 2022-09-22
 */
@RestController
@RequestMapping("/buyer/empworkhour")
public class BuyerEmpWorkhourController extends BaseController
{
    @Autowired
    private IBuyerEmpWorkhourService buyerEmpWorkhourService;

    @Autowired
    private IBuyerEmpWorkhourMonthService buyerEmpWorkhourMonthService;

    @Autowired
    private IBuyerProjectService buyerProjectService;

    /**
     * 查询员工工时分摊记录列表
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:list')")
    @GetMapping("/list")
    public TableDataInfo list(BuyerEmpWorkhour buyerEmpWorkhour)
    {
        startPage();
        buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<BuyerEmpWorkhour> list = buyerEmpWorkhourService.selectBuyerEmpWorkhourList(buyerEmpWorkhour);
        return getDataTable(list);
    }

    /**
     * 查询员工工作时间列表
     */
    @GetMapping("/workDatelist")
    public TableDataInfo workDatelist(BuyerEmpWorkhour buyerEmpWorkhour)
    {
        buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<String> list = buyerEmpWorkhourService.workDatelist(buyerEmpWorkhour);
        return getDataTable(list);
    }

    /**
     * 根据项目统计工时
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:list')")
    @GetMapping("/listGrroupProject")
    public TableDataInfo listGrroupProject(BuyerEmpWorkhourByProject buyerEmpWorkhour)
    {
        startPage();
        buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<BuyerEmpWorkhourByProject> list = buyerEmpWorkhourService.listGrroupProject(buyerEmpWorkhour);
        return getDataTable(list);
    }

    /**
     * 查询某个项目的年月工时统计列表
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:list')")
    @GetMapping("/listByProjectId")
    public TableDataInfo listByProjectId(String projectId)
    {
        List<BuyerEmpWorkhourByProject> list = buyerEmpWorkhourService.listByProjectId(projectId);
        return getDataTable(list);
    }

    /**
     * 导出员工工时分摊记录列表
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:export')")
    @Log(title = "员工工时分摊记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BuyerEmpWorkhour buyerEmpWorkhour)
    {
        // 获取项目名称
        BuyerProject project = buyerProjectService.selectBuyerProjectById(buyerEmpWorkhour.getProjectId());
        List<BuyerEmpWorkhour> list = buyerEmpWorkhourService.selectBuyerEmpWorkhourList(buyerEmpWorkhour);
        for(BuyerEmpWorkhour wkhour : list){
            wkhour.setTypeName("1".equals(wkhour.getType()) ? "表格导入" : "手动填写");
            wkhour.setProjectName(project.getName());
        }
        ExcelUtil<BuyerEmpWorkhour> util = new ExcelUtil<BuyerEmpWorkhour>(BuyerEmpWorkhour.class);
        util.exportExcel(response, list, "员工工时分摊记录数据");
    }

    /**
     * 获取员工工时分摊记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(buyerEmpWorkhourService.selectBuyerEmpWorkhourById(id));
    }

    /**
     * 新增员工工时分摊记录
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:add')")
    @Log(title = "员工工时分摊记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BuyerEmpWorkhour buyerEmpWorkhour)
    {
        buyerEmpWorkhour.setId(IdUtil.simpleUUID());
        buyerEmpWorkhour.setCreateBy(getUsername());
        return toAjax(buyerEmpWorkhourService.insertBuyerEmpWorkhour(buyerEmpWorkhour));
    }

    /**
     * 修改员工工时分摊记录
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:edit')")
    @Log(title = "员工工时分摊记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BuyerEmpWorkhour buyerEmpWorkhour)
    {
        buyerEmpWorkhour.setUpdateBy(getUsername());
        return toAjax(buyerEmpWorkhourService.updateBuyerEmpWorkhour(buyerEmpWorkhour));
    }

    /**
     * 删除员工工时分摊记录
     */
    @PreAuthorize("@ss.hasPermi('buyer:empworkhour:remove')")
    @Log(title = "员工工时分摊记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(buyerEmpWorkhourService.deleteBuyerEmpWorkhourByIds(ids));
    }

    @ApiOperation(value = "下载模板文件")
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<BuyerEmpWorkHourExcel> util = new ExcelUtil<BuyerEmpWorkHourExcel>(BuyerEmpWorkHourExcel.class);
        util.importTemplateExcel(response, "员工工时月考勤导入模板");
    }

    @ApiOperation(value = "导入数据")
    @PostMapping("/importTable")
    public void importTable(MultipartFile file, String projectId, String year, String month) throws Exception {
        if(StrUtil.isEmpty(projectId) || StrUtil.isEmpty(year)
                || StrUtil.isEmpty(month)){
            throw new Exception("项目id、年度、月度都不能为空！");
        }
        BuyerEmpWorkhour _bean = new BuyerEmpWorkhour();
        _bean.setProjectId(projectId);
        _bean.setYear(Long.parseLong(year));
        _bean.setMonth(Long.parseLong(month));
        ExcelUtil<BuyerEmpWorkHourExcel> util = new ExcelUtil<>(BuyerEmpWorkHourExcel.class);
        List<BuyerEmpWorkHourExcel> empList = util.importExcel(file.getInputStream());
        buyerEmpWorkhourService.deleteBuyerEmpWorkhour(_bean);
        for(BuyerEmpWorkHourExcel buyerEmpWorkHourExcel : empList){
            BuyerEmpWorkhour buyerEmpWorkHour = BeanUtil.copyProperties(buyerEmpWorkHourExcel, BuyerEmpWorkhour.class);
            buyerEmpWorkHour.setId(IdUtil.simpleUUID());
            buyerEmpWorkHour.setYear(Long.parseLong(year));
            buyerEmpWorkHour.setMonth(Long.parseLong(month));
            buyerEmpWorkHour.setProjectId(projectId);
            buyerEmpWorkHour.setCompanyId(SecurityUtils.getCompanyId());
            buyerEmpWorkHour.setCreateBy(SecurityUtils.getUsername());
            buyerEmpWorkHour.setUpdateBy(SecurityUtils.getUsername());
            // 1:指定为导入模式
            buyerEmpWorkHour.setType("1");
            buyerEmpWorkhourService.insertBuyerEmpWorkhour(buyerEmpWorkHour);
        }
    }

    @ApiOperation(value = "批量新增")
    @PostMapping("/batchAdd")
    public void batchAdd(@RequestParam String projectId, @RequestParam String year, @RequestParam String month,
                         @RequestParam String workDate,
                         @RequestBody List<BuyerEmpWorkhour> buyerEmpWorkhours) throws Exception {
        if(StrUtil.isEmpty(projectId) || StrUtil.isEmpty(year)
                || StrUtil.isEmpty(month) || null == workDate){
            throw new Exception("项目id、年度、月度和工作时间都不能为空！");
        }
        BuyerEmpWorkhour _bean = new BuyerEmpWorkhour();
        _bean.setProjectId(projectId);
        _bean.setWorkDate(DateUtil.parseDate(workDate));
        buyerEmpWorkhourService.deleteBuyerEmpWorkhour(_bean);
        for(BuyerEmpWorkhour buyerEmpWorkhour : buyerEmpWorkhours){
            buyerEmpWorkhour.setId(IdUtil.simpleUUID());
            buyerEmpWorkhour.setYear(Long.parseLong(year));
            buyerEmpWorkhour.setMonth(Long.parseLong(month));
            buyerEmpWorkhour.setProjectId(projectId);
            buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
            buyerEmpWorkhour.setWorkDate(DateUtil.parseDate(workDate));
            buyerEmpWorkhour.setCreateBy(SecurityUtils.getUsername());
            buyerEmpWorkhour.setUpdateBy(SecurityUtils.getUsername());
            // 1:指定为手动模式
            buyerEmpWorkhour.setType("0");
            buyerEmpWorkhourService.insertBuyerEmpWorkhour(buyerEmpWorkhour);
        }
    }

    @Log(title = "批量更新员工工时月报", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/batchUpdate")
    public AjaxResult batchUpdate(@RequestBody List<BuyerEmpWorkhour> buyerEmpWorkhours)
    {
        if(null != buyerEmpWorkhours && buyerEmpWorkhours.size() > 0){
            // 工时合计
            BigDecimal totalWork = new BigDecimal(0);
            // 成本合计
            BigDecimal totalCost = new BigDecimal(0);

            for(int i = 0; i < buyerEmpWorkhours.size(); i++){
                BuyerEmpWorkhour buyerEmpWorkhour = buyerEmpWorkhours.get(i);
                buyerEmpWorkhour.setUpdateBy(SecurityUtils.getUsername());
                buyerEmpWorkhourService.updateBuyerEmpWorkhour(buyerEmpWorkhour);
                totalWork = totalWork.add(buyerEmpWorkhour.getCost());
                totalCost = totalCost.add(buyerEmpWorkhour.getWages().add(buyerEmpWorkhour.getSocialSecurity()));
            }
            // 先删除当前月数据
            BuyerEmpWorkhourMonth buyerEmpWorkhourMonth = new BuyerEmpWorkhourMonth();
            buyerEmpWorkhourMonth.setCompanyId(SecurityUtils.getCompanyId());
            buyerEmpWorkhourMonth.setYear(buyerEmpWorkhours.get(0).getYear());
            buyerEmpWorkhourMonth.setMonth(buyerEmpWorkhours.get(0).getMonth());
            buyerEmpWorkhourMonthService.deleteBuyerEmpWorkhourMonth(buyerEmpWorkhourMonth);
            // 更新员工工时
            buyerEmpWorkhourMonth.setId(IdUtil.simpleUUID());
            buyerEmpWorkhourMonth.setCreateBy(SecurityUtils.getUsername());
            buyerEmpWorkhourMonth.setUpdateBy(SecurityUtils.getUsername());
            buyerEmpWorkhourMonth.setTotalWork(totalWork);
            buyerEmpWorkhourMonth.setTotalCost(totalCost);
            buyerEmpWorkhourMonthService.insertBuyerEmpWorkhourMonth(buyerEmpWorkhourMonth);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("员工工时列表不能为空！");
        }
    }

    /**
     * 查询员工工时分摊月报详情(根据年月查询)
     */
    @GetMapping("/listForYearMonth")
    public TableDataInfo listForYearMonth(BuyerEmpWorkhour buyerEmpWorkhour)
    {
        buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<Map<String, Object>> list = buyerEmpWorkhourService.listForYearMonth(buyerEmpWorkhour);
        return getDataTable(list);
    }

    /**
     * 查询员工工时分摊月报详情(根据年月查询)-导出
     */
    @PostMapping("/listForYearMonthExport")
    public void listForYearMonthExport(HttpServletResponse response, BuyerEmpWorkhour buyerEmpWorkhour) throws IOException {
        buyerEmpWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<Map<String, Object>> list = buyerEmpWorkhourService.listForYearMonth(buyerEmpWorkhour);
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=员工工时分摊月报详情.xlsx");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }
}
