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

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.foreverwin.mesnac.anomaly.mapper.AbnormalBillLogMapper;
import com.foreverwin.mesnac.anomaly.mapper.AbnormalNcCodeMapper;
import com.foreverwin.mesnac.anomaly.model.AbnormalBill;
import com.foreverwin.mesnac.anomaly.model.AbnormalBillDispose;
import com.foreverwin.mesnac.anomaly.model.AbnormalBillLog;
import com.foreverwin.mesnac.anomaly.model.AbnormalNcCode;
import com.foreverwin.mesnac.anomaly.service.*;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.meapi.mapper.ShopOrderMapper;
import com.foreverwin.mesnac.meapi.model.Router;
import com.foreverwin.mesnac.meapi.model.ShopOrder;
import com.foreverwin.mesnac.meapi.service.NwaUserService;
import com.foreverwin.mesnac.meapi.service.RouterService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * <p>
 * 异常单记录表 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-09-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AbnormalBillLogServiceImpl extends ServiceImpl<AbnormalBillLogMapper, AbnormalBillLog> implements AbnormalBillLogService {


    @Autowired
    private AbnormalBillLogMapper abnormalBillLogMapper;

    @Autowired
    private AbnormalNcCodeService abnormalNcCodeService;

    @Autowired
    private AbnormalNcCodeMapper abnormalNcCodeMapper;

    @Autowired
    private AbnormalBillService abnormalBillService;

    @Autowired
    private AbnormalBillDisposeService abnormalBillDisposeService;

    @Autowired
    private RouterService routerService;

    @Autowired
    private NwaUserService nwaUserService;


    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private AbnormalPlanService abnormalPlanService;


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

    @Override
    public List<AbnormalBillLog> selectList(AbnormalBillLog abnormalBillLog) {
        QueryWrapper<AbnormalBillLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(abnormalBillLog);
        return super.list(queryWrapper);
    }
    @Override
    public void saveAndUpdate(AbnormalBill abnormalBill, AbnormalBillDispose abnormalBillDispose, List<String> ncGroupAndNcCodes, List<String> dutyCauseType, List<String> dutyType) {
        String user = CommonMethods.getUser();
        LocalDateTime now = LocalDateTime.now();
        String site = CommonMethods.getSite();
        AbnormalBillLog abnormalBillLog = abnormalBillLogMapper.findAllByAbnormalNo(abnormalBill);

        if (!StringUtil.isBlank(abnormalBillDispose.getRouterBo())) {
            //分割该工艺路线
            String[] routerSplit = abnormalBillDispose.getRouterBo().split(",");
            //判断该返修工艺是否正确
            Router router = new Router();
            router.setSite(site);
            router.setRouter(routerSplit[1]);
            router.setRouterType(routerSplit[2]);
            router.setCurrentRevision("true");
            List<Router> routers = routerService.selectList(router);
            if (routers == null || routers.size() == 0) {
                throw BusinessException.build("该返修工艺不存在");
            }
        }
        //判断返修工单是否正确
        if (!StringUtil.isBlank(abnormalBillDispose.getResolveShopOrder())) {
            ShopOrder shopOrder = shopOrderMapper.selectById(HandleEnum.SHOP_ORDER.getHandle(site, abnormalBillDispose.getResolveShopOrder()));
            if (shopOrder == null) {
                throw BusinessException.build("该返修工单不存在");
            }
        }
        //发送用户
        if (!StringUtil.isBlank(abnormalBill.getReportSendUserGroup())) {
            nwaUserService.checkUserGroup(site, abnormalBill.getReportSendUserGroup());
        } else if (!StringUtil.isBlank(abnormalBillDispose.getDutySendUserGroup())) {
            nwaUserService.checkUserGroup(site, abnormalBillDispose.getDutySendUserGroup());
        } else if (!StringUtil.isBlank(abnormalBillDispose.getResolveSendUserGroup())) {
            nwaUserService.checkUserGroup(site, abnormalBillDispose.getResolveSendUserGroup());
        }

        if (abnormalBillLogMapper.selectById(abnormalBillLog.getHandle()) == null) {
            //根据abnormalNo找到不合格代码组
            StringBuilder ncGroup = new StringBuilder();

            QueryWrapper<AbnormalNcCode> abnormalNcCodeQueryWrapper = new QueryWrapper<>();
            abnormalNcCodeQueryWrapper.eq("ABNORMAL_BILL_BO", abnormalBillLog.getHandle());
            List<AbnormalNcCode> abnormalNcCodes = abnormalNcCodeMapper.selectList(abnormalNcCodeQueryWrapper);
            if (abnormalNcCodes != null && abnormalNcCodes.size() > 0) {
                for (AbnormalNcCode abnormalNcGroup : abnormalNcCodes) {
                    ncGroup.append(abnormalNcGroup.getNcCodeGroup()).append(",");
                }
            }
            List<String> ncGroups = new ArrayList<>();
            if (!StringUtil.isBlank(ncGroup.toString())) {
                ncGroup = new StringBuilder(ncGroup.substring(0, ncGroup.length() - 1));
                List<String> ncGroupList = Arrays.asList(ncGroup.toString().split(","));
                ncGroups.add(ncGroupList.get(0));
                for (int i = 1; i < ncGroupList.size(); i++) {
                    for (int j = 0; j < ncGroups.size(); j++) {
                        if (j == (ncGroups.size() - 1) && !ncGroups.get(j).equals(ncGroupList.get(i))) {
                            ncGroups.add(ncGroupList.get(i));
                        }
                        if (ncGroups.get(j).equals(ncGroupList.get(i))) {
                            break;
                        }
                    }
                }
            }
            ncGroup = new StringBuilder();
            for (int i = 0; i < ncGroups.size(); i++) {
                if (i == (ncGroups.size() - 1)) {
                    ncGroup.append(ncGroups.get(i));
                } else {
                    ncGroup.append(ncGroups.get(i)).append(",");
                }
            }
            abnormalBillLog.setNcCodeGroup(ncGroup.toString());
            abnormalBillLog.setCreatedUser(user);
            abnormalBillLog.setCreatedDataTime(now);
            abnormalBillLog.setModifiedUser(user);
            abnormalBillLog.setModifiedDateTime(now);

            this.save(abnormalBillLog);
        }


        if (Constants.ABNORMAL_QUALITY.equals(abnormalBill.getType())) {
            abnormalPlanService.saveAbnormalPlan(abnormalBill, abnormalBillDispose, now);
            abnormalBillService.anomalyReport(abnormalBill, abnormalBillDispose, ncGroupAndNcCodes, dutyCauseType, dutyType);
        } else if (Constants.ABNORMAL_OTHER.equals(abnormalBill.getType())) {
            abnormalBillService.anomalyReportOther(abnormalBill, abnormalBillDispose, dutyCauseType, dutyType);
        }

    }
}