package cn.iocoder.yudao.module.mes.controller.admin.baogongrecord;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.mes.controller.admin.itemrequisition.vo.ItemRequisitionRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.itemrequisition.ItemRequisitionDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.plan.PlanDO;
import cn.iocoder.yudao.module.mes.service.plan.PlanService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.mes.controller.admin.baogongrecord.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.baogongrecord.BaogongRecordDO;
import cn.iocoder.yudao.module.mes.service.baogongrecord.BaogongRecordService;

@Tag(name = "管理后台 - 报工")
@RestController
@RequestMapping("/mes/baogong-record")
@Validated
public class BaogongRecordController {

    @Resource
    private BaogongRecordService baogongRecordService;

    @Resource
    private PlanService planService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建报工")
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:create')")
    public CommonResult<Long> createBaogongRecord(@Valid @RequestBody BaogongRecordSaveReqVO createReqVO) {
        PlanDO plan = planService.getPlan(createReqVO.getPlanId());
        if (plan.getWangongNumber() == null) {
            plan.setWangongNumber(0L);
        }
        if (plan.getPassNumber() == null) {
            plan.setPassNumber(0L);
        }
        if (plan.getNoPassNumber() == null) {
            plan.setNoPassNumber(0L);
        }
        plan.setWangongNumber(plan.getWangongNumber() + createReqVO.getNum() + createReqVO.getNoPassNum());
        plan.setPassNumber(plan.getPassNumber() + createReqVO.getNum());
        plan.setNoPassNumber(plan.getNoPassNumber() + createReqVO.getNoPassNum());
        if (plan.getWangongNumber() <= 0) {
            plan.setPassRate(BigDecimal.ZERO);
        } else {
            BigDecimal rate = new BigDecimal(plan.getPassNumber())
                    .divide(new BigDecimal(plan.getWangongNumber()), 4, RoundingMode.HALF_UP);
            plan.setPassRate(rate.multiply(new BigDecimal("100")));
        }
        planService.updatePlan(BeanUtils.toBean(plan, PlanSaveReqVO.class));
        return success(baogongRecordService.createBaogongRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新报工")
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:update')")
    public CommonResult<Boolean> updateBaogongRecord(@Valid @RequestBody BaogongRecordSaveReqVO updateReqVO) {
        baogongRecordService.updateBaogongRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除报工")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:delete')")
    public CommonResult<Boolean> deleteBaogongRecord(@RequestParam("id") Long id) {
        baogongRecordService.deleteBaogongRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报工")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:query')")
    public CommonResult<BaogongRecordRespVO> getBaogongRecord(@RequestParam("id") Long id) {
        BaogongRecordDO baogongRecord = baogongRecordService.getBaogongRecord(id);
        return success(BeanUtils.toBean(baogongRecord, BaogongRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得报工分页")
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:query')")
    public CommonResult<PageResult<BaogongRecordRespVO>> getBaogongRecordPage(@Valid BaogongRecordPageReqVO pageReqVO) {
        PageResult<BaogongRecordDO> pageResult = baogongRecordService.getBaogongRecordPage(pageReqVO);
        return success(new PageResult<>(buildVOList(pageResult.getList()), pageResult.getTotal()));
    }

    private List<BaogongRecordRespVO> buildVOList(List<BaogongRecordDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(list, baogong -> Long.parseLong(baogong.getCreator())));

        return BeanUtils.toBean(list, BaogongRecordRespVO.class, item -> {
            MapUtils.findAndThen(userMap, Long.parseLong(item.getCreator()), user -> item.setCreator(user.getUsername()));
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出报工 Excel")
    @PreAuthorize("@ss.hasPermission('mes:baogong-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBaogongRecordExcel(@Valid BaogongRecordPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BaogongRecordDO> list = baogongRecordService.getBaogongRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "报工.xls", "数据", BaogongRecordRespVO.class,
                        BeanUtils.toBean(list, BaogongRecordRespVO.class));
    }

}