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

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.mes.controller.admin.organization.vo.OrganizationListReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.orgworker.vo.OrgWorkerPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.orgworker.vo.OrgWorkerRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.orgworker.vo.OrgWorkerSaveReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportDetailSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.orgworker.OrgWorkerDO;
import cn.iocoder.yudao.module.mes.service.organization.OrganizationService;
import cn.iocoder.yudao.module.mes.service.orgworker.OrgWorkerService;
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.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
@Tag(name = "管理后台 - 工位安排")
@RestController
@RequestMapping("/mes/org-worker")
@Validated
public class OrgWorkerController {

    @Resource
    private OrgWorkerService orgWorkerService;

    @PostMapping("/create")
    @Operation(summary = "创建工位安排")
    //@PreAuthorize("@ss.hasPermission('mes:org-worker:create')")
    public CommonResult<Long> createOrgWorker(@Valid @RequestBody OrgWorkerSaveReqVO createReqVO) {
        return success(orgWorkerService.createOrgWorker(createReqVO));
    }
    @GetMapping("/createWorker")
    @Operation(summary = "工位多日期派工")
    public CommonResult<Long> createWorker(@Valid OrgWorkerSaveReqVO createReqVO) {
        return success(orgWorkerService.createOrgWorker(createReqVO));
    }
    @PutMapping("/update")
    @Operation(summary = "更新工位安排")
    //@PreAuthorize("@ss.hasPermission('mes:org-worker:update')")
    public CommonResult<Boolean> updateOrgWorker(@Valid @RequestBody OrgWorkerSaveReqVO updateReqVO) {
        orgWorkerService.updateOrgWorker(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工位安排")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('mes:org-worker:delete')")
    public CommonResult<Boolean> deleteOrgWorker(@RequestParam("id") Long id) {
        orgWorkerService.deleteOrgWorker(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工位安排")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('mes:org-worker:query')")
    public CommonResult<OrgWorkerRespVO> getOrgWorker(@RequestParam("id") Long id) {
        OrgWorkerDO orgWorker = orgWorkerService.getOrgWorker(id);
        return success(BeanUtils.toBean(orgWorker, OrgWorkerRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得个人工位安排分页")
    public CommonResult<PageResult<OrgWorkerRespVO>> getOrgWorkerPage(@Valid OrgWorkerPageReqVO pageReqVO) {
        PageResult<OrgWorkerRespVO> pageResult = orgWorkerService.getOrgWorkerPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工位安排 Excel")
    //@PreAuthorize("@ss.hasPermission('mes:org-worker:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportOrgWorkerExcel(@Valid OrgWorkerPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OrgWorkerRespVO> list = orgWorkerService.getOrgWorkerPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工位安排.xls", "数据", OrgWorkerRespVO.class,
                        list);
    }
    @Resource
    private OrganizationService organizationService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private WorkTeamService workTeamService;

    /**个人报工，获取某日期当前用户绑定的工位情况**/
    @GetMapping("/getPersonal")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<OrganizationDO>> getPersonal(@Valid ProduceReportDetailSaveReqVO 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);
        List<Long> ids = orgWorkers.stream().map(OrgWorkerDO::getOrgId).collect(Collectors.toList());
        List<OrganizationDO> list = organizationService.getList(ids);
        return success(list);
    }
    /**代替报工，获取某日期某用户绑定的工位情况**/
    @GetMapping("/getOtherPersonal")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<OrganizationDO>> getOtherPersonal(@Valid ProduceReportDetailSaveReqVO reqVO) {
        OrgWorkerPageReqVO pageReqVO = new OrgWorkerPageReqVO().setOrgType(reqVO.getOrgType()).setGroupType(reqVO.getGroupType());
        pageReqVO.setWorkDate(DateUtils.getDateRange(reqVO.getReportDate()));

        List<OrgWorkerDO> orgWorkers = orgWorkerService.getOrgWorkerByReportResVo(pageReqVO);
        List<Long> ids = orgWorkers.stream().map(OrgWorkerDO::getOrgId).collect(Collectors.toList());
        List<OrganizationDO> list = organizationService.getList(ids);
        return success(list);
    }

    /**代替报工，用户列表**/
    @GetMapping("/getOtherPersonalUser")
    @Operation(summary = "获得用户列表")
    public CommonResult<List<AdminUserRespDTO>> getOtherPersonalUser(@Valid ProduceReportDetailSaveReqVO reqVO) {
        OrgWorkerPageReqVO pageReqVO = new OrgWorkerPageReqVO().setOrgType(reqVO.getOrgType()).setGroupType(reqVO.getGroupType());
        pageReqVO.setWorkDate(DateUtils.getDateRange(reqVO.getReportDate()));
        pageReqVO.setWorkerId(reqVO.getUserId());

        OrganizationListReqVO listReqVO = new OrganizationListReqVO().setOrgType(reqVO.getOrgType());
        List<OrganizationDO> orgList = organizationService.getOrganizationList(listReqVO);
        List<Long> orgIds = orgList.stream().map(OrganizationDO::getId).collect(Collectors.toList());
        pageReqVO.setOrgIds(orgIds);

        List<OrgWorkerDO> list = orgWorkerService.getOrgWorkerByReportResVo(pageReqVO);
        List<Long> ids = list.stream().map(OrgWorkerDO::getWorkerId).collect(Collectors.toList());
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(ids);
        return success(new ArrayList<>(userMap.values()));
    }

    /**个人报工，获取某日期当前用户绑定的工位情况**/
    @GetMapping("/getOrgWorkerRespVO")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<OrgWorkerRespVO>> getOrgWorkerRespVO(@Valid ProduceReportDetailSaveReqVO 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( orgWorkerService.buildVOList(orgWorkers));
    }
    /**代替报工，获取某日期某用户绑定的工位情况**/
    @GetMapping("/getOtherOrgWorkerRespVO")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<OrgWorkerRespVO>> getOtherOrgWorkerRespVO(@Valid ProduceReportDetailSaveReqVO reqVO) {
        OrgWorkerPageReqVO pageReqVO = new OrgWorkerPageReqVO().setOrgType(reqVO.getOrgType()).setGroupType(reqVO.getGroupType());
        pageReqVO.setWorkDate(DateUtils.getDateRange(reqVO.getReportDate()));
        pageReqVO.setWorkerId(reqVO.getUserId());

        List<OrgWorkerDO> orgWorkers = orgWorkerService.getOrgWorkerByReportResVo(pageReqVO);

        return success(orgWorkerService.buildVOList(orgWorkers));
    }

    /**个人报工，获取某日期当前用户绑定的工位情况**/
    @GetMapping("/getOrgWorkerListByOrgId")
    @Operation(summary = "获得工位安排")
    public CommonResult<List<OrgWorkerRespVO>> getOrgWorkerListByOrgId(@RequestParam("orgId") Long orgId) {
        OrganizationDO org = organizationService.getOrganization(orgId);
        OrgWorkerRespVO respVO = new OrgWorkerRespVO().setOrgId(orgId).setOrgName(org.getName()).setOrgType(org.getOrgType());
        List<OrgWorkerRespVO> list = new ArrayList<>();
        list.add(respVO);
        return success(list);
    }
}