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

import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.utils.ResumeNameUtils;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanRespVO;
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.dal.mysql.deviceledger.DeviceLedgerMapper;
import cn.iocoder.yudao.module.mes.service.organization.OrganizationService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.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.*;
import javax.servlet.http.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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.deviceledger.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.service.deviceledger.DeviceLedgerService;

@Tag(name = "管理后台 - 设备台账")
@RestController
@RequestMapping("/mes/device-ledger")
@Validated
public class DeviceLedgerController {

    @Resource
    private DeviceLedgerService deviceLedgerService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建设备台账")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:create')")
    public CommonResult<Long> createDeviceLedger(@Valid @RequestBody DeviceLedgerSaveReqVO createReqVO) {
        return success(deviceLedgerService.createDeviceLedger(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备台账")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:update')")
    public CommonResult<Boolean> updateDeviceLedger(@Valid @RequestBody DeviceLedgerSaveReqVO updateReqVO) {
        deviceLedgerService.updateDeviceLedger(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备台账")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:delete')")
    public CommonResult<Boolean> deleteDeviceLedger(@RequestParam("ids") String ids) {

        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());

        deviceLedgerService.deleteDeviceLedger(idList);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备台账")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:query')")
    public CommonResult<DeviceLedgerRespVO> getDeviceLedger(@RequestParam("id") Long id) {
        DeviceLedgerDO deviceLedger = deviceLedgerService.getDeviceLedger(id);
        DeviceLedgerRespVO respVO = BeanUtils.toBean(deviceLedger, DeviceLedgerRespVO.class);
        respVO.setCreatorName(adminUserApi.getUser(Long.valueOf(deviceLedger.getCreator())).getNickname());
        if (StringUtils.isNotBlank(respVO.getDeviceManager())) {
            String[] userIds = respVO.getDeviceManager().split(",");
            StringBuilder names = new StringBuilder();

            for (int i = 0; i < userIds.length; i++) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(userIds[i].trim()));
                if (user != null) {
                    if (i > 0) names.append(", ");
                    names.append("(").append(user.getUsername()).append(")").append(user.getNickname());
                }
            }
            respVO.setDeviceManagerName(names.toString());
        }

        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备台账分页")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:query')")
    public CommonResult<PageResult<?>> getDeviceLedgerPage(@Valid DeviceLedgerPageReqVO pageReqVO) {
        PageResult<DeviceLedgerDO> pageResult = deviceLedgerService.getDeviceLedgerPage(pageReqVO);
        Set<Long> workshopIds = pageResult.getList().stream()
                .map(DeviceLedgerDO::getWorkshop)
                .filter(StringUtils::isNotBlank)  // 使用StringUtils或手动判断
                .flatMap(workshop -> {
                    try {
                        return Stream.of(Long.valueOf(workshop.trim()));
                    } catch (NumberFormatException e) {
                        return Stream.empty(); // 转换失败时返回空流，相当于跳过
                    }
                })
                .collect(Collectors.toSet());

        Map<Long, OrganizationDO> organizationMap = organizationService.getMap(workshopIds);

        // 4. 设置 workshopName
        for (DeviceLedgerDO item : pageResult.getList()) {
            if (item.getWorkshop() != null) {
                try {
                    Long workshopId = Long.parseLong(item.getWorkshop().trim());
                    OrganizationDO org = organizationMap.get(workshopId);
                    if (org != null) {
                        item.setWorkshopName(org.getName());
                    }
                } catch (NumberFormatException e) {
                }
            }
        }
        return success(ResumeNameUtils.buildPageCreatorName(BeanUtils.toBean(pageResult, DeviceLedgerRespVO.class)));
    }

    @GetMapping("/list")
    @Operation(summary = "获得设备台账列表")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:query')")
    public CommonResult<List<DeviceLedgerDO>> getDeviceLedgerList() {
        List<DeviceLedgerDO> deviceLedgerDOList = deviceLedgerService.getDeviceLedgerList();
        return success(deviceLedgerDOList);
    }

    @GetMapping("/noUsedlist")
    @Operation(summary = "获得未关联设备台账列表")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:query')")
    public CommonResult<List<DeviceLedgerDO>> getDeviceLedgerListByNoUsed() {
        List<DeviceLedgerDO> deviceLedgerDOList = deviceLedgerService.getDeviceLedgerList();
        deviceLedgerDOList.removeIf(device ->
                device.getWorkshop() != null && !device.getWorkshop().trim().isEmpty()
        );
        return success(deviceLedgerDOList);
    }

    @GetMapping("/noUsedlist2")
    @Operation(summary = "获得未关联设备台账列表")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:query')")
    public CommonResult<List<DeviceLedgerDO>> getDeviceLedgerList2ByNoUsed(@RequestParam("id") Long id) {
        List<DeviceLedgerDO> deviceLedgerDOList = deviceLedgerService.getDeviceLedgerList();
        deviceLedgerDOList.removeIf(device ->
                device.getWorkshop() != null && !device.getWorkshop().trim().isEmpty() && !Objects.equals(device.getId(), id)
        );
        return success(deviceLedgerDOList);
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出设备台账 Excel")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceLedgerExcel(@Valid DeviceLedgerPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        List<DeviceLedgerDO> list = deviceLedgerService.getDeviceLedgerPage(pageReqVO).getList();
        List<DeviceLedgerRespVO> deviceLedgerRespVOS = BeanUtils.toBean(list, DeviceLedgerRespVO.class);

        ResumeNameUtils.fillUserInfoForExport(deviceLedgerRespVOS);

        // 导出 Excel
        ExcelUtils.write(response, "设备台账.xls", "数据", DeviceLedgerRespVO.class,deviceLedgerRespVOS);
    }




    @GetMapping("/exportInspectionHistory")
    @Operation(summary = "根据设备Id导出点检履历")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInspectionHistory(@Valid DeviceLedgerPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        List<DeviceLedgerDO> list = deviceLedgerService.getDeviceLedgerPage(pageReqVO).getList();
        List<DeviceLedgerRespVO> deviceLedgerRespVOS = BeanUtils.toBean(list, DeviceLedgerRespVO.class);

        ResumeNameUtils.fillUserInfoForExport(deviceLedgerRespVOS);

        // 导出 Excel
        ExcelUtils.write(response, "设备台账.xls", "数据", DeviceLedgerRespVO.class,deviceLedgerRespVOS);
    }


    @GetMapping("/export-spare-based")
    @Operation(summary = "根据设备Id导出备件")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSpareBased(@RequestParam(name = "id") Long id,
                                        HttpServletResponse response) throws IOException {
        List<ErpProductVO> list = deviceLedgerService.exportSpareBased(id);
        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("备件.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        String fileName = String.format("备件_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        // 导出 Excel
        ExcelUtils.write(response, fileName, "数据", ErpProductVO.class,list);
    }

    @GetMapping("/export-mold")
    @Operation(summary = "根据设备Id导出模具")
    @PreAuthorize("@ss.hasPermission('mes:device-ledger:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMold(@RequestParam(name = "id") Long id,
                                 HttpServletResponse response) throws IOException {
        List<MoldVO> list = deviceLedgerService.exportMold(id);
        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("模具.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        String fileName = String.format("模具_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        // 导出 Excel
        ExcelUtils.write(response, fileName, "数据", MoldVO.class,list);
    }
}