package com.bonus.sgzb.material.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bonus.sgzb.base.api.domain.RepairTestInputDto;
import com.bonus.sgzb.common.core.constant.HttpStatus;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.DateTimeHelper;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.PurchaseMacodeInfoMapper;
import com.bonus.sgzb.material.mapper.RepairTestInputMapper;
import com.bonus.sgzb.material.mapper.TaskMapper;
import com.bonus.sgzb.material.mapper.TmTaskAgreementMapper;
import com.bonus.sgzb.material.service.RepairTestInputService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 10488
 * 修试入库
 */
@Service("RepairTestInputService")
@Slf4j
public class RepairTestInputServiceImpl implements RepairTestInputService {

    @Resource(name = "RepairTestInputMapper")
    private RepairTestInputMapper mapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private PurchaseMacodeInfoMapper purchaseMacodeInfoMapper;

    @Resource
    private TmTaskAgreementMapper agreementMapper;

    @Override
    public List<RepairTestInputVo> getRepairedList(RepairTestInputDto dto) {
        return mapper.getRepairedList(dto);
    }

    @Override
    public List<RepairTestInputDetailVo> getRepairedDetailList(RepairTestInputDto dto) {
        List<RepairTestInputDetailVo> repairedDetailList = mapper.getRepairedDetailList(dto);
        for (RepairTestInputDetailVo repairTestInputDetailVo : repairedDetailList) {
            List<String> userIds = purchaseMacodeInfoMapper.selectKeepUser(repairTestInputDetailVo.getTypeId());
            userIds.add("1");
            repairTestInputDetailVo.setUserIds(userIds);
        }
        return repairedDetailList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult inputByType(RepairTestInputDto repairTestInputDto) {
        try {
            if (StringUtils.isEmpty(repairTestInputDto.getParams())) {
                return AjaxResult.error(HttpStatus.ERROR, "参数不正确");
            }
            List<RepairTestWarehousingDto> list = JSONObject.parseArray(repairTestInputDto.getParams(), RepairTestWarehousingDto.class);
            if (CollectionUtils.isEmpty(list)) {
                return AjaxResult.error(HttpStatus.ERROR, "参数不正确");
            }
            List<RepairAuditDetails> auditDetails = new ArrayList<>();
            Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            String updateTime = DateTimeHelper.getNowTime();
            String updateBy = SecurityUtils.getLoginUser().getUsername();
            for (RepairTestWarehousingDto dto : list) {
                if (companyId != null) {
                    dto.setCompanyId(companyId);
                }
                dto.setUpdateTime(updateTime);
                dto.setUpdateBy(updateBy);
                if (Objects.equals("2", dto.getCheckType())) {
                    RepairAuditDetails detail = new RepairAuditDetails();
                    detail.setRepairId(Long.valueOf(dto.getId()));
                    detail.setTypeId(Long.valueOf(dto.getTypeId()));
                    if (StringHelper.isNotEmpty(dto.getMaId())) {
                        detail.setMaId(Long.valueOf(dto.getMaId()));
                    }
                    detail.setRepairNum(dto.getRepairNum());
                    detail.setRepairedNum(dto.getRepairNum());
                    detail.setScrapNum(0);
                    detail.setStatus("0");
                    detail.setCreateBy(String.valueOf(userId));
                    detail.setUpdateBy(String.valueOf(userId));
                    detail.setCompanyId(Math.toIntExact(dto.getCompanyId()));
                    auditDetails.add(detail);
                    // 审核不通过-入库数量修改为 0
                    dto.setRepairNum(0);
                }
                // 更新修试后入库数据
                mapper.updateRepairInputDetails(dto);
                if (Objects.equals("1", dto.getCheckType())) {
                    // 审核通过-更新入库任务详细表
                    mapper.addInputApplyDetails(dto);
                    // 查询机具类型-现有库存
                    Map<String, Object> map = mapper.getMaTypeByNum(dto.getTypeId());
                    // 更新机具类型-库存
                    Integer repairNum = dto.getRepairNum() != null ? dto.getRepairNum() : 0;
                    Integer num = countNum(map.get("num"), repairNum);
                    mapper.updateMaTypeNum(dto.getTypeId(), num);
                    int codeMachinePreStoreNum = 0;
                    if (Objects.equals("0", dto.getType())) {
                        codeMachinePreStoreNum = mapper.getCountOfMachineByTypeId(dto.getTypeId());
                        // 查询机具状态-在库的id、管理方式为编号的需更新机具设备的机具状态
                        //int dicId = mapper.getDicByMaStatusId("ma_status", "在库");
                        mapper.updateMaMachineStatus(15, dto.getMaId());
                    }
//                    try {
//                        if (Objects.equals("0", dto.getType())) {
//                            repairTestInputDto.setPreStoreNum(codeMachinePreStoreNum);
//                            repairTestInputDto.setRepairNum(Integer.parseInt(repairNum));
//                            repairTestInputDto.setPostStoreNum(mapper.getCountOfMachineByTypeId(dto.getTypeId()));
//                        }
//                        else if (Objects.equals("1", dto.getType())) {
//                            repairTestInputDto.setPreStoreNum((Integer) map.get("num"));
//                            repairTestInputDto.setRepairNum(Integer.parseInt(repairNum));
//                            repairTestInputDto.setPostStoreNum((int) num);
//                        }
//                    } catch (Exception e) {
//                        log.error("修试后入库-入库操作-获取库存日志失败", e);
//                    }
                }
            }
            RepairTestWarehousingDto dto = list.get(0);
            // 查询修试后入库的状态是否全部更新、更新任务表状态
            Map<String, Object> numMap = mapper.getIsAllUpdate(dto);
            TmTaskAgreement tmTaskAgreement = agreementMapper.selectTmTaskAgreementByTaskId(Long.valueOf(dto.getTaskId()));
            // 总量、未审核数量、入库数量、驳回数量
            int totalNum = Integer.parseInt(String.valueOf(numMap.get("totalNum")));
            int noCheckNum = Integer.parseInt(String.valueOf(numMap.get("noCheckNum")));
            int passNum = Integer.parseInt(String.valueOf(numMap.get("passNum")));
            int noPassNum = Integer.parseInt(String.valueOf(numMap.get("noPassNum")));
            if (passNum == totalNum) {
                int dicId = mapper.getDicByMaStatusId("rk_task", "入库完成");
                mapper.updateTmTaskStatus(dto, dicId);
            } else if (noPassNum > 0 && noCheckNum == 0) {
                int dicId = mapper.getDicByMaStatusId("rk_task", "入库驳回");
                mapper.updateTmTaskStatus(dto, dicId);
            }
            if (auditDetails.size() > 0) {
                int i = reject(auditDetails, tmTaskAgreement);
                if (i != auditDetails.size()) {
                    throw new ServiceException("驳回出错");
                }
            }

        } catch (Exception e) {
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("修试后入库-入库操作", e);
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    public int reject(List<RepairAuditDetails> auditDetails, TmTaskAgreement tmTaskAgreement) {
        String taskCode = "";
        int taskStatus = 0;
        int taskType = 0;
        int companyId = 0;
        int i = 0;
        if (auditDetails.get(0).getCompanyId() != null) {
            companyId = Math.toIntExact(auditDetails.get(0).getCompanyId());
        }
        taskCode = purchaseCodeRule("WX", 45);
        taskStatus = 46;
        taskType = 45;
        long repairTaskId = genTask(taskCode, taskType, taskStatus, tmTaskAgreement, companyId);
        for (RepairAuditDetails bean : auditDetails) {
            bean.setTaskId(repairTaskId);
            i = i + mapper.addRepaieAudit(bean);
        }
        return i;
    }

    private String purchaseCodeRule(String code, Integer taskType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = taskMapper.selectTaskNumByMonths(nowDate, taskType);
        if (StringHelper.isNotEmpty(taskNum)) {
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是四位数，不足四位则在前面补0
            taskNum = String.format("%04d", num);
        } else {
            taskNum = "0001";
        }
        String codeNum = code + format + "-" + taskNum;
        return codeNum;
    }

    private long genTask(String taskCode, int taskType, int taskStatus, TmTaskAgreement tmTaskAgreement, int companyId) {
        TmTask task = new TmTask();
        task.setCode(taskCode);
        task.setTaskStatus(taskStatus);
        task.setTaskType(taskType);
        task.setCompanyId(companyId);
        task.setCreateTime(new Date());
        task.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        taskMapper.insertTmTask(task);
        // 添加协议信息表
        TmTaskAgreement taskAgreement = new TmTaskAgreement();
        long taskId = task.getTaskId();
        taskAgreement.setTaskId(taskId);
        if (tmTaskAgreement.getAgreementId() == null) {
            throw new ServiceException("缺少协议数据");
        } else {
            taskAgreement.setAgreementId(tmTaskAgreement.getAgreementId());
        }
        taskAgreement.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        agreementMapper.insertTmTaskAgreement(taskAgreement);
        return taskId;
    }

    @Override
    public List<RepairTestInputDetailVo> exportList(RepairTestInputDto bean) {
        return mapper.exportList(bean);
    }

    /**
     * @param num
     * @param repairNum
     * @return double
     * @description 添加库存
     * @author cwchen
     * @date 2023/12/16 20:43
     */
    public Integer countNum(Object num, Integer repairNum) {
        Integer value = 0;
        value = value + repairNum;
        if (Objects.nonNull(num)) {
            int numValue = Integer.parseInt(num.toString());
            value = value + numValue;
        }
        return value;
    }
}
