package com.sifang.modules.quality.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.GaodeUtil;
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.entity.CrmEntryQualityAcceptance;
import com.sifang.modules.quality.entity.CrmEntryQualityAcceptanceDetail;
import com.sifang.modules.quality.utils.NumberGenUtil;
import com.sifang.modules.quality.vo.DispatchEmpVo;
import com.sifang.modules.quality.vo.ListSortingVo;
import com.sifang.modules.quality.vo.QualityAcceptVo;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class CrmEntryQualityAcceptanceService extends BaseService {

    @Autowired
    private CrmEntryQualityAcceptanceDao qualityAcceptanceDao;

    @Autowired
    private CrmEntryQualityAcceptanceDetailDao acceptanceDetailDao;

    @Autowired
    private CrmPlatformEmpDao platformEmpDao;



    //列表数据
    public LayuiPage<Record> entryQualityData(Map<String,String> param, LayuiPage<Record> page){
        List<Record> list= qualityAcceptanceDao.entryQualityData(param,page);
        page.setData(list);
        Long count=qualityAcceptanceDao.getListCont(param);
        page.setCount(count);
        return page;
    }

    //质检单详情
    public Record getOrderDetail(String id){
        return qualityAcceptanceDao.getOrderDetail(id);
    }
    //质检单抽检的关联的电站信息（抽检的）
    public List<Record> getOrderRelateEntryList(String id){
        List<Record> listEntry=qualityAcceptanceDao.getOrderRelateEntryList(id,"","");
        return listEntry;
    }
    //质检单关联的所有电站
    public List<Record> getOrderEntryList(String id,String status,String tenantName){
        List<Record> listEntry=qualityAcceptanceDao.getOrderRelateEntryList(id,status,tenantName);
        return listEntry;
    }

    public CrmEntryQualityAcceptanceDetail canNotAcceptanceDetail(String detailId){
        CrmEntryQualityAcceptanceDetail detail=acceptanceDetailDao.get(detailId);
        return detail;
    }


    /**
     * 根据设置的规则，生成不同代理商的巡检单
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveXjdAcceptance(Record traderRecord, List<Record> listEntry, Date date,Integer sampleCount){
        logger.info("saveXjdAcceptance traderId:{},entrys:{}",traderRecord.getStr("trader_id"),listEntry.size());

        CrmEntryQualityAcceptance qualityAcceptance=new CrmEntryQualityAcceptance();
        qualityAcceptance.setId(IdGen.uuid());
        qualityAcceptance.setType("2");
        long todayCnt=qualityAcceptanceDao.countByDate(date);
        String number=NumberGenUtil.genYmdhmm("", date, todayCnt + 1,3);
        qualityAcceptance.setNumber(number);
        qualityAcceptance.setTraderId(traderRecord.getStr("trader_id"));
        qualityAcceptance.setTraderName(traderRecord.getStr("trader_name"));
        qualityAcceptance.setRelateOrderId("");
        qualityAcceptance.setRegionProvince(traderRecord.getStr("province"));
        qualityAcceptance.setRegionCity(traderRecord.getStr("city"));
        qualityAcceptance.setRegionArea(traderRecord.getStr("area"));
        qualityAcceptance.setStatus(QualityConstants.QUALITY_STATUS_WAITE);
        qualityAcceptance.setCreateMethod("1");
        qualityAcceptance.setTotalCount(traderRecord.getLong("totalCount").intValue());
        qualityAcceptance.setSampleCount(sampleCount);
        qualityAcceptance.setFinishCount(0);
        qualityAcceptance.setQualityRatio("20");
        qualityAcceptance.setCreateTime(date);


        List<CrmEntryQualityAcceptanceDetail> details=new ArrayList<>();
        for(Record r:listEntry){
            CrmEntryQualityAcceptanceDetail acceptanceDetail=new CrmEntryQualityAcceptanceDetail();
            acceptanceDetail.setMainId(qualityAcceptance.getId());
            acceptanceDetail.setEntryId(r.getStr("entry_id"));
            acceptanceDetail.setPowerStationCode(r.getStr("power_station_code"));
            acceptanceDetail.setTenantName(r.getStr("tenant_name"));
            acceptanceDetail.setStatus(QualityConstants.DETAIL_STATUS_SYSTEM);
            acceptanceDetail.setAcceptStatus(QualityConstants.ACCEPT_STATUS_WAIT);
            acceptanceDetail.setTraderId(r.getStr("create_trader_id"));
            details.add(acceptanceDetail);
        }
        acceptanceDetailDao.save(details);
        qualityAcceptanceDao.save(qualityAcceptance);
    }



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

    /**
     * 保存 质检 派工
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveDispatchEmp(DispatchEmpVo empVo, Operator operator){
       logger.info("saveDispatchEmp  id:{},empId:{}",empVo.getId(),empVo.getEmpId());
        CrmEntryQualityAcceptance qualityAcceptance=qualityAcceptanceDao.get(empVo.getId());
        if(!QualityConstants.QUALITY_STATUS_WAITE.equals(qualityAcceptance.getStatus())){
              throw new IllegalArgumentException("质检单已派工，请刷新页面！");
        }
        Date date=new Date();
        qualityAcceptance.setDispatchTime(date);
        qualityAcceptance.setQualityEmpId(empVo.getEmpId());
        CrmPlatformEmployee empRecord=platformEmpDao.get(empVo.getEmpId());
        qualityAcceptance.setQualityEmpUserId(empRecord.getUserId());
        qualityAcceptance.setQualityEmpName(empRecord.getName());
        qualityAcceptance.setStatus(QualityConstants.QUALITY_STATUS_IN);
        qualityAcceptance.setDispatchUserName(operator.getUserName());
        qualityAcceptanceDao.save(qualityAcceptance);

        SQLQuery sqlQuery = acceptanceDetailDao.getSession().createSQLQuery(" UPDATE crm_entry_quality_acceptance_detail SET dispatch_time=:dispatchTime,emp_user_id=:empUserId WHERE main_id =:mainId  and status in ('1','2') ");
        sqlQuery.setParameter("dispatchTime", date);
        sqlQuery.setParameter("empUserId", empRecord.getUserId());
        sqlQuery.setParameter("mainId", empVo.getId());
        int cou = sqlQuery.executeUpdate();
        if (cou < 1) {
            throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
        }
    }

    //保存 自己添加的 抽检电站
    @Transactional(rollbackFor = Exception.class)
    public void saveQualityAccept(QualityAcceptVo acceptVo){
        logger.info("saveQualityAccept id:{},arr:{}",acceptVo.getId(),acceptVo.getDetails().size());
        CrmEntryQualityAcceptance qualityAcceptance=qualityAcceptanceDao.get(acceptVo.getId());
        //判断选中的电站，是否都是 未检验的电站
        Long count= Db.queryLong("SELECT COUNT(id) FROM `crm_entry_quality_acceptance_detail` d WHERE d.status<>'0' AND d.id IN ("+StringUtil.joinInSql(acceptVo.getDetails())+") ");
        if(count>0){
            throw new IllegalArgumentException("抽检状态发生改变，请刷新页面后再操作！");
        }
        SQLQuery sqlQuery = acceptanceDetailDao.getSession().createSQLQuery(" UPDATE crm_entry_quality_acceptance_detail SET dispatch_time=:dispatchTime,emp_user_id=:empUserId,status='2',accept_status='0' WHERE status='0' and id in ("+StringUtil.joinInSql(acceptVo.getDetails())+") ");
        sqlQuery.setParameter("dispatchTime", new Date());
        sqlQuery.setParameter("empUserId", qualityAcceptance.getQualityEmpUserId());
        int cou = sqlQuery.executeUpdate();
        if (cou < 1) {
            throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
        }
        logger.info(">>>>saveQualityAccept  cou:{}",cou);
        qualityAcceptance.setSampleCount(qualityAcceptance.getSampleCount()+cou);
        qualityAcceptanceDao.save(qualityAcceptance);
    }

    /**
     * 撤回质检的电站
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelAccept(String detailId){
        logger.info("cancelAccept  detailId:{}",detailId);
        GuardUtils.notBlank(detailId, "必传参数不能为空！");
        CrmEntryQualityAcceptanceDetail detail=acceptanceDetailDao.get(detailId);
        if(QualityConstants.DETAIL_STATUS_SYSTEM.equals(detail.getStatus())){
            throw new IllegalArgumentException("系统派工，不可撤回！");
        }
        if(!QualityConstants.ACCEPT_STATUS_WAIT.equals(detail.getAcceptStatus())){
              throw new IllegalArgumentException("当前电站已在质检中，不可撤回！");
        }
        detail.setAcceptStatus(null);
        detail.setStatus(QualityConstants.DETAIL_STATUS_NO);
        acceptanceDetailDao.save(detail);
        CrmEntryQualityAcceptance qualityAcceptance=qualityAcceptanceDao.get(detail.getMainId());
        qualityAcceptance.setSampleCount(qualityAcceptance.getSampleCount()-1);
        if(qualityAcceptance.getFinishCount()==qualityAcceptance.getSampleCount()){
            qualityAcceptance.setStatus(QualityConstants.QUALITY_STATUS_FINISH);
            qualityAcceptance.setFinishTime(new Date());
        }
        qualityAcceptanceDao.save(qualityAcceptance);
    }

    /**
     * 无法验收 操作
     */
    @Transactional(rollbackFor = Exception.class)
    public void canNotAcceptance(String detailId,String reason,String imgPath){
       logger.info("canNotAcceptance  detailId:{}",detailId);
        GuardUtils.notBlank(detailId, "必传参数不能为空！");
        GuardUtils.notBlank(reason, "无法验收的原因不能为空！");
        CrmEntryQualityAcceptanceDetail detail=acceptanceDetailDao.get(detailId);
        if(!QualityConstants.DETAIL_STATUS_SYSTEM.equals(detail.getStatus())){  //系统派遣的 可以操作 无法验收
            throw new IllegalArgumentException("非系统派检的电站，可直接操作撤回！");
        }
       //操作无法验收前，判断电站里面是否还有其他电站 可以分配去验收,如果没有，可以在抽检的电站，那么不能操作，无法验收
       List<String> list=Db.query(" SELECT id FROM crm_entry_quality_acceptance_detail d WHERE d.status='0' AND main_id=? ",detail.getMainId());
       if(list.size()==0){
           throw new IllegalArgumentException("已没有其他可分配电站，不能操作无法验收！");
       }
       Date date=new Date();
       detail.setStatus(QualityConstants.DETAIL_STATUS_NO_ACCEPT);
       detail.setAcceptTime(date);
       detail.setUnAcceptFile(imgPath);
       detail.setUnAcceptReason(reason);
       acceptanceDetailDao.save(detail);
       //自动抽检一个电站
        Random random=new Random();
        int idx=random.nextInt(list.size());
        String sjDetailId=list.get(idx);
        CrmEntryQualityAcceptanceDetail detailSJ=acceptanceDetailDao.get(sjDetailId);
        detailSJ.setStatus("1");
        detailSJ.setAcceptStatus("0");
        detailSJ.setDispatchTime(date);
        acceptanceDetailDao.save(detailSJ);
    }


    public LayuiPage getQualityStatisticsList(Map<String, String> map, LayuiPage page) {
        page.setData(qualityAcceptanceDao.getQualityStatisticsList(map, page));
        page.setCount(qualityAcceptanceDao.getQualityStatisticsListCount(map));
        return page;
    }

    public Map<String,Object> listSorting(ListSortingVo req) {
        Map<String,Object> resultMap = new HashMap<>();
        String id = req.getId();
        Record detailRecord= getOrderDetail(id);
        resultMap.put("detailRecord",detailRecord);
        //抽检的电站
        List<Record> cjEntry=getOrderEntryList(id,"1,2","");
        cjEntry.forEach(record -> listSort(record,req));
        //电站列表
        List<Record> wcjEntry=getOrderEntryList(id,"0,3","");
        wcjEntry.forEach(record -> listSort(record,req));
//
        wcjEntry.sort(Comparator.comparingDouble((Record r) -> r.getLong("distance")));
        cjEntry.sort(Comparator.comparingDouble((Record r) -> r.getLong("distance")));
        resultMap.put("wcjEntry",wcjEntry);
        resultMap.put("cjEntry",cjEntry);
        return resultMap;
    }

    private void listSort(Record record,ListSortingVo req){
        String longitude = record.getBigDecimal("longitude")==null?"":record.getBigDecimal("longitude").toString();
        String latitude = record.getBigDecimal("longitude")==null?"":record.getBigDecimal("latitude").toString();
        String lonLat = longitude+","+latitude;
        if(StringUtil.isAnyBlank(longitude,latitude)){
             lonLat = GaodeUtil.getLonLat(record.getStr("entryAddress"));
            if(StringUtil.isNotBlank(lonLat)){
                String[] lonLatArr = lonLat.split(",");
                longitude = lonLatArr[0];
                latitude = lonLatArr[1];
                record.set("latitude",lonLatArr[1]);
                Db.update(" update crm_customer_entry set longitude = ? ,latitude=? where id = ?",
                        longitude,latitude,record.getStr("entry_id"));
            }else {
                    lonLat = "100.0000,10.00";
            }
        }
        record.set("distance",GaodeUtil.getDistance(req.getLongitude()+","+req.getLatitude(),lonLat));
    }

    public static void main(String[] arr){
        BigDecimal ratioB=new BigDecimal("100.00");
        System.out.println(ratioB.stripTrailingZeros().toPlainString());
    }

}
