package com.sifang.modules.quality.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.quality.constant.QualityConstants;
import com.sifang.modules.quality.dao.*;
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.DispatchEmpVo;
import com.sifang.modules.quality.vo.QualityChangingDetailVo;
import com.sifang.modules.quality.vo.QualityChangingVo;
import com.sifang.modules.quality.vo.ResultRes;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.LayuiPage;
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 CrmQualityRectificationService extends BaseService {

    @Autowired
    private CrmQualityRectificationDao qualityRectificationDao;

    @Autowired
    CrmEntryQualityAcceptanceDetailDao entryQualityAcceptanceDetailDao;

    @Autowired
    CrmEntryQualityAcceptanceResultDao entryQualityAcceptanceResultDao;

    @Autowired
    private CrmEntryQualityAcceptanceDao qualityAcceptanceDao;

    //列表数据
    public LayuiPage<Record> getQualityRectificationList(Map<String,String> param, LayuiPage<Record> page, Operator operator){
        List<Record> list= qualityRectificationDao.getQualityRectificationList(param,page,operator);
        page.setData(list);
        Long count=qualityRectificationDao.getListCount(param,operator);
        page.setCount(count);
        return page;
    }

    /**
     * 获取派工的员工
     */
    public List<Record> getDispatchEmpList(Map<String,String> param, Operator operator){
        return qualityRectificationDao.getDispatchEmpList(param,operator);
    }

    /**
     * 派工
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveDispatchEmp(DispatchEmpVo empVo){
        logger.info("saveDispatchEmp  id:{},empId:{}",empVo.getId(),empVo.getEmpId());
        CrmEntryQualityAcceptanceDetail qualityAcceptanceDetail = entryQualityAcceptanceDetailDao.get(empVo.getId());
        if(!QualityConstants.CHANGE_STATUS_WAITE.equals(qualityAcceptanceDetail.getChangeStatus())&&qualityAcceptanceDetail.getChangeStatus() != null){
            throw new IllegalArgumentException("该整改单已派工，请刷新页面！");
        }
        qualityAcceptanceDetail.setChangeEmpUserId(empVo.getEmpId());
        qualityAcceptanceDetail.setChangeEmpName(empVo.getEmpName());
        qualityAcceptanceDetail.setChangeTime(new Date());
        qualityAcceptanceDetail.setChangeStatus(QualityConstants.CHANGE_STATUS_ING);
        entryQualityAcceptanceDetailDao.save(qualityAcceptanceDetail);
    }

    /**
     * 整改
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveChangingQuality(QualityChangingDetailVo change){
        for(QualityChangingVo vo : change.getList() ){
            CrmEntryQualityAcceptanceResult result = entryQualityAcceptanceResultDao.get(vo.getId());
            result.setChangeImg(vo.getChangeImg());
            result.setChangeDesc(vo.getRemark());
            entryQualityAcceptanceResultDao.save(result);
        }
        CrmEntryQualityAcceptanceDetail qualityAcceptanceDetail = entryQualityAcceptanceDetailDao.get(change.getDetailId());
        qualityAcceptanceDetail.setChangeStatus(change.getChangeStatus());
        if(QualityConstants.CHANGE_STATUS_ACCEPT.equals(change.getChangeStatus())){
            qualityAcceptanceDetail.setAcceptStatus(change.getChangeStatus());
        }
        qualityAcceptanceDetail.setChangeTime(new Date());
        entryQualityAcceptanceDetailDao.save(qualityAcceptanceDetail);

    }


    /**
     * 验收
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveAcceptQuality(String id, String changeAcceptRemarks, String changeStatus){
        CrmEntryQualityAcceptanceDetail qualityAcceptanceDetail = entryQualityAcceptanceDetailDao.get(id);
        if(QualityConstants.CHANGE_STATUS_BACK.equals(changeStatus)){
            qualityAcceptanceDetail.setAcceptStatus(changeStatus);
        }
        qualityAcceptanceDetail.setChangeStatus(changeStatus);
        qualityAcceptanceDetail.setChangeAcceptRemarks(changeAcceptRemarks);
        qualityAcceptanceDetail.setAcceptStatus(changeStatus);
        if("5".equals(changeStatus)){ //验收通过
            qualityAcceptanceDetail.setAcceptStatus("1");
            Date date=new Date();
            qualityAcceptanceDetail.setAcceptTime(date);
            CrmEntryQualityAcceptance acceptance=qualityAcceptanceDao.get(qualityAcceptanceDetail.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(">>>>>saveAcceptQuality 质检单完成");
            }
            qualityAcceptanceDao.save(acceptance);
        }
        entryQualityAcceptanceDetailDao.save(qualityAcceptanceDetail);
    }

    //获取合格项 和不合格项  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);
        for(Record record : listItem){
            StringBuilder builder = new StringBuilder();
            builder.append(" SELECT type FROM crm_entry_quality_item_set WHERE name = "+"'"+record.getStr("item_name")+"'");
            String type = Db.queryColumn(builder.toString());
            if(type != null){
                record.set("type",type);
            }else{
                record.set("type","0");
            }
        }
        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;
    }

}