package com.sifang.modules.order.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.order.dao.CrmOrderDispatchDao;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.dao.OrderOperationInfoDao;
import com.sifang.modules.order.dao.SiteOrderDispatchDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.entity.CrmOrderDispatch;
import com.sifang.modules.order.entity.CrmOrderOperationInfo;
import com.sifang.modules.order.entity.SiteOrderDispatch;
import com.sifang.modules.order.utils.*;
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.CrmSiteUtils;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class CrmOrderDispatchService extends BaseService {
    @Autowired
    private CrmOrderDispatchDao disDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderOperationInfoDao infoDao;

    @Autowired
    private SiteOrderDispatchDao siteOrderDao;

    private static final Logger logger = LoggerFactory.getLogger(CrmOrderDispatchService.class);

    /**
     * 平台给服务商派工
    */
    @Transactional(rollbackFor=Exception.class)
    public Result dispatchOrderSite(String orderId,String siteId){
        User user = UserUtils.getUser();
        Result result = new Result();
        try {
            CrmOrder order = orderDao.get(orderId);
            if(!ApplyOrderConstants.ORDER_STATUS_DIS.equals(order.getStatus())){
                logger.info("CrmOrderDispatchService dispatchOrderSite 该工单已经不在派工单状态 userId ："+user.getId()+", orderId :"+orderId);
                return Result.fail("400");
            }
            Record site = CrmSiteUtils.getSiteById(siteId);
            String userName = CrmUtils.getUserXM(user);
         //   logger.info("CrmOrderDispatchService dispatchOrderSite dis userId ："+user.getId()+", orderId :"+orderId);
            Record rd = CrmUtils.getByUserId(user);
            String siteName = site.getStr("name");
            Date time = new Date();
            order.setSiteId(siteId);
            order.setSiteName(siteName);
            order.setUpdateTime(time);
            order.setUpdateName(userName);
            order.setDispatchTime(time);
            order.setStatus(CrmOrder.ORDERTYPETWO);
            order.setSiteStatus(CrmOrder.ORDERTYPE_ONE);
            orderDao.save(order);
            //派工表插入数据
            CrmOrderDispatch dis = new CrmOrderDispatch();
            dis.setOrderId(orderId);
            dis.setDispatchTime(time);
            dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_DJD);
            dis.setSiteId(siteId);
            dis.setSiteName(siteName);
            if(rd != null){
                dis.setEmployeeId(rd.getStr("id"));
                dis.setEmployeeName(rd.getStr("name"));
            }
            dis.setPromiseFlag(ApplyOrderConstants.FLAG_ZERO);
            dis.setCompletionResult(ApplyOrderConstants.RESULT_ZERO);
            disDao.save(dis);
            //更新过程信息
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(userName);
            ta.setC("平台人员："+userName + "派工至"+siteName+"服务商");
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(order.getId());
            ta.setT(2);
            if(StringUtil.isBlank(info.getId())){
               info.setOrder(order);
            }
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
            info.setProcessDetail(str);
            infoDao.save(info);
            result.setCode("200");
        }catch (Exception e){
            result.setCode("505");
            logger.error("CrmOrderDispatchService dispatchOrderSite Exception :"+e+"  userId ："+user.getId()+", orderId :"+orderId);
            throw e;
        }
        return result;
    }

    /**
     * 转派工单
    */
    @Transactional(rollbackFor=Exception.class)
    public Result turnDispatchOrderSite(String orderId ,String siteId,String remarks){
        User user = UserUtils.getUser();
        Result result = new Result();
        try {
            CrmOrder order = orderDao.get(orderId);
            if(!ApplyOrderConstants.ORDER_STATUS_SERVICE.equals(order.getStatus())){//不在服务中不可操作转派
                logger.info("CrmOrderDispatchService dispatchOrderSite 该工单已经不在服务中状态 userId ："+user.getId()+", orderId :"+orderId);
                return Result.fail("400","不在服务中不可操作转派");
            }
            if(!ApplyOrderConstants.FITTING_FLAG_NO.equals(order.getFittingFlag())){
                return Result.fail("402","该工单有申请备件，不能操作转派！");
            }
            //判断是否有收款记录
            List<Record> list=Db.find("SELECT id FROM `crm_order_collections` WHERE order_id=? AND STATUS='0' " ,orderId);
            if(list.size()>0){
                return Result.fail("403","该工单有收款记录，不能操作转派！");
            }
            Record site = CrmSiteUtils.getSiteById(siteId);
            String userName = CrmUtils.getUserXM(user);
            logger.info("CrmOrderDispatchService dispatchOrderSite dis userId ："+user.getId()+", orderId :"+orderId);
            String siteName = site.getStr("name");
            Date time = new Date();
            order.setSiteId(siteId);
            order.setSiteName(siteName);
            order.setUpdateTime(time);
            order.setUpdateName(userName);
            order.setDispatchTime(time);
            order.setStatus(CrmOrder.ORDERTYPETWO);
            order.setSiteStatus(CrmOrder.ORDERTYPE_ONE);
            order.setEmployeId("");
            order.setEmployeName("");
            order.setEmployeMobile("");
            order.setPromiseFlag("");
            order.setDispatchTime(time);
            order.setProcessTime(null);
            order.setSiteDispatchTime(null);
            order.setSiteProcessTime(null);
            order.setDropInTime(null);
            order.setMileage(new BigDecimal("0"));
            order.setEndTime(null);
            orderDao.save(order);
            //修改平台派工表
            CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
            if(ordis != null){
                ordis.setStatus(CrmOrder.FOUR);
                ordis.setUpdateBy(user.getId());
                ordis.setUpdateTime(time);
                ordis.setRemarks(remarks);
                disDao.save(ordis);
            }
            //修改服务商派工表
           SiteOrderDispatch siteOrdis =  siteOrderDao.getByOrderId(orderId);
            if(siteOrdis != null){
                siteOrdis.setStatus(CrmOrder.FOUR);
                siteOrdis.setUpdateBy(user.getId());
                siteOrdis.setRemarks(remarks);
                siteOrdis.setUpdateTime(time);
                siteOrderDao.save(siteOrdis);
            }

            //派工表插入数据
            Record rd = CrmUtils.getByUserId(user);
            CrmOrderDispatch dis = new CrmOrderDispatch();
            dis.setOrderId(orderId);
            dis.setDispatchTime(time);
            dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_DJD);
            dis.setSiteId(siteId);
            dis.setSiteName(siteName);
            if(rd != null){
                dis.setEmployeeId(rd.getStr("id"));
                dis.setEmployeeName(rd.getStr("name"));
            }
            disDao.save(dis);
            //更新过程信息
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(userName);
            ta.setC("平台人员："+userName + "转派至"+siteName+"服务商,转派原因: "+remarks);
            ta.setT(3);
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(order.getId());
            if(StringUtil.isBlank(info.getId())){
                info.setOrder(order);
            }
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
            info.setProcessDetail(str);
            infoDao.save(info);
            result.setCode("200");
        }catch (Exception e){
            result.setCode("505");
            logger.error("CrmOrderDispatchService dispatchOrderSite Exception :"+e+"  userId ："+user.getId()+", orderId :"+orderId);
            throw e;
        }

        return result;
    }
  //平台新建工单时直接派工，获取服务商及里程数
    public List<Record> getSiteByAdress(String customerAdress,String province,String city,String siteName){
        long startTime=System.currentTimeMillis();
        List<Record> list = null;
        if(StringUtil.isNotEmpty(siteName)){
             list =  PlantformUtils.getSiteBySiteNameList(siteName);
        }else{
            list= PlantformUtils.getSiteDefaultAddressList(province,city);
        }
        String[] lnglats;
        String lng = null;
        String lat = null;
        String lng1 = null;
        String lat1 = null;
        String customer_lnglat=null;
        double[] da = Apiutils.httpURLConectionGET(customerAdress);
        if (da != null) {
            lng = Double.toString(da[0]);
            lat = Double.toString(da[1]);
            customer_lnglat =lng +","+lat;
        }
        for(Record r:list){
           double d;
           String lnglat=r.getStr("lnglat"); //获取服务商纬度，经度
           if(StringUtil.isBlank(lnglat)){
               String siteAddr = r.getStr("province")+r.getStr("city")+r.getStr("area")+r.getStr("address");
               double[] dals = Apiutils.httpURLConectionGET(siteAddr);
               if (dals != null) {
                   lng1 = Double.toString(dals[0]);
                   lat1 = Double.toString(dals[1]);
                   lnglat =lng1 +","+lat1;
               }
           }
            if (StringUtils.isNotEmpty(lnglat) && StringUtils.isNotEmpty(customer_lnglat)) {
                d = GetDistance.getDistance(lnglat,customer_lnglat);
            } else {
                d = Double.MAX_VALUE;
            }
            r.set("distance", d);
            r.set("distance_formatted", d == Double.MAX_VALUE ? "未知" : String.format("%.2f km", d));
        }
        Collections.sort(list, new MapComparator2());
        long endTime=System.currentTimeMillis();
        System.out.println("程序运行时间： "+(endTime - startTime)+"ms");
        return list;
    }

    //计算距离
    public List<Record> getDisOrderSite(String orderId) {

        CrmOrder or = orderDao.get(orderId);
        List<Record> list =  PlantformUtils.getSiteDefaultAddressList(or.getProvince(),or.getCity());
        CalculateDistance(list,or);
        return list;
    }

    public List<Record> getOrderConditionSiteList(String orderId,String siteName){
        CrmOrder or = orderDao.get(orderId);
        List<Record> list =  PlantformUtils.getSiteBySiteNameList(siteName);
        CalculateDistance(list,or);
        return list;
    }


    public void CalculateDistance(List<Record> list,CrmOrder or){
        String[] lnglats;
        String lng = null;
        String lat = null;
        String lng1 = null;
        String lat1 = null;
        String customer_lnglat = or.getCustomerLnglat();
        long start = System.currentTimeMillis();
        if(StringUtil.isBlank(customer_lnglat)){
            String address = or.getProvince()+or.getCity()+or.getArea()+or.getCustomerAddress();
            if (StringUtils.isNotBlank(address)) {
                double[] da = Apiutils.httpURLConectionGET(address);
                if (da != null) {
                    lng = Double.toString(da[0]);
                    lat = Double.toString(da[1]);
                    customer_lnglat =lng +","+lat;
                }
            }
        }
        long zong = System.currentTimeMillis();
        for (Record r : list) {
            double d;
            String lnglat = r.getStr("lnglat");
            if(StringUtil.isBlank(lnglat)){
                String siteAddr = r.getStr("province")+r.getStr("city")+r.getStr("area")+r.getStr("address");
                double[] dals = Apiutils.httpURLConectionGET(siteAddr);
                if (dals != null) {
                    lng1 = Double.toString(dals[0]);
                    lat1 = Double.toString(dals[1]);
                    lnglat =lng1 +","+lat1;
                }
            }
            if (StringUtils.isNotEmpty(lnglat) && StringUtils.isNotEmpty(customer_lnglat)) {
                d = GetDistance.getDistance(lnglat,customer_lnglat);
            } else {
                d = Double.MAX_VALUE;
            }
            r.set("distance", d);
            r.set("distance_formatted", d == Double.MAX_VALUE ? "未知" : String.format("%.2f km", d));
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start));
        Collections.sort(list, new MapComparator2());
    }


    private static class MapComparator2 implements Comparator<Record> {
        @Override
        public int compare(Record o1, Record o2) {
            Double d1 = o1.getDouble("distance");
            Double d2 = o2.getDouble("distance");
            return d1.compareTo(d2);
        }
    }

    /**
     * 根据工单获取派工信息
     * @param orderId
     * @return
     */
    public Record getOrderDispatchInfo(String orderId) {
        String sql = "select * from crm_order_dispatch where order_id=? and status in('0','1','2','3') ";
        return Db.findFirst(sql, orderId);
    }


}
