package com.sifang.modules.quality.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowpath.service.CashOutApplyService;
import com.sifang.modules.quality.constant.QualityConstants;
import com.sifang.modules.quality.dao.CrmEntryQualityAcceptanceDao;
import com.sifang.modules.quality.dao.CrmEntryQualityAcceptanceDetailDao;
import com.sifang.modules.quality.dao.CrmEntryQualityAcceptanceResultDao;
import com.sifang.modules.quality.entity.CrmEntryQualityAcceptance;
import com.sifang.modules.quality.entity.CrmEntryQualityAcceptanceDetail;
import com.sifang.modules.quality.entity.CrmEntryQualityAcceptanceResult;
import com.sifang.modules.quality.vo.ResultRes;
import com.sifang.modules.quality.vo.SaveAcceptItemVo;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CrmEntryQualityAcceptanceResultService extends BaseService {

    @Autowired
    private CrmEntryQualityAcceptanceDetailDao detailDao;

    @Autowired
    private CrmEntryQualityAcceptanceDao acceptanceDao;

    @Autowired
    private CrmEntryQualityAcceptanceResultDao resultDao;

    @Autowired
    private CashOutApplyService cashOutApplyService;

    public List<Record> acceptItems(String detailId){
        //所有的类目
        List<Record> listItem=Db.find("  SELECT s.name,s.parent_id,s.result_right,s.result_wrong,s.type,s.sort ,CONCAT(p.name,s.name) AS groupName " +
                ",'' AS result_desc,'' AS result,'' AS special_desc,'' AS img_path,'' AS test_remarks "+
                " FROM crm_entry_quality_item_set s LEFT JOIN  crm_entry_quality_item_set p ON s.parent_id=p.id AND p.group='1' WHERE s.group='2' ORDER BY s.sort ASC ");

        //暂存的验收结果
        List<Record> listResult=Db.find("SELECT r.group_name,r.item_name ,result_desc,r.result,r.special_desc,r.img_path,r.test_remarks,concat(r.group_name,r.item_name) as groupName  " +
                "    FROM crm_entry_quality_acceptance_result r WHERE r.acceptance_detail_id=? ORDER BY r.sort ASC ",detailId);
        if(!listResult.isEmpty()){
            Map<String, Record> typeMap = listResult.stream()
                    .collect(Collectors.toMap(e -> e.getStr("groupName"), e -> e, (a, b) -> a));
            for(Record item:listItem){
                Record itemResult=typeMap.get(item.getStr("groupName"));
                if(itemResult!=null){
                    item.set("result_desc",itemResult.getStr("result_desc"));
                    item.set("result",itemResult.getStr("result"));
                    item.set("special_desc",itemResult.getStr("special_desc"));
                    item.set("img_path",itemResult.getStr("img_path"));
                    item.set("test_remarks",itemResult.getStr("test_remarks"));
                }
            }
        }
        Map<String, List<Record>> itemMap = listItem.stream().collect(Collectors.groupingBy(r -> r.getStr("parent_id")));
        List<Record> list= Db.find(" SELECT s.name,s.id FROM crm_entry_quality_item_set s WHERE s.parent_id='0' ORDER BY s.sort ASC ");
        for(Record record:list){
            record.set("items",itemMap.get(record.getStr("id")));
        }
        return list;
    }

    public Record getResultCount(String detailId){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT COUNT(CASE WHEN r.result='0' THEN 1 END) AS rightCount, ");
        sb.append(" COUNT(CASE WHEN r.result='1' THEN 1 END) AS wrongCount ");
        sb.append(" FROM crm_entry_quality_acceptance_result r WHERE r.acceptance_detail_id=? and r.item_name!='其他' ");
        return Db.findFirst(sb.toString(),detailId);
    }

    //验收 保存
    @Transactional(rollbackFor = Exception.class)
    public void saveAcceptItem(SaveAcceptItemVo itemVo){
        String detailId=itemVo.getDetailId();
        CrmEntryQualityAcceptanceDetail detail=detailDao.get(detailId);
        if(itemVo.getItems().isEmpty()){
            throw new IllegalArgumentException("检验项目不能为空！");
        }
        logger.info("...saveAcceptItem detailId：{}, size:{},saveResult:{}",detailId,itemVo.getItems().size(),itemVo.getSaveResult());
        if("1".equals(itemVo.getSaveResult())){  //0 暂存  1提交
            List<CrmEntryQualityAcceptanceResult> list=itemVo.getItems();
            List<Record> itemSet=Db.find(" SELECT s.name,s.parent_id,s.name,s.type  FROM crm_entry_quality_item_set s  WHERE s.group='2' ");
            Map<String, Record> itemSetMap = itemSet.stream()
                    .collect(Collectors.toMap(e -> e.getStr("name"), e -> e, (a, b) -> a));
            for(CrmEntryQualityAcceptanceResult result:list){
                logger.info("saveAcceptItem  itemName:{},result:{}",result.getItemName(),result.getResult());
                Record record=itemSetMap.get(result.getItemName());
                if(StringUtil.isBlank(result.getResult()) && "1".equals(record.getStr("type"))){
                    throw new IllegalArgumentException("检验项目"+result.getItemName()+"，没有验收结果，不能提交！");
                }
                if("接地阻值".equals(result.getItemName()) && StringUtil.isBlank(result.getSpecialDesc())){
                    throw new IllegalArgumentException("测试阻值 不能为空");
                }
                if("周围无遮挡物".equals(result.getItemName()) && "1".equals(result.getResult()) && StringUtil.isBlank(result.getSpecialDesc())){
                    throw new IllegalArgumentException("周围无遮挡物,遮挡位置有几处 不能为空");
                }
                if(!"其他".equals(result.getItemName()) && !"各路电压正常".equals(result.getItemName()) && StringUtil.isBlank(result.getImgPath())){
                    throw new IllegalArgumentException(result.getItemName()+" 验收图片不能为空");
                }
                if("各路电压正常".equals(result.getItemName()) && "不正常".equals(result.getResultDesc()) && StringUtil.isBlank(result.getImgPath())){
                    throw new IllegalArgumentException("各路电压不正常,那么验收图片不能为空");
                }
                if("1".equals(result.getResult()) && StringUtil.isBlank(result.getTestRemarks())){
                    throw new IllegalArgumentException(result.getItemName()+" ,不合格的，验收说明不能为空");
                }
                if("4".equals(record.getStr("type"))){ //类型：1仅单选框 2单选后需特殊说明 3单选+输入 4没有单选和输入框
                    result.setResult("0");
                }

            }
        }
        int wrongCount=0;
        for(CrmEntryQualityAcceptanceResult result:itemVo.getItems()){
           result.setAcceptanceId(detail.getMainId());
           result.setAcceptanceDetailId(detail.getId());
           result.setEntryId(detail.getEntryId());
           if("1".equals(result.getResult())){
              wrongCount++;
           }
        }
        logger.info("saveAcceptItem  wrongCount:{}",wrongCount);
        Date date=new Date();
        if("1".equals(itemVo.getSaveResult())){  //提交
            if(wrongCount>0){  //质检有不合格的
                detail.setAcceptStatus(QualityConstants.ACCEPT_STATUS_BAD);
                detail.setChangeStatus("1");
                detail.setChangeCreateTime(new Date());
            }else{
                detail.setAcceptStatus(QualityConstants.ACCEPT_STATUS_GOOD);
                CrmEntryQualityAcceptance acceptance=acceptanceDao.get(detail.getMainId());
                acceptance.setFinishCount(acceptance.getFinishCount()+1);
                logger.info("....saveAcceptItem finishCount:{}",acceptance.getFinishCount());
                if(acceptance.getFinishCount()>=acceptance.getSampleCount()){
                    acceptance.setStatus(QualityConstants.QUALITY_STATUS_FINISH);
                    acceptance.setFinishTime(date);
                    logger.info(">>>>>saveAcceptItem 质检单完成");
                }
                acceptanceDao.save(acceptance);
            }
            detail.setAcceptTime(date);
            detailDao.save(detail);

        }
        //删除之前保存的验收信息
        SQLQuery sqlQuery = resultDao.getSession().createSQLQuery("DELETE FROM crm_entry_quality_acceptance_result WHERE acceptance_detail_id=:detailId");
        sqlQuery.setParameter("detailId", detailId);
        sqlQuery.executeUpdate();
        resultDao.save(itemVo.getItems());
    }

    //获取合格项 和不合格项  result=0 合格项  result=1 不合格项
    public  List<ResultRes> getAcceptResultByDetailId(String detailId,String result){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT r.id,r.group_name,r.item_name ,result_desc,r.result,r.special_desc,r.img_path,r.test_remarks,r.change_img,r.change_desc ");
        sb.append(" FROM crm_entry_quality_acceptance_result r WHERE r.acceptance_detail_id=? AND r.result=? ");
        sb.append(" ORDER BY r.sort ASC  ");
        List<Record> listItem=Db.find(sb.toString(),detailId,result);
        Map<String, List<Record>> itemMap = listItem.stream().collect(Collectors.groupingBy(r -> r.getStr("group_name")));

        List<ResultRes> resultList=new ArrayList<>();
        for(Map.Entry<String, List<Record>> ent : itemMap.entrySet()){
            ResultRes resultRes=new ResultRes(ent.getKey(),ent.getValue());
            resultList.add(resultRes);
        }
        return resultList;
    }

}
