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

import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.common.controller.admin.mold.vo.MoldRespVO;
import cn.iocoder.yudao.module.common.controller.admin.mold.vo.MoldSaveReqVO;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpStockInItemDO;
import cn.iocoder.yudao.module.erp.service.mold.MoldService;
import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo.DeviceLedgerRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo.DeviceLedgerSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.service.deviceledger.DeviceLedgerService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.util.StringUtils;
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.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

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.moldoperate.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldoperate.MoldOperateDO;
import cn.iocoder.yudao.module.mes.service.moldoperate.MoldOperateService;

@Tag(name = "管理后台 - 模具上下模")
@RestController
@RequestMapping("/mes/mold-operate")
@Validated
public class MoldOperateController {

    @Resource
    private MoldOperateService moldOperateService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private MoldService moldService;
    @Resource
    private DeviceLedgerService deviceLedgerService;


    @PostMapping("/create")
    @Operation(summary = "创建模具上下模")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:create')")
    public CommonResult<Long> createMoldOperate(@Valid @RequestBody MoldOperateSaveReqVO createReqVO) {



        if (Objects.equals(createReqVO.getOperateType(), "1")) {
            DeviceLedgerDO deviceLedger = deviceLedgerService.getDeviceLedger(createReqVO.getDeviceId());
            List<Long> idList = Arrays.stream(createReqVO.getMoldId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long id : idList) {
                MoldDO moldDO = moldService.getMold(id);
                moldDO.setMachineId(createReqVO.getDeviceId());
                moldDO.setMachineName(deviceLedger.getDeviceName());
                moldDO.setStatus(0); // 在机 0 在库 1
                moldService.updateMold(BeanUtils.toBean(moldDO, MoldSaveReqVO.class));
            }

            deviceLedger.setMoldId(createReqVO.getMoldId());
            deviceLedgerService.updateDeviceLedger(BeanUtils.toBean(deviceLedger, DeviceLedgerSaveReqVO.class));
        }  else {
            List<Long> lowerMoldId = Arrays.stream(createReqVO.getLowerMoldId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            //下模
            for (Long id : lowerMoldId) {
                MoldDO moldDO = moldService.getMold(id);
                moldDO.setMachineId(0L);
                moldDO.setMachineName("");
                moldDO.setStatus(3); // 在机 0 在途 3
                moldService.updateMold(BeanUtils.toBean(moldDO, MoldSaveReqVO.class));
            }

            DeviceLedgerDO deviceLedger = deviceLedgerService.getDeviceLedger(createReqVO.getDeviceId());
            deviceLedger.setMoldId(createReqVO.getMoldId());
            deviceLedgerService.updateDeviceLedger(BeanUtils.toBean(deviceLedger, DeviceLedgerSaveReqVO.class));
        }
        return success(moldOperateService.createMoldOperate(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新模具上下模")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:update')")
    public CommonResult<Boolean> updateMoldOperate(@Valid @RequestBody MoldOperateSaveReqVO updateReqVO) {
        moldOperateService.updateMoldOperate(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除模具上下模")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:delete')")
    public CommonResult<Boolean> deleteMoldOperate(@RequestParam("id") Long id) {
        moldOperateService.deleteMoldOperate(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得模具上下模")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:query')")
    public CommonResult<MoldOperateRespVO> getMoldOperate(@RequestParam("id") Long id) {
        MoldOperateDO moldOperate = moldOperateService.getMoldOperate(id);
        return success(BeanUtils.toBean(moldOperate, MoldOperateRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得模具上下模分页")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:query')")
    public CommonResult<PageResult<MoldOperateRespVO>> getMoldOperatePage(@Valid MoldOperatePageReqVO pageReqVO) {
        PageResult<MoldOperateDO> pageResult = moldOperateService.getMoldOperatePage(pageReqVO);
        // 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), admin -> Long.parseLong(admin.getCreator())));

//        // 模具信息
//        Map<Long, MoldRespVO> moldMap = moldService.getMoldVOMap(
//                convertSet(pageResult.getList(), MoldOperateDO::getMoldId));

        // 设备台账
//        Map<Long, DeviceLedgerRespVO> deviceLedgerMap = deviceLedgerService.getDeviceLedgerVOMap(
//                convertSet(pageResult.getList(), MoldOperateDO::getDeviceId));
        return success(BeanUtils.toBean(pageResult, MoldOperateRespVO.class,moldOperate -> {
            MapUtils.findAndThen(userMap, Long.parseLong(moldOperate.getCreator()), user -> moldOperate.setCreatorName(user.getNickname()));
//            MapUtils.findAndThen(moldMap, moldOperate.getMoldId(), mold -> moldOperate.setMoldName(mold.getName()));
//            MapUtils.findAndThen(deviceLedgerMap, moldOperate.getDeviceId(), deviceLedger -> moldOperate.setDeviceName(deviceLedger.getDeviceName()));
        }));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出模具上下模 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMoldOperateExcel(@Valid MoldOperatePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MoldOperateDO> list = moldOperateService.getMoldOperatePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "模具上下模.xls", "数据", MoldOperateRespVO.class,
                        BeanUtils.toBean(list, MoldOperateRespVO.class));
    }

    @GetMapping("/get-mold")
    @Operation(summary = "获得设备是否有模具")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:query')")
    public CommonResult<Boolean> getDeviceLedgerLMold(@RequestParam("id") Long id) {
        DeviceLedgerDO deviceLedgerDO = deviceLedgerService.getDeviceLedger(id);
        if (deviceLedgerDO.getMoldId() != null && !deviceLedgerDO.getMoldId().isEmpty() &&  Integer.parseInt(deviceLedgerDO.getMoldId()) != 0) {
            return success(true);
        }  else {
            return success(false);
        }

    }

    @GetMapping("/getLowerMoldList")
    @Operation(summary = "获得模具下模列表")
    @Parameter(name = "id", description = "设备id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-operate:query')")
    public CommonResult<List<MoldDO>> getLowerMoldList(@RequestParam("id") Long id) {
        List<MoldDO> moldDO = moldOperateService.getLowerMoldList(id);
        return success(moldDO);
    }

}