package com.sifang.modules.order.service;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.OrderCustomerSettlementTemplateDao;
import com.sifang.modules.sunshine.SystemSetting.service.CrmOrderMileageSettingsService;
import com.sifang.modules.sunshine.SystemSetting.utils.CustomException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.financialManagement.dao.SiteAssetDao;
import com.sifang.modules.order.dao.*;
import com.sifang.modules.order.entity.*;
import com.sifang.modules.order.utils.Apiutils;
import com.sifang.modules.order.utils.Target;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.supply.order.constant.ApplyOrderConstants;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrdeCallbackService extends BaseService{

    @Autowired
    private OrdeCallbackDao callDao;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderOperationInfoDao infoDao;
    @Autowired
    private CrmOrderDispatchDao disDao;
    @Autowired
    private SiteOrderDispatchDao siteOrderDao;

    @Autowired
    private OrderCustomerSettlementTemplateDao facsetTemDao;

    @Autowired
    private CrmOrderMileageSettingsService crmOrderMileageSettingsService;


    private Logger logger = Logger.getLogger(OrdeCallbackService.class);

    public OrderCallback getOrderCallbackByOrderId(String orderId){

        return callDao.getOrderCallback(orderId);
    }


    /**
     * 平台回访并
    */
    @Transactional(rollbackFor=Exception.class)
    public Result callbackOrder(OrderCallback back,  Map<String,String> map) throws CustomException{
        Result result = new Result();

            CrmOrder or = orderDao.get(back.getOrderId());
            if(!CrmOrder.ORDERTYPETHREE.equals(or.getStatus())){
                //该工单不在待回访状态下
                result.setCode("409");
                return result;
            }
        OrderCallback call = callDao.getOrderCallback(back.getOrderId());
            if(call == null){
                call = new OrderCallback();
            }
        call.setOrderId(back.getOrderId());
            call.setResult(back.getResult());
            call.setServiceAttitude(back.getServiceAttitude());
            call.setVisitMany(back.getVisitMany());
            call.setRemarks(back.getRemarks());
            call.setVisitTotal(back.getVisitTotal());
            call.setSafetyEvaluation(back.getSafetyEvaluation());
            User user = UserUtils.getUser();
            String name = CrmUtils.getUserXM(user);
            StringBuilder bf = new StringBuilder();

            String mileageHide = map.get("mileageHide");
            if(StringUtil.isNotBlank(mileageHide)){
                or.setMileage(new BigDecimal(mileageHide));
            }

            if(ApplyOrderConstants.RESULT_OK.equals(call.getResult())){
               logger.info("平台回访工单 ，回访结果 ：已回访 ："+or.getId());
                bf.append("平台已回访,回访结果:已回访");
                or.setStatus("4");
                or.setLatestProcess("平台回访工单");
                or.setLatestProcessTime(new Date());
                or.setCallbackResult(CrmOrder.ORDERTYPE_ONE);
            }else if(ApplyOrderConstants.RESULT_BAD.equals(call.getResult())){
                logger.info("平台回访工单 ，回访结果 ：仍需上门 ："+or.getId());
                bf.append(name +" 已回访:仍需上门");
                /** 任需上门
                 crm_order_dispatch.status=1  工单平台派工表
                 crm_order_site_dispatch.status=1  工单服务商内部派工表*/
                or.setCallbackResult(CrmOrder.ORDERTYPETWO);
                or.setStatus(CrmOrder.ORDERTYPETWO);
                or.setSiteStatus(CrmOrder.SIX);
                or.setLatestProcess("平台回访工单,仍需上门");
                or.setLatestProcessTime(new Date());
                or.setEndTime(null);
                CrmOrderDispatch dis = disDao.getByOrderId(call.getOrderId());
                dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_YJD);
                disDao.save(dis);
                SiteOrderDispatch siteDis = siteOrderDao.getByOrderId(call.getOrderId());
                siteDis.setStatus(ApplyOrderConstants.SITE_STATUS_GET);
                siteOrderDao.save(siteDis);

            }else if(ApplyOrderConstants.RESULT_NO_MAN.equals(call.getResult())){
                bf.append("平台回访,回访结果:无人接听。");
            }else if(ApplyOrderConstants.RESULT_NO_REFUSE.equals(call.getResult())){
                bf.append("平台回访,回访结果:回访不通过-进入已完成。");
                //回访不通---工单直接进入已完成
                or.setStatus(ApplyOrderConstants.ORDER_STATUS_FINISH);
                or.setLatestProcess("平台回访工单--不通过-进入已完成");
                or.setLatestProcessTime(new Date());
                or.setCallbackResult(CrmOrder.ORDERTYPE_ONE);
            }else if(ApplyOrderConstants.ORDER_STATUS_FINISH.equals(call.getResult())){
                bf.append("平台回访,回访结果:多次回访。");
            }
            if(StringUtil.isNotEmpty(back.getRemarks())){
                bf.append("回访内容:"+back.getRemarks());
            }
            orderDao.save(or);
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(name);
            ta.setC(bf.toString());
            call.setSiteId(or.getSiteId());
            call.setCreateName(name);
            call.setCreateBy(user.getId());
            callDao.save(call);
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(call.getOrderId());
            ta.setT(16);
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
            info.setProcessDetail(str);
            infoDao.save(info);
            result.setCode("200");

      return result;
    }

    public Record getCallbackOrder(String orderId){
        return Db.findFirst("SELECT * FROM crm_order_callback a WHERE order_id=? ",orderId);
    }

    /**
     * 获取结算方案
    */
    public List<Record> getCustomerSettlementTemplate(String orderId){
        CrmOrder order = orderDao.get(orderId);
        String category= order.getApplianceCategory();
         String setviceType = order.getServiceType();
        String warrType = order.getWarrantyType();
        return facsetTemDao.getCustomerSettlementTemplate(category,setviceType,warrType,order.getServiceMeasures());
    }

    /**
     * 获取结算方案
    */
    public List<Record> getCustomerSettlementTemplateByStep(String orderId,String serviceStep){
        CrmOrder order = orderDao.get(orderId);
        String category= order.getApplianceCategory();
         String setviceType = order.getServiceType();
        String warrType = order.getWarrantyType();
        return facsetTemDao.getCustomerSettlementTemplate(category,setviceType,warrType,serviceStep);
    }


    /**
     * 获取平台回访信息
    */
    public Record getCallOrderByOrderId(String orderId){
        CrmOrder or = orderDao.get(orderId);
        Record rd = getOrderCallback(orderId);
        if(rd ==null){
            rd = new Record();
        }
       /* long hour= DateUtils.pastHour(or.getEndTime(),or.getSiteProcessTime());*/
        String hour= DateUtils.pastHour(or.getEndTime(),or.getProcessTime());
        String log = or.getCustomerLnglat();//用户经纬度
        if(StringUtil.isNotBlank(log)){
            double  fi =callDao.getCusaddress(log,or.getSiteId());
            rd.set("address",fi);
        }else{
            rd.set("address","未知");
        }

        rd.set("hour",hour);
        return rd;
    }

    public Record getOrderCallback(String orderId){
        String sql = " SELECT * FROM crm_order_callback c WHERE c.order_id=?  ";
        Record rd = Db.findFirst(sql,orderId);
        return rd;
    }


    /**
     * 平台重新回访
    */
    @Transactional(rollbackFor=Exception.class)
    public Result anewCallbackUpdate(Map<String,String> map){
        Result res = new Result();
        try {
            OrderCallback call=null;
            if(StringUtil.isBlank(map.get("id"))){
                call = new OrderCallback();
                call.setOrderId(map.get("orderId"));
            }else{
                call = callDao.get(map.get("id"));
            }
            CrmOrder or = orderDao.get(call.getOrderId());
            if (!or.getStatus().equals("4")) {
                res.setCode("401");
                return res;
            }
        call.setResult(map.get("result"));
        call.setRemarks(map.get("remarks"));
        call.setVisitTotal(StringUtil.isBlank( map.get("visitTotal"))? new BigDecimal("0"):new BigDecimal(map.get("visitTotal")));
        call.setVisitMany(map.get("visitMany"));
    /*    call.setSafetyEvaluation(map.get("safetyEvaluation"));*/
        call.setServiceAttitude(map.get("serviceAttitude"));
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
            Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(name);
            if(ApplyOrderConstants.RESULT_OK.equals(call.getResult())){
                ta.setC("平台重新回访,回访结果:已完成");

            }else if(ApplyOrderConstants.RESULT_BAD.equals(call.getResult())){
            logger.info("平台重新回访,回访结果:仍需上门; "+or.getId());
            ta.setC("平台重新回访,回访结果:仍需上门;"+name +"操作回访,仍需上门");
            /** 任需上门
             crm_order_dispatch.status=1
             crm_order_site_dispatch.status=1*/
            or.setStatus(CrmOrder.ORDERTYPETWO);
            or.setSiteStatus(CrmOrder.SIX);
            or.setLatestProcess("平台重新回访工单,仍需上门");
            or.setLatestProcessTime(new Date());
            or.setEndTime(null);
            or.setCallbackResult(CrmOrder.ORDERTYPETWO);
            CrmOrderDispatch dis = disDao.getByOrderId(call.getOrderId());
            dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_YJD);
            dis.setEndTime(null);
            disDao.save(dis);
            SiteOrderDispatch siteDis = siteOrderDao.getByOrderId(call.getOrderId());
            siteDis.setStatus("1");
            siteDis.setEndTime(null);
            siteOrderDao.save(siteDis);
            orderDao.save(or);
        }else  if(ApplyOrderConstants.RESULT_NO_MAN.equals(call.getResult())){
                ta.setC("平台重新回访,回访结果:无人接听");
            }else  if(ApplyOrderConstants.RESULT_NO_REFUSE.equals(call.getResult())){
                ta.setC("平台重新回访,回访结果:回访不通过");
            }
        callDao.save(call);
        ta.setT(17);
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(call.getOrderId());
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);
            res.setCode("200");
        }catch (Exception e){
            res.setCode("505");
            throw e;
        }
        return res;
    }

    /**
     * 判断是否有路程费用 -- 结算
    */
    public Map<String ,Object> getMileagePayment(CrmOrder or,String type){
        Map<String,Object> map = Maps.newHashMap();
        String Lnglat = or.getCustomerLnglat();
        BigDecimal mil = or.getMileage();
        BigDecimal big;
        if(mil.compareTo(BigDecimal.ZERO)==1){
            big = or.getMileage();
        }else{
            if(StringUtil.isBlank(Lnglat)){
                double[] dals = Apiutils.httpURLConectionGET(or.getProvince()+or.getCity()+or.getArea()+or.getCustomerAddress());
                if(dals != null){
                    Lnglat = Double.toString(dals[0])+","+Double.toString(dals[1]);
                    or.setCustomerLnglat(Lnglat);
                }
            }
            double  fi =callDao.getCusaddress(or.getCustomerLnglat(),or.getSiteId());//计算用户距离
            big = new BigDecimal(String.valueOf(fi));
        }

        BigDecimal cost = new BigDecimal("0");
        //获取设置的里程计算规则
        Record rd = crmOrderMileageSettingsService.getSiteMeleageSet(type,or.getWarrantyType());// type=1为用户
        String s_cost="0";
        if(rd != null){
            BigDecimal initial = rd.getBigDecimal("initial_value");//基本路程
            BigDecimal amount = rd.getBigDecimal("amount");
            if(big.compareTo(initial) == 1){
                cost =  (big.subtract(initial)).multiply(amount).setScale(2,BigDecimal.ROUND_DOWN);
                s_cost=cost.setScale( 0, BigDecimal.ROUND_DOWN ).toString();// 向下取整
            }
        }
        map.put("address",big);
        map.put("cost",s_cost);
        return map;
    }

    /**
     * 修改里程计算费用
    */
    public BigDecimal getNewMileage(BigDecimal mileage,String warrantyType ,String type){

        BigDecimal cost = new BigDecimal("0");

            //获取设置的里程计算规则
            Record rd = crmOrderMileageSettingsService.getSiteMeleageSet(type,warrantyType);// type=1为用户
            String s_cost="";
            if(rd != null){
                BigDecimal initial = rd.getBigDecimal("initial_value");//基本路程
                BigDecimal amount = rd.getBigDecimal("amount");
                if(mileage.compareTo(initial) == 1){
                    cost =  (mileage.subtract(initial)).multiply(amount).setScale(2,BigDecimal.ROUND_DOWN);
                    s_cost=cost.setScale( 0, BigDecimal.ROUND_DOWN ).toString();// 向下取整
                    cost = new BigDecimal(s_cost);
                }
            }

       // }
        return cost;
    }


    public long getOrderFittingCount(String orderId){
        return callDao.getOrderFittingCount(orderId);

    }


}
