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

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.app.service.AppService;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.AppOrgWorkerVO;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.AppProductVo;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.AppReportReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.AppReportSaveReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.organization.vo.ProcessTypeEnum;
import cn.iocoder.yudao.module.mes.controller.admin.orgworker.vo.OrgWorkerPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanStatusEnum;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.orgworker.OrgWorkerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.workteam.WorkTeamDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.workteam.WorkTeamDetailDO;
import cn.iocoder.yudao.module.mes.service.orgworker.OrgWorkerService;
import cn.iocoder.yudao.module.mes.service.plan.PlanService;
import cn.iocoder.yudao.module.mes.service.producereport.ProduceReportService;
import cn.iocoder.yudao.module.mes.service.workteam.WorkTeamService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "app - 工位安排")
@RestController
@RequestMapping("/mes/app/org-worker")
@Validated
public class AppOrgWorkerController {

    @Resource
    private OrgWorkerService orgWorkerService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private AppService appService;
    @Resource
    private WorkTeamService workTeamService;
    @Resource
    private PlanService planService;
    @Resource
    private ProduceReportService produceReportService;

    /**个人报工，获取某日期当前用户绑定的工位情况**/
    @GetMapping("/getOrgList")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<AppOrgWorkerVO>> getOrgWorkerRespVO(@Valid AppReportReqVO reqVO) {
        OrgWorkerPageReqVO pageReqVO = new OrgWorkerPageReqVO().setOrgType(reqVO.getOrgType()).setGroupType(reqVO.getGroupType());
        pageReqVO.setWorkDate(DateUtils.getDateRange(reqVO.getReportDate()));
        Long userId =  getLoginUserId();
        pageReqVO.setWorkerId(userId);
        List<OrgWorkerDO> orgWorkers = orgWorkerService.getOrgWorkerByReportResVo(pageReqVO);
        return success(appService.getOrgList(orgWorkers));
    }

    /**代替报工，获取某日期某用户绑定的工位情况**/
    @GetMapping("/getOtherOrgList")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<AppOrgWorkerVO>> getOtherPersonal(@Valid AppReportReqVO reqVO) {
        OrgWorkerPageReqVO pageReqVO = new OrgWorkerPageReqVO().setOrgType(reqVO.getOrgType())
                .setGroupType(reqVO.getGroupType()).setWorkerId(reqVO.getUserId());
        pageReqVO.setWorkDate(DateUtils.getDateRange(reqVO.getReportDate()));
        List<OrgWorkerDO> orgWorkers = orgWorkerService.getOrgWorkerByReportResVo(pageReqVO);
        return success(appService.getOrgList(orgWorkers));
    }

    /**代替报工，用户列表**/
    @GetMapping("/getOtherPersonalUser")
    @Operation(summary = "获得用户列表")
    public CommonResult<List<AppOrgWorkerVO>> getOtherPersonalUser(@Valid AppReportReqVO reqVO) {
        //目前代报工成员列表和工序没关系了，只和班组有关系.setTeamType(reqVO.getOrgType())
        WorkTeamDO workTeamDO = new WorkTeamDO().setIsEnable(true);
        if(reqVO.getGroupType()!=null) workTeamDO.setGroupType(reqVO.getGroupType().toString());
        List<WorkTeamDO> workTeamDOList =workTeamService.getList(workTeamDO);
        List<Long> teamIds = workTeamDOList.stream().map(WorkTeamDO::getId).collect(Collectors.toList());
        List<WorkTeamDetailDO> doList = workTeamService.getDetailByWorkTeamIds(teamIds);

        List<Long> ids = doList.stream().map(WorkTeamDetailDO::getUserId).collect(Collectors.toList());
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(ids);
        List<AdminUserRespDTO> userList = new ArrayList<>(userMap.values());
        return success(appService.getUserList(userList));
    }
    @GetMapping("/getProductList")
    @Operation(summary = "获得正在开工生产的产品")
    public CommonResult<List<AppProductVo>> getProductList() {
        List<Integer> status = new ArrayList<>();
        status.add(PlanStatusEnum.量产.getValue());
        List<ErpProductRespVO> proList = planService.getProductByPlanStatus(status);
        return success(appService.getProductList(proList));
    }
    @GetMapping("/getPlanProductList")
    @Operation(summary = "获得正在开工生产的产品以及工序的需求")
    public CommonResult<List<AppProductVo>> getPlanProductList(String orgType) {
        if(StringUtils.isEmpty(orgType))orgType= ProcessTypeEnum.成型.getValue();
        return success(appService.getPlanProductList(orgType));
    }

    @PostMapping("/createReport")
    @Operation(summary = "创建生产报工单")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:create')")
    public CommonResult<Long> createReport(@Valid @RequestBody AppReportSaveReqVO appSaveVo) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(appSaveVo.getReportDateString(), formatter);
        appSaveVo.setReportDate(localDateTime);

        ProduceReportSaveReqVO createReqVO = BeanUtils.toBean(appSaveVo,ProduceReportSaveReqVO.class);
        createReqVO.setProduceReportDetails(appSaveVo.getProduceReportDetails());

        return success(produceReportService.createProduceReport(createReqVO));
    }
}