package com.foreverwin.mesnac.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.service.AnomalyService;
import com.foreverwin.mesnac.common.service.CommonService;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.dto.NcCodeDto;
import com.foreverwin.mesnac.meapi.dto.SfcDto;
import com.foreverwin.mesnac.meapi.mapper.UserGroupMapper;
import com.foreverwin.mesnac.meapi.model.UserGroup;
import com.foreverwin.mesnac.meapi.service.NcCodeService;
import com.foreverwin.mesnac.production.mapper.SfcCrossMapper;
import com.foreverwin.mesnac.quality.dto.SelfReportRequest;
import com.foreverwin.mesnac.quality.mapper.SelfReportMapper;
import com.foreverwin.mesnac.quality.model.SelfReport;
import com.foreverwin.mesnac.quality.service.SelfReportService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 自报代办事项 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-08-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SelfReportServiceImpl extends ServiceImpl<SelfReportMapper, SelfReport> implements SelfReportService {


    @Autowired
    private SelfReportMapper selfReportMapper;
    @Autowired
    private SfcCrossMapper sfcCorssMapper;
    @Autowired
    private AnomalyService anomalyService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private NcCodeService ncCodeService;
    @Autowired
    private UserGroupMapper userGroupMapper;

    @Override
    public IPage<SelfReport> selectPage(FrontPage<SelfReport> frontPage, SelfReport selfReport) {
        QueryWrapper<SelfReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(selfReport);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<SelfReport> selectList(SelfReport selfReport) {
        QueryWrapper<SelfReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(selfReport);
        return super.list(queryWrapper);
    }
    @Override
    public List<SelfReport> selectList(QueryWrapper<SelfReport> queryWrapper, String locale, LocalDate startTime, LocalDate endTime) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        List<UserGroup> userGroupList = userGroupMapper.findUserGroupListByUser(site, user);
        //ADMINISTRATORS,如果有的话就等于null
        for (UserGroup userGroup : userGroupList){
            if("ADMINISTRATORS".equals(userGroup.getUserGroup())){
                userGroupList = null;
                break;
            }
        }

        return selfReportMapper.selectListByCondition(queryWrapper,locale,startTime,endTime,userGroupList);
    }

    @Override
    public void doAdd(Map<String, Object> map) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String sfc = (String)map.get("sfc");
        String resrce = (String)map.get("resrce");
        String ncQty = (String)map.get("ncQty");
        if (StringUtil.isBlank(ncQty)){
            throw new BaseException("不良件数不能为空");
        }
        String comments = (String)map.get("comments");
        String location=(String)map.get("location");
        String userGroup=(String)map.get("userGroup");
        List<SelfReportRequest> list = (List<SelfReportRequest>)map.get("ncList");
        ObjectMapper mapper = new ObjectMapper();
        list = mapper.convertValue(list, new TypeReference<List<SelfReportRequest>>() {});
        SfcDto sfcDto = new SfcDto();
        sfcDto.setSfc(sfc);
        sfcDto.setResrce(resrce);
        Map<String, Object> sfcData = sfcCorssMapper.querySfcData(site, LocaleContextHolder.getLocale().getLanguage(), sfcDto);
        if (sfcData == null) {
            throw new BaseException("根据当前资源未找到条码[" + sfc + "]的基本信息！");
        }
        BigDecimal sfcQty = (BigDecimal) sfcData.get("SFC_QTY");
        if (new BigDecimal(ncQty).compareTo(sfcQty)>0 ){
            throw new BaseException("不良总数超过产品批次数量");
        }
        String operationStep = (String)sfcData.get("OPERATION_STEP");
        String shopOrder = (String)sfcData.get("SHOP_ORDER");
        String item = (String)sfcData.get("ITEM");
        List<SelfReportRequest> resrceAbnormalList = list.stream().filter(selfReportRequest -> selfReportRequest.getType().equals(Constants.ABNORMAL_RESRCE)).collect(Collectors.toList());
        if (resrceAbnormalList.size()>0){
            StringBuilder stringBuilder = new StringBuilder();
            for (int i=0;i<resrceAbnormalList.size();i++){
                stringBuilder.append(resrceAbnormalList.get(i).getNcCode());
                if (i!=resrceAbnormalList.size()-1){
                    stringBuilder.append(",");
                }
            }
            anomalyService.createAnomalyTask(Constants.ABNORMAL_RESRCE,resrce,shopOrder,sfc,stringBuilder.toString(),location,ncQty,comments,userGroup);
        }
        List<SelfReportRequest> otherAbnormalList = list.stream().filter(selfReportRequest -> selfReportRequest.getType().equals(Constants.ABNORMAL_OTHER)).collect(Collectors.toList());
        if (otherAbnormalList.size()>0){
            anomalyService.createAnomalyTask(Constants.ABNORMAL_OTHER,resrce,shopOrder,sfc,"",location,ncQty,comments,userGroup);
        }
        LambdaQueryWrapper<SelfReport> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SelfReport::getSfc,sfc);
        queryWrapper.eq(SelfReport::getOpStep,operationStep);
        queryWrapper.eq(SelfReport::getState,Constants.NEW);
        List<SelfReport> selfReports = list(queryWrapper);
        if (selfReports.size()>0){
            throw new BaseException("存在未处理的自报任务");
        }
        List<SelfReportRequest> selfReportList = list.stream().filter(selfReportRequest -> selfReportRequest.getType().equals("Z")).collect(Collectors.toList());
        if (selfReportList.size()>0){
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder description = new StringBuilder();
            for (int i=0;i<selfReportList.size();i++){
                String ncCode = selfReportList.get(i).getNcCode();
                stringBuilder.append(ncCode);
                List<NcCodeDto> ncCodeDescriptionByNcCode = ncCodeService.findNcCodeDescriptionByNcCode(ncCode);
                description.append(ncCodeDescriptionByNcCode.get(0).getNgDescription());
                if (i!=selfReportList.size()-1){
                    stringBuilder.append(",");
                    description.append(",");
                }
            }
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String taskNo =  "SR_" + dateFormat1.format(date);
            String handle = HandleEnum.SELF_REPORT.getHandle(site, taskNo);
            SelfReport selfReport = new SelfReport();
            selfReport.setDescription("自报");
            selfReport.setHandle(handle);
            selfReport.setSite(site);
            selfReport.setTaskNo(taskNo);
            String workShopBo = commonService.getWorkShopBo(HandleEnum.RESOURCE.getHandle(site, resrce));
            if (StringUtil.isBlank(workShopBo)){
                throw new BaseException("资源未维护车间");
            }
            selfReport.setWorkCenter(StringUtil.trimHandle(workShopBo));
            selfReport.setShopOrder(shopOrder);
            selfReport.setItem(item);
            selfReport.setOpStep(operationStep);
            selfReport.setResrce(resrce);
            selfReport.setSfc(sfc);
            selfReport.setNcCode(stringBuilder.toString());
            selfReport.setNcCodeDesc(description.toString());
            selfReport.setNcQty(new BigDecimal(ncQty));
            selfReport.setLocation(location);
            selfReport.setState(Constants.STATUS_NEW);
            selfReport.setRemark(comments);
            selfReport.setCreateUser(user);
            selfReport.setCreatedDateTime(LocalDateTime.now());
            selfReport.setModifyUser(user);
            selfReport.setModifiedDateTime(LocalDateTime.now());
            selfReport.setReportUserGroup(userGroup);
            save(selfReport);
        }
    }

    @Override
    public Object updateState(String handle, String state) {
        SelfReport selfReport = getById(handle);
        if (!selfReport.getState().equals(Constants.STATUS_NEW)){
            throw new BaseException("状态不为新建，请重新检索");
        }
        selfReport.setState(state);
        selfReport.setModifiedDateTime(LocalDateTime.now());
        selfReport.setModifyUser(CommonMethods.getUser());
        return updateById(selfReport);
    }



}