package com.ruoyi.web.controller.buyerapi;

import java.io.IOException;
import java.math.BigDecimal;
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.IBuyerDeviceWorkhourMonthService;
import com.ruoyi.buyerapi.service.IBuyerProjectService;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.IBuyerDeviceWorkhourService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备工时分摊记录Controller
 *
 * @author ruoyi
 * @date 2022-09-22
 */
@RestController
@RequestMapping("/buyer/deviceworkhour")
public class BuyerDeviceWorkhourController extends BaseController
{
    @Autowired
    private IBuyerDeviceWorkhourService buyerDeviceWorkhourService;

    @Autowired
    private IBuyerDeviceWorkhourMonthService buyerDeviceWorkhourMonthService;

    @Autowired
    private IBuyerProjectService buyerProjectService;

    /**
     * 查询设备工时分摊记录列表
     */
    @PreAuthorize("@ss.hasPermi('buyer:deviceworkhour:list')")
    @GetMapping("/list")
    public TableDataInfo list(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        startPage();
        buyerDeviceWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<BuyerDeviceWorkhour> list = buyerDeviceWorkhourService.selectBuyerDeviceWorkhourList(buyerDeviceWorkhour);
        return getDataTable(list);
    }

    /**
     * 查询设备工作时间列表
     */
    @GetMapping("/workDatelist")
    public TableDataInfo workDatelist(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        buyerDeviceWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<String> list = buyerDeviceWorkhourService.workDatelist(buyerDeviceWorkhour);
        return getDataTable(list);
    }

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


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

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

    /**
     * 新增设备工时分摊记录
     */
    @PreAuthorize("@ss.hasPermi('buyer:deviceworkhour:add')")
    @Log(title = "设备工时分摊记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        buyerDeviceWorkhour.setId(IdUtil.simpleUUID());
        buyerDeviceWorkhour.setCreateBy(getUsername());
        return toAjax(buyerDeviceWorkhourService.insertBuyerDeviceWorkhour(buyerDeviceWorkhour));
    }

    /**
     * 修改设备工时分摊记录
     */
    @PreAuthorize("@ss.hasPermi('buyer:deviceworkhour:edit')")
    @Log(title = "设备工时分摊记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        buyerDeviceWorkhour.setUpdateBy(getUsername());
        return toAjax(buyerDeviceWorkhourService.updateBuyerDeviceWorkhour(buyerDeviceWorkhour));
    }

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

    @ApiOperation(value = "下载模板文件")
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<BuyerDeviceWorkHourExcel> util = new ExcelUtil<BuyerDeviceWorkHourExcel>(BuyerDeviceWorkHourExcel.class);
        util.importTemplateExcel(response, "设备工时记录记录");
    }

    @ApiOperation(value = "导入数据")
    @PostMapping("/importTable")
    public void importTable(MultipartFile file, String projectId, String year, String month, String workDate) throws Exception {
        if(StrUtil.isEmpty(projectId) || StrUtil.isEmpty(year)
                || StrUtil.isEmpty(month) || null == workDate){
            throw new Exception("项目id、年度、月度和工作时间都不能为空！");
        }
        BuyerDeviceWorkhour _bean = new BuyerDeviceWorkhour();
        _bean.setProjectId(projectId);
        _bean.setWorkDate(DateUtil.parseDate(workDate));
        ExcelUtil<BuyerDeviceWorkHourExcel> util = new ExcelUtil<>(BuyerDeviceWorkHourExcel.class);
        List<BuyerDeviceWorkHourExcel> deviceList = util.importExcel(file.getInputStream());
        buyerDeviceWorkhourService.deleteBuyerDeviceWorkhour(_bean);
        for(BuyerDeviceWorkHourExcel buyerDeviceWorkHourExcel : deviceList){
            BuyerDeviceWorkhour buyerDeviceWorkhour = BeanUtil.copyProperties(buyerDeviceWorkHourExcel, BuyerDeviceWorkhour.class);
            buyerDeviceWorkhour.setId(IdUtil.simpleUUID());
            buyerDeviceWorkhour.setYear(Long.parseLong(year));
            buyerDeviceWorkhour.setMonth(Long.parseLong(month));
            buyerDeviceWorkhour.setProjectId(projectId);
            buyerDeviceWorkhour.setCompanyId(SecurityUtils.getCompanyId());
            buyerDeviceWorkhour.setWorkDate(DateUtil.parseDate(workDate));
            buyerDeviceWorkhour.setCreateBy(SecurityUtils.getUsername());
            buyerDeviceWorkhour.setUpdateBy(SecurityUtils.getUsername());
            // 1:指定为导入模式
            buyerDeviceWorkhour.setType("1");
            buyerDeviceWorkhourService.insertBuyerDeviceWorkhour(buyerDeviceWorkhour);
        }
    }

    @Log(title = "批量更新员工工时月报", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/batchUpdate")
    public AjaxResult batchUpdate(Long year, Long month)
    {
        if(null != year && null != month){
            BuyerDeviceWorkhourByProject _bean = new BuyerDeviceWorkhourByProject();
            _bean.setYear(year);
            _bean.setMonth(month);
            _bean.setCompanyId(SecurityUtils.getCompanyId());
            List<BuyerDeviceWorkhourByProject> deviceWorkhourByProject = buyerDeviceWorkhourService.listGrroupYearMonth(_bean);
            for (BuyerDeviceWorkhourByProject buyerDeviceWorkhourByProject : deviceWorkhourByProject) {
                BuyerDeviceWorkhourMonth buyerDeviceWorkhourMonth = BeanUtil.copyProperties(buyerDeviceWorkhourByProject, BuyerDeviceWorkhourMonth.class);
                buyerDeviceWorkhourMonth.setCompanyId(SecurityUtils.getCompanyId());
                // 先删除
                buyerDeviceWorkhourMonthService.deleteBuyerDeviceWorkhourMonth(buyerDeviceWorkhourMonth);
                // 更新工时
                buyerDeviceWorkhourMonth.setId(IdUtil.simpleUUID());
                buyerDeviceWorkhourMonth.setCreateBy(SecurityUtils.getUsername());
                buyerDeviceWorkhourMonth.setUpdateBy(SecurityUtils.getUsername());
                buyerDeviceWorkhourMonthService.insertBuyerDeviceWorkhourMonth(buyerDeviceWorkhourMonth);
            }
            return AjaxResult.success();
        }else{
            return AjaxResult.error("年份和月份不能为空！");
        }
    }

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

    /**
     * 查询员工工时分摊月报详情(根据年月查询)-导出
     */
    @PostMapping("/listForYearMonthExport")
    public void listForYearMonthExport(HttpServletResponse response, BuyerDeviceWorkhour buyerDeviceWorkhour) throws IOException {
        buyerDeviceWorkhour.setCompanyId(SecurityUtils.getCompanyId());
        List<Map<String, Object>> list = buyerDeviceWorkhourService.listForYearMonth(buyerDeviceWorkhour);
        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);
    }

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

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