package com.sifang.modules.order.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.dao.PowerStationDao;
import com.sifang.modules.customer.entity.Customer;
import com.sifang.modules.customer.entity.PowerStation;
import com.sifang.modules.sunshine.SystemSetting.dao.EmployeInformationDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteEmploye;
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.entity.CrmOrderSiteSettlement;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.order.dao.*;
import com.sifang.modules.order.entity.*;
import com.sifang.modules.order.service.excel.ExcelWrite;
import com.sifang.modules.order.service.excel.OrderExcelImportHandler;
import com.sifang.modules.order.utils.*;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingApplyDao;
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.persistence.Parameter;
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 com.sifang.modules.sys.util.LayuiPage;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class OrderService extends BaseService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderOperationInfoDao infoDao;

    @Autowired
    private CrmOrderDispatchDao disDao;
    @Autowired
    private SiteOrderDispatchDao siteOrderDao;

    @Autowired
    CrmSiteFittingApplyDao crmSiteFittingApplyDao;
    @Autowired
    private SiteOrderDispatchDao siteOrderDispatchDao;
    @Autowired
    private OrderDispatchEmployeRelDao employeRelDao;
    @Autowired
    private EmployeInformationDao empDao;
    @Autowired
    private OrdeCallbackDao ordeCallbackDao;


    @Autowired
    SiteSettlementRecordDao siteSettlementRecordDao;

    @Autowired
    private OrderCollectionsDao collectionsDao;

    @Autowired
    private OrderFeedbackDao feedDao;

    @Autowired
    private OrdeCallbackService ordeCallbackService;

    @Autowired
    private SiteInformationDao siteInformationDao;
    @Autowired
    private CustomerDao customerDao;

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

    public CrmOrder getOrderById(String id){
        if(StringUtil.isBlank(id)){
            return new CrmOrder();
        }
        return orderDao.get(id);
    }

    public void saveOrder(CrmOrder order){
        orderDao.save(order);
    }

    /**
     * 把特殊字符全替换成下划线
     * @param character
     * @return
     */
    public static String getSpecialCharacter(String character) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：\"\'’？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(character);
        return m.replaceAll("").trim();
    }

 // 验证必填的工单信息是否为空
    public Boolean checkBlack(CrmOrder order){
        Boolean flag=false;
        if(StringUtil.isBlank(order.getOrderType())){
            return  flag;
        }else if(StringUtil.isBlank(order.getServiceType())){
            return  flag;
        }else if("安装".equals(order.getServiceType()) && order.getApplianceCapacity()==null){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerName())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerMobile())){
            return  flag;
        }else if(StringUtil.isBlank(order.getProvince())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCity())){
            return  flag;
        }else if(StringUtil.isBlank(order.getArea())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerAddress())){
            return  flag;
        }
        return  true;
    }
    // 验证必填的工单信息是否为空
    public Boolean checkFlag(CrmOrder order){
        Boolean flag=false;
        if(StringUtil.isBlank(order.getOrderType())){
            return  flag;
        }else if(order.getApplianceCapacity()==null){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerName())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerMobile())){
            return  flag;
        }else if(StringUtil.isBlank(order.getProvince())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCity())){
            return  flag;
        }else if(StringUtil.isBlank(order.getArea())){
            return  flag;
        }else if(StringUtil.isBlank(order.getCustomerAddress())){
            return  flag;
        }
        return  true;
    }
    /**
     * 平台添加工单
    */
    @Transactional(rollbackFor=Exception.class)
    public Object SaveOrder(CrmOrder order, User user) throws CustomException{
        Result result = new Result();
        Date time = new Date();
            logger.info("平台新增工单 SaveOrder , order  :" +order);
           String number ="";
            if(ApplyOrderConstants.SERVICE_TYPE_AZ.equals(order.getServiceType())){
                number = "AZ"+ PlantformUtils.getOrderNumber();
            }else if(ApplyOrderConstants.SERVICE_TYPE_ZX.equals(order.getServiceType())){
                number = "ZX"+ PlantformUtils.getOrderNumber();
            }else{
                number = "WX"+ PlantformUtils.getOrderNumber();
            }
                String UserName = CrmUtils.getUserXM(user);
                order.setNumber(number);
                order.setCreateTime(time);
                order.setCreateBy(user.getId());
                if(order.getProcessTime() !=null){
                    order.setPromiseFlag("1");
                }
                order.setLatestProcess(UserName+"报修");
                order.setLatestProcessTime(time);
                if(StringUtil.isNotBlank(order.getCustomerAddress())){
                    order.setCustomerAddress(getSpecialCharacter(order.getCustomerAddress().trim()));
                }
                double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
                if(dals != null){
                    order.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
                    double addre=  ordeCallbackDao.getCusaddress(order.getCustomerLnglat(),order.getSiteId());
                    order.setMileage(new BigDecimal(addre));
                }
                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(UserName);
                ta.setC(UserName + "接入");
                ta.setT(Target.NEW_ORDER);

                if(StringUtil.isNotEmpty(order.getMemoNote())){
                    order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_FINISH);
                    order.setStatus(ApplyOrderConstants.ORDER_STATUS_FINISH);
                    ta.setC(ta.getC()+",并直接封单，封单备注："+order.getMemoNote());
                }

        String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");

                //新建工单并且直接派单到服务商
                if(StringUtil.isNotBlank(order.getSiteId())){
                    Record site = CrmSiteUtils.getSiteById(order.getSiteId());
                    String siteName = site.getStr("name");
                    logger.info("平台新建工单并派工到服务商：order:"+order +"派工至服务商："+siteName);
                    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(order.getId());
                    dis.setDispatchTime(time);
                    dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_DJD);
                    dis.setSiteId(order.getSiteId());
                    dis.setSiteName(siteName);
                    dis.setPromiseFlag("0");
                    dis.setCompletionResult(ApplyOrderConstants.RESULT_ZERO);
                    disDao.save(dis);
                    logger.info("平台新建工单并派工到服务商：order:"+order +"派工至服务商："+siteName+" ，保存派工记录");

                    /**向工单操作/跟踪明细记录表添加数据
                     */
                    Target ta2 = new Target();
                    ta2.setD(DateUtils.getDateTime());
                    ta2.setP(UserName);
                    ta2.setC("平台人员："+UserName + "新建工单并直接派工至"+siteName+"服务商");
                    CrmOrderOperationInfo info2 = new CrmOrderOperationInfo();
                    ta2.setT(2);
                    info2.setOrder(order);
                    String str2 = WebPageFunUtils.appendOrderProcessDetail(ta2, info2.getProcessDetail());
                    info2.setProcessDetail(str2);
                    infoDao.save(info2);
                    result.setCode("200");

                }else{
                    logger.info("平台新建工单 ，没有直接派工，保存新建的工单：order"+order.getBdImgs());
                    //只是新建工单
                    orderDao.save(order);
                    /**向工单操作/跟踪明细记录表添加数据
                     */
                    CrmOrderOperationInfo info = new CrmOrderOperationInfo();
                    //  info.setSiteId(order.getSiteId());
                    info.setOrder(order);
                    info.setProcessDetail(str);
                    infoDao.save(info);
                    result.setCode("200");
                }
        return result;
    }
    /**
     * 平台添加渠道商安装单
     */
    @Transactional(rollbackFor=Exception.class)
    public Object saveChannelBusinessOrder(CrmOrder order, User user) throws CustomException{
        Result result = new Result();
        Date time = new Date();
        logger.info("平台新增渠道商安装单 SaveOrder , order  :" +order);
        String number = "AZ"+ PlantformUtils.getOrderNumber();
        String UserName = CrmUtils.getUserXM(user);
        order.setNumber(number);
        order.setCreateTime(time);
        order.setCreateBy(user.getId());
        order.setServiceType("安装");
       order.setSpecialInstallation("2");
        order.setLatestProcess(UserName+"报修渠道商安装单");
        order.setStatus(ApplyOrderConstants.ORDER_STATUS_FINISH);
        order.setLatestProcessTime(time);
        if(StringUtil.isNotBlank(order.getCustomerAddress())){
            order.setCustomerAddress(getSpecialCharacter(order.getCustomerAddress().trim()));
        }
        double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
        if(dals != null){
            order.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
        }
        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(UserName);
        ta.setC(UserName + "报修渠道商安装单");
        ta.setT(Target.NEW_ORDER);
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
            logger.info("平台新建渠道商安装单 ：order"+order.getBdImgs());
            //只是新建工单
            orderDao.save(order);
            CrmOrderOperationInfo info = new CrmOrderOperationInfo();
            info.setOrder(order);
            info.setProcessDetail(str);
            infoDao.save(info);
            result.setCode("200");
        return result;
    }
/***
 * 平台保存修改的渠道商工单
 */

@Transactional(rollbackFor=Exception.class)
public Object UpdateChannelBusinessOrder(CrmOrder order,User user) throws CustomException{
    Result re = new Result();
    logger.info("平台修改渠道商工单 CrmOrderId: "+order.getId());
    StringBuilder content = new StringBuilder();
    CrmOrder or = orderDao.get(order.getId());

    if(StringUtil.isNotBlank(or.getCustomerName()) && !or.getCustomerName().equals(order.getCustomerName())){
        content.append(" ;用户姓名："+or.getCustomerName()+", 修改为："+order.getCustomerName());
    }
    if(!or.getApplianceCapacity().equals(order.getApplianceCapacity())){
        content.append(" ;容量："+or.getApplianceCapacity()+", 修改为："+order.getApplianceCapacity());
    }
    if(StringUtil.isNotBlank(or.getCustomerMobile()) && !or.getCustomerMobile().equals(order.getCustomerMobile())){
        content.append(" ;联系方式一："+or.getCustomerMobile()+", 修改为："+order.getCustomerMobile());
    }else if(StringUtil.isBlank(or.getCustomerMobile()) && StringUtil.isNotBlank(order.getCustomerMobile())){
        content.append(" ;联系方式一 修改为："+order.getCustomerMobile());
    }

    if(StringUtil.isNotBlank(or.getCustomerTelephone()) && !or.getCustomerTelephone().equals(order.getCustomerTelephone())){
        content.append(" ;联系方式二："+or.getCustomerTelephone()+", 修改为："+order.getCustomerTelephone());
    }else if(StringUtil.isBlank(or.getCustomerTelephone()) && StringUtil.isNotBlank(order.getCustomerTelephone())){
        content.append(" ;联系方式二 修改为："+order.getCustomerTelephone());
    }

    String org_address= or.getProvince()+or.getCity()+or.getArea()+or.getCustomerAddress();
    String new_address=order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress();
    if(!org_address.equals(new_address)){
        content.append(" ;详细地址："+org_address+" , 修改为："+new_address);
        order.setCustomerAddress(getSpecialCharacter(order.getCustomerAddress().trim()));

    }
    if( or.getApplianceBuyTime()!=null && order.getApplianceBuyTime()!=null && !DateUtils.formatYMDDateTime(or.getApplianceBuyTime()).equals(DateUtils.formatYMDDateTime(order.getApplianceBuyTime()))){
        content.append(" ;投运日期："+or.getApplianceBuyTime()+" ,修改为："+DateUtils.formatDateTime(order.getApplianceBuyTime()));
    }else if(or.getApplianceBuyTime()==null && order.getApplianceBuyTime()!=null){
        content.append(" ;投运日期 修改为："+DateUtils.formatDateTime(order.getApplianceBuyTime()));
    }

    if(StringUtil.isNotBlank(or.getRemarks()) && !or.getRemarks().equals(order.getRemarks())){
        content.append(" ;现场描述 ："+or.getRemarks()+ " , 修改为："+order.getRemarks());
    }else if(StringUtil.isBlank(or.getRemarks()) && StringUtil.isNotBlank(order.getRemarks())){
        content.append(" ;现场描述 修改为："+order.getRemarks());
    }
    if(StringUtil.isNotBlank(order.getApplianceCategory()) && !order.getApplianceCategory().equals(or.getApplianceCategory())){
        //修改了设备类型
        content.append("  ;原设备类型 ："+or.getApplianceCategory()+" ,修改为 ").append(order.getApplianceCategory());
    }else if(StringUtil.isNotBlank(order.getWarrantyType()) && !order.getWarrantyType().equals(or.getWarrantyType())){
        //修改了保修类型
        String type = "";
        String newType="";
        if(or.getWarrantyType().equals(ApplyOrderConstants.WARRANTY_TYPE_ONE)){
            type ="保内";
        }else if(or.getWarrantyType().equals(ApplyOrderConstants.WARRANTY_TYPE_TWO)){
            type ="保外";
        }
        if(order.getWarrantyType().equals(ApplyOrderConstants.WARRANTY_TYPE_ONE)){
            newType ="保内";
        }else if(order.getWarrantyType().equals(ApplyOrderConstants.WARRANTY_TYPE_TWO)){
            newType ="保外";
        }
        content.append(" ;原保修类型："+type+", 修改为 ").append(newType);
    }
    String UserName = CrmUtils.getUserXM(user);
    or.setApplianceCapacity(order.getApplianceCapacity());
    or.setLatestProcessTime(new Date());
    or.setLatestProcess(UserName+ "修改渠道商工单");
    or.setUpdateName(UserName);
    or.setUpdateTime(new Date());

    or.setServiceMeasures(order.getServiceMeasures());
    or.setOrderType(order.getOrderType());
    or.setCustomerName(order.getCustomerName());
    or.setCustomerMobile(order.getCustomerMobile());
    or.setCustomerTelephone(order.getCustomerTelephone());
    or.setProvince(order.getProvince());
    or.setCity(order.getCity());
    or.setArea(order.getArea());
    or.setCustomerAddress(order.getCustomerAddress());
    //更新经纬度信息
    double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
    if(dals != null){
        or.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
    }
    if(StringUtil.isNotBlank(order.getPowerStationName())){
        or.setPowerStationName(order.getPowerStationName());
    }
    if(StringUtil.isNotBlank(order.getApplianceCategory())){
        or.setApplianceCategory(order.getApplianceCategory());
    }
    or.setApplianceModel(order.getApplianceModel());
    or.setApplianceBuyTime(order.getApplianceBuyTime());
    if(StringUtil.isNotBlank(order.getApplianceBrand())){
        or.setApplianceBrand(order.getApplianceBrand());
    }

    or.setApplianceMachineCode(order.getApplianceMachineCode());
    if(StringUtil.isNotBlank(order.getWarrantyType())){
        or.setWarrantyType(order.getWarrantyType());
    }
    or.setPromiseTime(order.getPromiseTime());
    or.setPromiseLimit(order.getPromiseLimit());
    or.setPleaseReferMall(order.getPleaseReferMall());
    or.setInvoice(order.getInvoice());
    or.setLevel(order.getLevel());
    or.setRemarks(order.getRemarks());
    or.setBdImgs(order.getBdImgs());
    orderDao.save(or);
    Target ta = new Target();
    ta.setD(DateUtils.getDateTime());
    ta.setP(UserName);
    ta.setT(Target.DISPATCH_ORDER);
    ta.setC(UserName + "修改渠道商工单:"+content.toString());
    CrmOrderOperationInfo info = infoDao.getOperaByOrderId(order.getId());
    if(StringUtil.isBlank(info.getId())){
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
        info.setSiteId(or.getSiteId());
        info.setOrder(or);
        info.setProcessDetail(str);
    }else{
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
    }
    infoDao.save(info);
    re.setCode("200");
    return re;
}


    /**
     * 工单过程信息
    */
    public List<Target> getOrderDetail(String orderId){
        return infoDao.getOrderDetail(orderId);
    }

    /**
     * 无效工单
    */
    @Transactional(rollbackFor=Exception.class)
    public Result invalidOrder(String orderId,User user,String description){
        CrmOrder order  = orderDao.get(orderId);
        if(Integer.parseInt(order.getStatus()) > 1){
            return Result.fail("400","已完成不可操作无效");
        }
        logger.info("无效工单 操作无效工单 SaveOrder   , order  :" +order.getId());
        String UserName = CrmUtils.getUserXM(user);
        order.setStatus(ApplyOrderConstants.ORDER_STATUS_INVALID);
        order.setLatestProcessTime(new Date());
        order.setLatestProcess(UserName+ "无效工单");
        order.setDisableResource(description);
        String name = UserUtils.getUser().getLoginName();
        order.setUpdateName(name);//更新人名字
        order.setUpdateTime(new Date());//更新时间
        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(UserName);
        ta.setC(UserName + "确认无效工单，无效原因:"+order.getDisableResource());
        ta.setT(Target.MARK_ORDER);
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);
        orderDao.save(order);
        return Result.ok();
    }

    /**
     * 平台直接封单
     * @param orderId   工单id
     * @param user      当前登录用户实体类
     * @param consultOrder  封单备注
     *
    */
    @Transactional(rollbackFor=Exception.class)
    public Result consultOrderSave(String orderId,User user,String consultOrder){
        CrmOrder order  = orderDao.get(orderId);

        if(!ApplyOrderConstants.ORDER_STATUS_DIS.equals(order.getStatus())){
            return Result.fail("402","该工单不可直接封单！");
        }
        if(!ApplyOrderConstants.SERVICE_TYPE_ZX.equals(order.getServiceType())){
            return Result.fail("402","该工单不是咨询工单，可直接封单！");
        }

        logger.info("平台操作直接封单工单 SaveOrder userId  :"+user.getId()+", order  :" +order.getId());
        String UserName = CrmUtils.getUserXM(user);
        order.setStatus(ApplyOrderConstants.ORDER_STATUS_FINISH);
        order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_FINISH);
        order.setLatestProcessTime(new Date());
        order.setLatestProcess(UserName+ "直接封单");
        order.setMemoNote(consultOrder);
        String name = UserUtils.getUser().getLoginName();
        order.setUpdateName(name);//更新人名字
        order.setUpdateTime(new Date());//更新时间
        //修改平台派工表
        Date time = new Date();

        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(UserName);
        ta.setC("平台人员:"+UserName + " 直接封单，封单备注:"+consultOrder);
        ta.setT(Target.MARK_ORDER);
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        if(info.getOrder()==null){
            info.setOrder(order);
        }
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);
        orderDao.save(order);
        return Result.ok();
    }



    /**
     * 平台无效工单
    */
    @Transactional(rollbackFor=Exception.class)
    public Result platformInvalidOrder(String orderId,User user,String description){
        CrmOrder order  = orderDao.get(orderId);
        if(Integer.parseInt(order.getStatus()) > 4){

            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","该工单有收款记录，不能操作无效！");
        }
        logger.info("平台操作无效工单 SaveOrder userId  :"+user.getId()+", order  :" +order.getId());
        String UserName = CrmUtils.getUserXM(user);
        order.setStatus(ApplyOrderConstants.ORDER_STATUS_INVALID);
        order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_INVALID);
        order.setLatestProcessTime(new Date());
        order.setLatestProcess(UserName+ "无效工单");
        order.setDisableResource(description);
        String name = UserUtils.getUser().getLoginName();
        order.setUpdateName(name);//更新人名字
        order.setUpdateTime(new Date());//更新时间
        //修改平台派工表
        Date time = new Date();
        CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
        if(ordis != null){
            if(StringUtil.isNotBlank(ordis.getId())){
                ordis.setStatus(CrmOrder.FIVE);
                ordis.setUpdateBy(user.getId());
                ordis.setUpdateTime(time);
                ordis.setRemarks("无效");
                disDao.save(ordis);
            }
        }

        //修改服务商派工表
        SiteOrderDispatch siteOrdis =  siteOrderDao.getByOrderId(orderId);
        if(siteOrdis != null){
            if(StringUtil.isNotBlank(siteOrdis.getId())){
                siteOrdis.setStatus(CrmOrder.FIVE);
                siteOrdis.setUpdateBy(user.getId());
                siteOrdis.setUpdateTime(time);
                siteOrderDao.save(siteOrdis);
            }
        }
        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(UserName);
        ta.setC("平台人员:"+UserName + " 确认无效工单，无效原因:"+order.getDisableResource());
        ta.setT(Target.MARK_ORDER);
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        if(info.getOrder()==null){
            info.setOrder(order);
        }
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);
        orderDao.save(order);
        return Result.ok();
    }

    /**
     * 服务商无效工单
     */
    @Transactional(rollbackFor=Exception.class)
    public Result siteInvalidOrder(String orderId,User user,String description){
        CrmOrder order  = orderDao.get(orderId);
        if(Integer.parseInt(order.getStatus()) == 7){
            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","该工单有收款记录，不能操作无效！");
        }
        logger.info("平台操作无效工单 SaveOrder userId  :"+user.getId()+", order  :" +order.getId());
        String UserName = CrmUtils.getUserXM(user);
        order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_INVALID);
        order.setLatestProcessTime(new Date());
        order.setLatestProcess(UserName+ "无效工单");
        order.setDisableResource(description);
        String name = UserUtils.getUser().getLoginName();
        order.setUpdateName(name);//更新人名字
        order.setUpdateTime(new Date());//更新时间
        order.setStatus(ApplyOrderConstants.ORDER_STATUS_INVALID);
        //修改平台派工表
        Date time = new Date();
        CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
        if(ordis != null){
            if(StringUtil.isNotBlank(ordis.getId())){
                ordis.setStatus(CrmOrder.FIVE);
                ordis.setUpdateBy(user.getId());
                ordis.setUpdateTime(time);
                ordis.setRemarks("无效");
                disDao.save(ordis);
            }
        }

        //修改服务商派工表
        SiteOrderDispatch siteOrdis =  siteOrderDao.getByOrderId(orderId);
        if(siteOrdis != null){
            if(StringUtil.isNotBlank(siteOrdis.getId())){
                siteOrdis.setStatus(CrmOrder.FIVE);
                siteOrdis.setUpdateBy(user.getId());
                siteOrdis.setUpdateTime(time);
                siteOrderDao.save(siteOrdis);
            }
        }
        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(UserName);
        ta.setC("平台人员:"+UserName + " 确认无效工单，无效原因:"+order.getDisableResource());
        ta.setT(Target.MARK_ORDER);
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        if(info.getOrder()==null){
            info.setOrder(order);
        }
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);
        orderDao.save(order);
        return Result.ok();
    }


    /**
     * 修改工单
     * 后续需要记录具体修改那一项
    */
    @Transactional(rollbackFor=Exception.class)
    public Object updateOrder(CrmOrder order,User user) throws CustomException{
        Result re = new Result();
        logger.info("update_order CrmOrderId: "+order.getId());
        StringBuilder content = new StringBuilder();
        CrmOrder or = orderDao.get(order.getId());

        if(StringUtil.isNotBlank(or.getCustomerName()) && !or.getCustomerName().equals(order.getCustomerName())){
            content.append(" ，用户姓名："+or.getCustomerName()+", 修改为："+order.getCustomerName());
        }
        if(StringUtil.isNotBlank(or.getCustomerMobile()) && !or.getCustomerMobile().equals(order.getCustomerMobile())){
            content.append(" ，联系方式一："+or.getCustomerMobile()+", 修改为："+order.getCustomerMobile());
        }else if(StringUtil.isBlank(or.getCustomerMobile()) && StringUtil.isNotBlank(order.getCustomerMobile())){
            content.append(" ，联系方式一 修改为："+order.getCustomerMobile());
        }

        if(StringUtil.isNotBlank(or.getCustomerTelephone()) && !or.getCustomerTelephone().equals(order.getCustomerTelephone())){
            content.append(" ，联系方式二："+or.getCustomerTelephone()+", 修改为："+order.getCustomerTelephone());
        }else if(StringUtil.isBlank(or.getCustomerTelephone()) && StringUtil.isNotBlank(order.getCustomerTelephone())){
            content.append(" ，联系方式二 修改为："+order.getCustomerTelephone());
        }

        String org_address= or.getProvince()+or.getCity()+or.getArea()+or.getCustomerAddress();
        String new_address=order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress();
        if(!org_address.equals(new_address)){
            content.append(" ，详细地址："+org_address+", 修改为："+new_address);
                order.setCustomerAddress(getSpecialCharacter(order.getCustomerAddress().trim()));
            double[] dals = Apiutils.httpURLConectionGET(new_address);
            if(dals != null) {
                order.setCustomerLnglat(Double.toString(dals[0]) + "," + Double.toString(dals[1]));
                double addre=  ordeCallbackDao.getCusaddress(order.getCustomerLnglat(),or.getSiteId());
                or.setMileage(new BigDecimal(addre));
            }else{
                order.setCustomerLnglat("");
            }
        }
        if( or.getApplianceBuyTime()!=null && order.getApplianceBuyTime()!=null && !DateUtils.formatYMDDateTime(or.getApplianceBuyTime()).equals(DateUtils.formatYMDDateTime(order.getApplianceBuyTime()))){
            content.append("，投运日期："+or.getApplianceBuyTime()+"修改为："+DateUtils.formatDateTime(order.getApplianceBuyTime()));
        }else if(or.getApplianceBuyTime()==null && order.getApplianceBuyTime()!=null){
            content.append("，投运日期 修改为："+DateUtils.formatDateTime(order.getApplianceBuyTime()));
        }

        String st=" ，故障描述";
        if("安装".equals(or.getServiceType())){
          st=" , 现场描述";
        }
        if(StringUtil.isNotBlank(or.getRemarks()) && !or.getRemarks().equals(order.getRemarks())){
            content.append(st + "  ："+or.getRemarks()+", 修改为："+order.getRemarks());
        }else if(StringUtil.isBlank(or.getRemarks()) && StringUtil.isNotBlank(order.getRemarks())){
            content.append(st+ "  修改为："+order.getRemarks());
        }
            if(StringUtil.isNotBlank(order.getApplianceCategory()) && !order.getApplianceCategory().equals(or.getApplianceCategory())){
                //修改了设备类型
                content.append("  ，原设备类型 ："+or.getApplianceCategory()+"修改为 ").append(order.getApplianceCategory());
            }else if(StringUtil.isNotBlank(order.getWarrantyType()) && !order.getWarrantyType().equals(or.getWarrantyType())){
                //修改了保修类型
                String type = "";
                if(or.getWarrantyType() != null){
                    if(or.getWarrantyType().equals("1")){
                        type ="保内";
                    }else if(or.getWarrantyType().equals("2")){
                        type ="保外";
                    }
                }
                String newType="";
                if(order.getWarrantyType().equals("1")){
                    newType ="保内";
                }else if(order.getWarrantyType().equals("2")){
                    newType ="保外";
                }
                content.append(" ，原保修类型："+type+", 修改为 ").append(newType);
            }
            String UserName = CrmUtils.getUserXM(user);

            or.setLatestProcessTime(new Date());
            or.setLatestProcess(UserName+ "修改工单");
            or.setUpdateName(UserName);
            or.setUpdateTime(new Date());
            or.setApplianceCapacity(order.getApplianceCapacity());
           or.setServiceMeasures(order.getServiceMeasures());
           or.setOrderType(order.getOrderType());
            or.setCustomerName(order.getCustomerName());
            or.setCustomerMobile(order.getCustomerMobile().trim());
            or.setCustomerTelephone(order.getCustomerTelephone().trim());
            or.setProvince(order.getProvince());
            or.setCity(order.getCity());
            or.setArea(order.getArea());
            or.setCustomerAddress(order.getCustomerAddress());
            //更新经纬度信息
          /*  double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
            if(dals != null){
                or.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
                double addre=  ordeCallbackDao.getCusaddress(or.getCustomerLnglat(),or.getSiteId());
                or.setMileage(new BigDecimal(addre));
            }*/

        or.setPowerStationName(order.getPowerStationName());
        or.setApplianceCategory(order.getApplianceCategory());
          or.setApplianceModel(order.getApplianceModel());
        or.setApplianceBuyTime(order.getApplianceBuyTime());
        or.setApplianceBrand(order.getApplianceBrand());
           or.setApplianceMachineCode(order.getApplianceMachineCode());
        or.setWarrantyType(order.getWarrantyType());
        or.setPromiseTime(order.getPromiseTime());
        or.setPromiseLimit(order.getPromiseLimit());
        or.setPleaseReferMall(order.getPleaseReferMall());
        or.setInvoice(order.getInvoice());
        or.setLevel(order.getLevel());
        or.setRepairTime(order.getRepairTime());
        or.setRemarks(order.getRemarks());
          or.setBdImgs(order.getBdImgs());
            orderDao.save(or);
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(UserName);
            ta.setT(Target.DISPATCH_ORDER);
            ta.setC(UserName + "修改工单:"+content.toString());
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(order.getId());
            if(StringUtil.isBlank(info.getId())){
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
                info.setSiteId(or.getSiteId());
                info.setOrder(or);
                info.setProcessDetail(str);
            }else{
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
            }
            infoDao.save(info);
            re.setCode("200");

       return re;
    }


    public LayuiPage<Record> getPlatformOrderPage(LayuiPage<Record> page ,  Map<String,String> map){
        List<Record> list = orderDao.getPlatformOrdersList(page,map);
        long count = orderDao.getPlatformOrdersCount(map);
        page.setCount(count);
        page.setData(list);
        return page;
    }

    public LayuiPage<Record> getWaitingforOrdersPage(LayuiPage<Record> page ,  Map<String,String> map){
        List<Record> list = orderDao.getWaitingforOrdersList(page,map);
        long count = orderDao.getWaitingforOrdersCount(map);
        page.setCount(count);
        page.setData(list);
        return page;
    }
        //平台查看渠道商工单
        public LayuiPage<Record> getChannelBusinessOrdersPage(LayuiPage<Record> page ,  Map<String,String> map){
            List<Record> list = orderDao.getChannelBusinessList(page,map);
            long count = orderDao.getChannelBusinessCount(map);
            page.setCount(count);
            page.setData(list);
            return page;
        }

    public LayuiPage<Record> getPlatformOrderStatus(LayuiPage<Record> page ,  Map<String,String> map,String status){
        List<Record> list = orderDao.getPlatformOrdersStatus(page,map,status);
        long count = orderDao.getPlatformOrdersStatusCount(map,status);
        page.setCount(count);
        page.setData(list);
        return page;
    }

    public LayuiPage<Record> getManyTimesPlatformOrder(LayuiPage<Record> page ,  Map<String,String> map){
        List<Record> list = orderDao.getManyTimesPlatformOrders(page,map);
        long count = orderDao.getgetManyTimesPlatformOrdersCount(map);
        page.setCount(count);
        page.setData(list);
        return page;
    }

    //待备件
    public LayuiPage<Record> getPlatformFittingOrderPage(LayuiPage<Record> page ,  Map<String,String> map){
        List<Record> list = orderDao.getPlatformFittingOrderList(page,map);
        long count = orderDao.getPlatformFittingOrderCount(map);
        page.setCount(count);
        page.setData(list);
        return page;
    }
    //投诉单
    public LayuiPage<Record> getComplaintOrderPage(LayuiPage<Record> page ,  Map<String,String> map){
        List<Record> list = orderDao.getComplaintOrderList(page,map);
        long count = orderDao.getComplaintOrderCount(map);
        page.setCount(count);
        page.setData(list);
        return page;
    }

    /**
     * 标记工单
    */
    public Result flagOrder(String orderId,String flag){
        CrmOrder or = orderDao.get(orderId);
        or.setFlag(flag);
        orderDao.save(or);
        return Result.ok();
    }
        //跟进记录
    public void followUpInformation(String orderId ,String track){
        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        User user = UserUtils.getUser();
        Record rd = CrmUtils.getByUserId(user);
        ComplaintReply ta = new ComplaintReply();
        ta.setT(DateUtils.getDateTime());
        ta.setP(rd.getStr("name"));
        ta.setC("操作人-"+rd.getStr("name")+" 跟进信息,操作内容-"+track);
        String str = WebPageFunUtils.appendProcessDetail(ta, info.getTrackDetail());
        info.setTrackDetail(str);
        infoDao.save(info);
    }

    //获取跟进记录
    public List<ComplaintReply> getTrackDetail(String orderId){
        return infoDao.getTrackDetail(orderId);
    }

    /**
     * 服务商查看全部工单
    */
    public Map<String,Object> getSiteOrderList(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getSiteOrdersList(page,map,siteId);
        for (Record record : list) {
            if (record.getStr("create_by")!=null) {
                if (record.getStr("create_by").equals("1")) {
                    record.set("createName", "system");
                }
            }
        }
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getSiteOrdersCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }

    /**
     * 服务商查看服务中
    */
    public Map<String,Object> getInServiceOrderBySiteId(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getInServiceOrderBySiteId(page,map,siteId,"");
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getInServiceOrderCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }

    /**
     * 服务商查看待接收
     */
    public Map<String,Object> getWaitReceiveData(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getWaitReceiveData(page,map,siteId);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getWaitReceiveCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }

    /**
     * 服务商查看待派工
     */
    public Map<String,Object> getWaitWorkData(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getWaitWorkData(page,map,siteId);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getWaitWorkCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }
    /**
     * 服务商查看已完工
     */
    public Map<String,Object> getWorkFinishData(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getWorkFinishData(page,map,siteId);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getWorkFinishCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }

    /**
     * 获取无效单数据
     * @param page
     * @param map
     * @param status
     * @return
     */
    public LayuiPage<Record> getWorkInvalidData(LayuiPage<Record> page ,  Map<String,String> map,String status,String siteId){
        List<Record> list = orderDao.getWorkInvalidData(page,map,siteId);
        long count = orderDao.getWorkInvalidDataCount(map,siteId);
        page.setCount(count);
        page.setData(list);
        return page;
    }

    /**
     * 服务商查看已结算
     */
    public Map<String,Object> getWorkSettlementData(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getWorkSettlementData(page,map,siteId);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getWorkSettlementCount(map,siteId);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }
    /**
     * 服务商查看配件单
    */
    public Map<String,Object> getSitePartsOrderList(Map<String,String> map ,String siteId, LayuiPage<Record> page){
        List<Record> list = orderDao.getSitePartsOrderList(page,siteId,map);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        long count = orderDao.getSitePartsOrderCount(siteId,map);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",count);
        sitemap.put("orderList",mapx);
        return sitemap;
    }


    /**
     * 工程师接收工单
     */
    @Transactional(rollbackFor=Exception.class)
    public Result employeReceiveOrder(String orderId,String userId){
        Result result = new Result();
        String[] orderIds = orderId.split(",");
        Date time = new Date();
        try {
            for(String id : orderIds){
                CrmOrder order = orderDao.get(id);
                Record employe=CrmUtils.getEmployeId(userId);
              //  CrmSiteEmploye emp =empDao.get(order.getEmployeId());
                order.setStatus(ApplyOrderConstants.ORDER_STATUS_SERVICE);
                order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_DOOR);
                order.setLatestProcess("工程师"+employe.getStr("name")+"  已接收。联系电话："+(employe.getStr("mobile")));
                order.setLatestProcessTime(time);
                order.setProcessTime(time);
                order.setSiteProcessTime(time);
                orderDao.save(order);

                SiteOrderDispatch ordis = siteOrderDao.getByOrderId(id);
                if(ordis != null){
                    ordis.setStatus(CrmOrder.ORDERTYPE_ONE);
                    ordis.setPromiseTime(time);
                    siteOrderDao.save(ordis);
                }

                CrmOrderOperationInfo info = infoDao.getOperaByOrderId(id);
                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(employe.getStr("name"));
                ta.setC("工程师"+employe.getStr("name")+" 已接单。联系电话："+(employe.getStr("mobile")));
                ta.setT(Target.WAIT_NOT_DISPATCH);
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
                infoDao.save(info);
            }
            result.setCode("200");
        }catch (Exception e){
            result.setCode("204");
            throw e;
        }

        return result;
    }



    /**
     * 服务商接收工单
     */
    @Transactional(rollbackFor=Exception.class)
    public Result siteReceiveOrder(String orderId,String siteId){
        Result result = new Result();
        String[] orderIds = orderId.split(",");
        Date time = new Date();
        try {
            for(String id : orderIds){
                CrmOrder order = orderDao.get(id);
                if(!ApplyOrderConstants.SITE_STATUS_GET.equals(order.getSiteStatus())){
                    new Exception("工单中有已经被接收的工单");
                    break;
                }

                CrmSite site = siteInformationDao.get(order.getSiteId());
                order.setStatus(ApplyOrderConstants.ORDER_STATUS_SERVICE);
                order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_DIS);
                order.setLatestProcess(order.getSiteName()+" 服务商 工单已接收。联系电话："+(site.getMobile()==null?site.getTelephone():site.getMobile()));
                order.setLatestProcessTime(time);
                order.setProcessTime(time);
                orderDao.save(order);

                SiteOrderDispatch ordis = siteOrderDao.getByOrderId(id);
                if(ordis != null){
                    ordis.setStatus(CrmOrder.ORDERTYPE_ONE);
                    ordis.setPromiseTime(time);
                    siteOrderDao.save(ordis);
                }

                CrmOrderOperationInfo info = infoDao.getOperaByOrderId(id);
                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(order.getSiteName());
                ta.setC(order.getSiteName()+"服务商 工单已接收。联系电话："+(site.getMobile()==null?site.getTelephone():site.getMobile()));
                ta.setT(Target.WAIT_NOT_DISPATCH);
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
                infoDao.save(info);
            }
            result.setCode("200");
        }catch (Exception e){
            result.setCode("204");
            result.setMsg(e.getMessage());
            throw e;
        }

        return result;
    }

    /**
     * 服务商拒接工单
     */
    @Transactional(rollbackFor=Exception.class)
    public Result siteRefuseOrder(String orderId,String siteId){
        Result result = new Result();
        if(StringUtil.isBlank(orderId) || StringUtil.isBlank(siteId)){
            result.setCode("505");
            return result;
        }
        String[] orderIds = orderId.split(",");
        Date time = new Date();
        try {
            for(String id : orderIds){
                CrmOrder order = orderDao.get(id);
                if(!order.getSiteId().equals(siteId)){
                    result.setCode("505");//该工单已经不属于该服务商
                    return result;
                }
                if(!ApplyOrderConstants.SITE_STATUS_GET.equals(order.getSiteStatus())){
                    result.setCode("506");//该工单已不在待接单状态，无法拒接工单
                    continue;
                }
                CrmSite site = siteInformationDao.get(order.getSiteId());

                String name = order.getSiteName();
                String currentName = CrmUtils.getUserXM(UserUtils.getUser());
                order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_REFUSE);
                order.setStatus(ApplyOrderConstants.ORDER_STATUS_DIS);
                order.setLatestProcess(currentName+"  已拒接");
                order.setLatestProcessTime(time);
                order.setProcessTime(time);
                order.setEmployeId("");
                order.setEmployeName("");
                order.setEmployeMobile("");
                order.setSiteId("");
                order.setSiteName("");
                orderDao.save(order);

                CrmOrderDispatch ordis = disDao.getByOrderId(id);
                if (ordis != null) {
                    ordis.setStatus(CrmOrder.ORDERTYPETWO);
                    ordis.setPromiseTime(time);
                    disDao.save(ordis);
                }

                CrmOrderOperationInfo info = infoDao.getOperaByOrderId(id);
                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(name);
                ta.setC(currentName+" 已拒接");
                ta.setT(Target.CANCEL_WAIT_NOT_DISPATCH);
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
                infoDao.save(info);
                //增加服务上拒单次数
                site.setRefusalCount(site.getRefusalCount()+1);
                siteInformationDao.save(site);

            }
            result.setCode("200");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("204");
            throw e;
        }

        return result;
    }

    /**
     * 服务工程师拒接工单
     */
    @Transactional(rollbackFor=Exception.class)
    public Result employeRefuseOrder(String orderId,String siteId,String userId){
        Result result = new Result();
        if(StringUtil.isBlank(orderId) || StringUtil.isBlank(siteId)){
            result.setCode("505");
            return result;
        }
        Date time = new Date();
        try {
                CrmOrder order = orderDao.get(orderId);
                if(!order.getSiteId().equals(siteId)){
                    result.setCode("505");//该工单已经不属于该服务商
                    return result;
                }
                if(!ApplyOrderConstants.SITE_STATUS_RECEIVE.equals(order.getSiteStatus())){
                    result.setCode("506");//该工单已不在待接单状态，无法拒接工单
                    return result;
                }
            Record employe=CrmUtils.getEmployeId(userId);
                String name = employe.getStr("name");
                order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_DIS);
                order.setStatus(ApplyOrderConstants.ORDER_STATUS_SERVICE);
                order.setLatestProcess("工程师"+name+"  已拒接");
                order.setLatestProcessTime(time);
                order.setProcessTime(time);
                order.setEmployeId("");
                order.setEmployeName("");
                order.setEmployeMobile("");
                orderDao.save(order);

                SiteOrderDispatch ordis = siteOrderDao.getByOrderId(orderId);
                if (ordis != null) {
                    ordis.setStatus(CrmOrder.ORDERTYPETWO);
                    ordis.setPromiseTime(time);
                    siteOrderDao.save(ordis);
                }

                CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(name);
                ta.setC("工程师"+name+" 已拒接");
                ta.setT(Target.CANCEL_WAIT_NOT_DISPATCH);
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
                infoDao.save(info);

            result.setCode("200");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("204");
            throw e;
        }

        return result;
    }

    /**
     * 服务商预约
    */
    @Transactional(rollbackFor=Exception.class)
    public void sitePromiseTimeOrder(String orderId ,String promise_time,String promise_limit){
        CrmOrder order = orderDao.get(orderId);
        Date time = new Date();
        String name = order.getSiteName();
        order.setPromiseTime(DateUtils.parseDate(promise_time));
        order.setPromiseLimit(promise_limit);
        order.setPromiseFlag(ApplyOrderConstants.FLAG_ONE);
        orderDao.save(order);

        CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
        if(ordis != null){
           ordis.setPromiseFlag(ApplyOrderConstants.FLAG_ONE);
           ordis.setPromiseTime(time);
            disDao.save(ordis);
        }

        CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(name);
        ta.setT(11);
        ta.setC(name+"确认预约时间为"+promise_time +" "+promise_limit);
        String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
        info.setProcessDetail(str);
        infoDao.save(info);

    }

    /**
     * 服务商派工
     * 可多条同时操作
    */
    @Transactional(rollbackFor=Exception.class)
    public Result siteDispatchOrder(Map<String ,String> map){
        Result result= new Result();
        String orderIds = map.get("orderId");
        String disStatus = map.get("disStatus");
        String empIds = map.get("empId");
        String empName =map.get("empName");
        String siteId= map.get("siteId");
        String empMobile = map.get("employeMobile");
        if(StringUtil.isBlank(orderIds)){
            result.setCode("505");
            return result;
        }
        String[] ids = orderIds.split(",");
        Date time = new Date();
        String code = "200";
        try {
            for(String id :ids ){
                CrmOrder order = orderDao.get(id);
                if(!siteId.equals(order.getSiteId())){
                    //可能被转派
                    code = "203";
                    break;
                }
                if(!ApplyOrderConstants.SITE_STATUS_DIS.equals(order.getSiteStatus()) ){
                    code = "506";
                    break;
                }
                SiteOrderDispatch siteDis = siteOrderDispatchDao.getByOrderId(id);
                if(siteDis== null){

                   siteDis =  new SiteOrderDispatch();
                }
                if(ApplyOrderConstants.DISPATCH_STATUS_CHANGE.equals(disStatus)){//派工到维修中
                    order.setSiteStatus(CrmOrder.SIX);
                    order.setSiteProcessTime(time);
                    siteDis.setProcessTime(time);
                    siteDis.setDropInTime(time);
                }else{
                    order.setSiteStatus(CrmOrder.FOUR);
                }
                order.setStatus(CrmOrder.ORDERTYPETWO);
                order.setSiteDispatchTime(time);
                order.setLatestProcess(order.getSiteName()+"派工给"+empName);
                order.setLatestProcessTime(time);
                order.setEmployeId(empIds);
                order.setEmployeName(empName);
                order.setEmployeMobile(empMobile);
                orderDao.save(order);

                siteDis.setOrderId(id);
                siteDis.setSiteId(order.getSiteId());
                siteDis.setSiteName(order.getSiteName());
                siteDis.setEmployeId(empIds);
                siteDis.setEmployeName(empName);
                siteDis.setMessengerId(map.get("messId"));
                siteDis.setMessengerName(map.get("messName"));

                siteDis.setDispatchTime(time);
                siteDis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_DJD);
                siteOrderDispatchDao.save(siteDis);
                //派工与服务工程师关系表
                List<OrderDispatchEmployeRel> list = Lists.newArrayList();
                if(StringUtil.isNotBlank(empIds)){
                    String[] emps = empIds.split(",");
                    String[] empN = empName.split(",");
                    for(int i= 0;i<emps.length;i++){
                        OrderDispatchEmployeRel emprel = new OrderDispatchEmployeRel();
                        emprel.setDispatchId(siteDis.getId());
                        emprel.setEmpId(emps[i]);
                        emprel.setEmpName(empN[i]);
                        emprel.setOrderId(order.getId());
                        emprel.setSiteId(order.getSiteId());
                        list.add(emprel);
                    }
                }

                employeRelDao.save(list);

                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(order.getSiteName());
                ta.setT(6);
                ta.setC(order.getSiteName() + "服务商派工给"+empName+"。联系电话："+empMobile);
                CrmOrderOperationInfo info = infoDao.getOperaByOrderId(id);
                if(StringUtil.isBlank(info.getId())){
                    info.setOrder(order);
                }
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
                infoDao.save(info);
            }
            if(!"200".equals(code)){
                result.setCode(code);
                return result;
            }
            result.setCode("200");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
            throw  e;
        }
        return result;
    }

    /**
     * 转派
     * 可多条
     * 修改派工表状态 status = 4
     * 修改order表工程师信息
     * 新增派工休息
     *
    */
    @Transactional(rollbackFor=Exception.class)
    public Result siteTransferOrder(Map<String,String> map){
        Result result= new Result();
        String orderIds = map.get("orderIds");
        String empName = map.get("empName");
        String empIds = map.get("empIds");
        if(StringUtil.isBlank(orderIds)){
            result.setCode("500");
            return result;
        }
        String[] ids = orderIds.split(",");
        String empMobile = map.get("employeMobile");
        String siteId = map.get("siteId");
        String transferReasons = map.get("transferReasons");
        Date time = new Date();
        try {
        for(String id : ids){
            CrmOrder order = orderDao.get(id);
            if(!siteId.equals(order.getSiteId())){
                result.setCode("500");//已经不属于该服务商
                return result;
            }
            String siteStatus = order.getSiteStatus();
            if(CrmOrder.FOUR.equals(siteStatus) || CrmOrder.FIVE.equals(siteStatus) || CrmOrder.SIX.equals(siteStatus)){

            }else{
                result.setCode("405");//不可操作转派
                return result;
            }
            if(!ApplyOrderConstants.FITTING_FLAG_NO.equals(order.getFittingFlag())){
                return Result.fail("402","该工单有申请备件，不能转派！");
            }
            //判断是否有收款记录
            List<Record> list1=Db.find("SELECT id FROM `crm_order_collections` WHERE order_id=? AND STATUS='0' " ,id);
            if(list1.size()>0){
                return Result.fail("403","该工单有收款记录，不能转派！");
            }
            SiteOrderDispatch siteOrderDispatch = siteOrderDispatchDao.getByOrderId(id);
            if(siteOrderDispatch != null){
                siteOrderDispatch.setStatus("4");
                siteOrderDispatch.setUpdateTime(time);
                siteOrderDispatch.setUpdateBy(map.get("userId"));
                siteOrderDispatch.setRemarks("服务商已转派,转派原因："+transferReasons);
                siteOrderDispatchDao.save(siteOrderDispatch);
            }
            order.setSiteStatus(CrmOrder.FOUR);
            order.setSiteDispatchTime(time);
            order.setLatestProcess(order.getSiteName()+"转派给"+empName);
            order.setLatestProcessTime(time);
            order.setEmployeId(empIds);
            order.setEmployeName(empName);
            order.setEmployeMobile(empMobile);
            orderDao.save(order);

            SiteOrderDispatch siteDis = new SiteOrderDispatch();
            siteDis.setOrderId(id);
            siteDis.setSiteId(order.getSiteId());
            siteDis.setSiteName(order.getSiteName());
            siteDis.setEmployeId(empIds);
            siteDis.setEmployeName(empName);
            siteDis.setMessengerId(map.get("messId"));
            siteDis.setMessengerName(map.get("messName"));
            siteDis.setDispatchTime(time);
            siteDis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_DJD);
            siteOrderDispatchDao.save(siteDis);

            //派工与服务工程师关系表
            List<OrderDispatchEmployeRel> list = Lists.newArrayList();
            if(StringUtil.isNotBlank(empIds)){
                String[] emps = empIds.split(",");
                String[] empN = empName.split(",");

                for(int i= 0;i<emps.length;i++){
                    OrderDispatchEmployeRel emprel = new OrderDispatchEmployeRel();
                    emprel.setDispatchId(siteDis.getId());
                    emprel.setEmpName(empN[i]);
                    emprel.setEmpId(emps[i]);
                    emprel.setOrderId(order.getId());
                    emprel.setSiteId(order.getSiteId());
                    list.add(emprel);
                }
            }

            employeRelDao.save(list);

            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(order.getSiteName());
            ta.setT(8);
            ta.setC(order.getSiteName() + "服务商转派给"+empName+"。联系电话："+empMobile+";转派原因:"+transferReasons);
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(id);
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
            info.setProcessDetail(str);
            infoDao.save(info);
        }

            result.setCode("200");
    }catch (Exception e){
        result.setCode("505");
        throw  e;
    }
        return result;
    }


    //获取跟进记录
    public String getOrderTrackDetail(String orderId){
        String sql = " SELECT track_detail FROM crm_order_operation_info WHERE order_id=?  ";
        return Db.queryStr(sql,orderId);
    }

    /**
     * 服务工程师收款
    */
    @Transactional(rollbackFor=Exception.class)
    public Result employeReceivables(Map<String,String> map){
        String orderId = map.get("orderId");
        if(StringUtil.isEmpty(orderId)){
            return Result.fail("202","数据有误");
        }
        String accountsReceivable = map.get("accountsReceivable");// 收费总额
        BigDecimal Receivable = new BigDecimal(StringUtil.isNotBlank(accountsReceivable) ? accountsReceivable:"0.00");

        BigDecimal amount = Db.queryBigDecimal("SELECT SUM(a.payment_amount) AS payment_amount FROM crm_order_collections a WHERE a.status='0' AND a.order_id=? ",orderId);
         if(amount == null){
             amount = new BigDecimal("0.00");
         }
        BigDecimal paymentAmount = new BigDecimal(StringUtil.isNotBlank(map.get("paymentAmount")) ? map.get("paymentAmount"):"0.00");
        if(Receivable.compareTo(amount.add(paymentAmount))==-1){
            return Result.fail("501","收款总额大于应收金额");
        }
        CrmSiteEmploye emp = empDao.getByHql("from CrmSiteEmploye where userId = :p1",new Parameter(map.get("userId")));
        CrmOrder order = orderDao.get(orderId);
        order.setTotalCollections(order.getTotalCollections().add(paymentAmount));
        orderDao.save(order);

        OrderCollections coll = new OrderCollections();
        coll.setCreateBy(map.get("userId"));
        coll.setCustomerAddress(order.getProvince()+ order.getCity() + order.getArea() +order.getCustomerAddress());
        coll.setCustomerMobile(order.getCustomerMobile());
        coll.setCustomerName(order.getCustomerName());
        coll.setEmployeId(emp.getId());
        coll.setEmployeName(emp.getName());
        coll.setSiteId(order.getSiteId());
        coll.setPaymentAmount(paymentAmount);
        coll.setPaymentType(map.get("paymentType"));
        coll.setSource("0");
        coll.setImgs(map.get("imgs"));
        coll.setPowerStationName(order.getPowerStationName());
        coll.setOrderId(orderId);
        coll.setOrderNumber(order.getNumber());
        collectionsDao.save(coll);
        return Result.ok();
    }
    @Transactional(rollbackFor=Exception.class)
    public Result deleteOrderCollectionsById(String id,String orderId){
        OrderCollections coll = collectionsDao.get(id);
        CrmOrder order = orderDao.get(orderId);
 /*       if(!coll.getEmployeId().equals(order.getEmployeId())){
            return Result.fail("203","该条收款为别人收取不可删除");
        }
*/
        BigDecimal paymentAmount = coll.getPaymentAmount();
        coll.setStatus(SourceConstants.STATUS_ONE);
        collectionsDao.save(coll);
        order.setTotalCollections(order.getTotalCollections().subtract(paymentAmount));
        orderDao.save(order);
        return Result.ok();
    }



    public List<Record> getOrderCollectionList(String orderId){
        return collectionsDao.getOrderCollectionList(orderId);
    }



    /**
     * 服务商修改工单
    */
    @Transactional(rollbackFor=Exception.class)
    public Result siteUpdateOrder(Map<String,String> map){
        Result re = new Result();

        String orderId = map.get("orderId");
        logger.info("update_order CrmOrderId: "+map.get("orderId"));
        StringBuilder content = new StringBuilder("");
        CrmOrder or = orderDao.get(orderId);
        String UserName = map.get("feedback_name");
        try {

            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(UserName);
            ta.setT(Target.DISPATCH_ORDER);
            if(StringUtil.isNotBlank(or.getCustomerName()) && !or.getCustomerName().equals(map.get("customerName"))){
                content.append("，用户姓名："+or.getCustomerName()+"修改为："+map.get("customerName"));
            }
            if(StringUtil.isNotBlank(or.getCustomerMobile()) && !or.getCustomerMobile().equals(map.get("customerMobile"))){
                content.append("，联系方式一："+or.getCustomerMobile()+"修改为："+map.get("customerMobile"));
            }else if(StringUtil.isBlank(or.getCustomerMobile()) && StringUtil.isNotBlank(map.get("customerMobile"))){
                content.append("，联系方式一 修改为："+map.get("customerMobile"));
            }

            if(StringUtil.isNotBlank(or.getCustomerTelephone()) && !or.getCustomerTelephone().equals(map.get("customerTelephone"))){
                content.append("，联系方式二："+or.getCustomerTelephone()+"修改为："+map.get("customerTelephone"));
            }else if(StringUtil.isBlank(or.getCustomerTelephone()) && StringUtil.isNotBlank(map.get("customerTelephone"))){
                content.append("，联系方式二 修改为："+map.get("customerTelephone"));
            }

            String org_address= or.getProvince()+or.getCity()+or.getArea()+or.getCustomerAddress();
            String new_address=map.get("province")+map.get("city")+map.get("area")+map.get("customerAddress");
            if(!org_address.equals(new_address)){
                content.append("，详细地址："+org_address+"修改为："+new_address);
            }
            if(StringUtil.isNotBlank(or.getApplianceModel()) &&!or.getApplianceModel().equals(map.get("applianceModel"))){
                content.append("，产品型号："+or.getApplianceModel()+"修改为："+map.get("applianceModel"));
            }else if(StringUtil.isBlank(or.getApplianceModel()) && StringUtil.isNotBlank(map.get("applianceModel"))){
                content.append("，产品型号 修改为："+map.get("applianceModel"));
            }


       //产品数量
          /*  if((or.getApplianceNum())!=null && StringUtil.isNotBlank(map.get("applianceNum")) && or.getApplianceNum()!=Integer.parseInt(map.get("applianceNum"))){
                content.append("，产品数量："+or.getApplianceNum()+"修改为："+map.get("applianceNum"));
            }else if((or.getApplianceNum())==null && StringUtil.isNotBlank(map.get("applianceNum"))){
                content.append("，产品数量 修改为："+map.get("applianceNum"));
            }*/

            if(StringUtil.isNotBlank(or.getApplianceBarcode()) && !or.getApplianceBarcode().equals(map.get("applianceBarcode"))){
                content.append("，机身条码："+or.getApplianceBarcode()+"修改为："+map.get("applianceBarcode"));
            }else if(StringUtil.isBlank(or.getApplianceBarcode()) && StringUtil.isNotBlank(map.get("applianceBarcode"))){
                content.append("，机身条码 修改为："+map.get("applianceBarcode"));
            }

            if(or.getApplianceBuyTime()!=null && StringUtil.isNotBlank(map.get("applianceBuyTime")) &&!DateUtils.formatYMDDateTime(or.getApplianceBuyTime()).equals(DateUtils.formatYMDDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))))){
                content.append("，购买日期："+or.getApplianceBuyTime()+"修改为："+DateUtils.formatDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))));
            }else if(or.getApplianceBuyTime()==null && StringUtil.isNotBlank(map.get("applianceBuyTime"))){
                content.append("，购买日期 修改为："+DateUtils.formatDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))));
            }
            if(StringUtil.isNotBlank(or.getRemarks()) &&!or.getRemarks().equals(map.get("remarks"))){
                content.append("，备注："+or.getRemarks()+"修改为："+map.get("remarks"));
            }else if(StringUtil.isBlank(or.getRemarks()) && StringUtil.isNotBlank(map.get("remarks"))){
                content.append("，备注 修改为："+map.get("remarks"));
            }

            ta.setC("服务商 "+UserName + "修改工单:"+content.toString());
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
            if(info==null){
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
                info.setOrder(or);
                info.setProcessDetail(str);
            }else{
                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);
            }
            infoDao.save(info);


            or.setLatestProcessTime(new Date());
            or.setLatestProcess(UserName+ "修改工单");
            or.setUpdateName(UserName);
            or.setUpdateTime(new Date());

            or.setCustomerName(map.get("customerName"));
            or.setCustomerMobile(map.get("customerMobile"));
            or.setCustomerTelephone(map.get("customerTelephone"));
            or.setProvince(map.get("province"));
            or.setCity(map.get("city"));
            or.setArea(map.get("area"));
            or.setCustomerAddress(map.get("customerAddress"));

            or.setApplianceModel(map.get("applianceModel"));
            or.setApplianceBarcode(map.get("applianceBarcode"));
            or.setApplianceBuyTime(DateUtils.parseDate(map.get("applianceBuyTime")));
       /*     or.setApplianceNum(Integer.parseInt(map.get("applianceNum")));
*/
           // or.setWarrantyType(map.get("warrantyType"));

            or.setRemarks(map.get("remarks"));
            orderDao.save(or);

            re.setCode("200");

        }catch (Exception e){
            re.setCode("505");
            logger.error("OrderService updateOrder Exception %s UserName : "+UserName,e );
            throw e;
        }
        return re;
    }
    /**
     *服务商将已完成工单返回至服务中
     */
    @Transactional(rollbackFor=Exception.class)
    public Result updateOrderStatus(Map<String,String> map){
        Result re = new Result();
        String orderId = map.get("orderId");
        String UserName = map.get("feedback_name");
        CrmOrder or = orderDao.get(orderId);
        CrmOrderDispatch dis=disDao.getByOrderId(orderId);
        SiteOrderDispatch sitdis=siteOrderDispatchDao.getByOrderId(orderId);
        CrmOrderOperationInfo  info=infoDao.getOperaByOrderId(orderId);
            try {
                or.setLatestProcessTime(new Date());
                or.setLatestProcess(UserName+ "返回工单至服务状态");
                or.setUpdateName(UserName);
                or.setUpdateTime(new Date());

                or.setStatus(ApplyOrderConstants.ORDER_STATUS_SERVICE);
                or.setSiteStatus(ApplyOrderConstants.SITE_STATUS_SERVICE);
                or.setEndTime(null);

               dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_YJD);
               dis.setEndTime(null);

                sitdis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_YJD);
                sitdis.setEndTime(null);

                Target ta = new Target();
                ta.setD(DateUtils.getDateTime());
                ta.setP(UserName);
                ta.setT(Target.DISPATCH_ORDER);
                ta.setC(UserName + "返回工单至服务状态");

                String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
                info.setProcessDetail(str);

                infoDao.save(info);
               disDao.save(dis);
               orderDao.save(or);
                siteOrderDispatchDao.save(sitdis);
                re.setCode("200");
            } catch (Exception e) {
                re.setCode("505");
                throw e;
            }
        return  re;
    }
    /**
     * 获取服务商结算信息
     * @param orderId
    */
    public CrmOrderSiteSettlement getOrderSiteSettlementByOrderId(String orderId){

        CrmOrderSiteSettlement siteset = siteSettlementRecordDao.getByorderId(orderId);
        return siteset;
    }
    /**
     * 获取服务商调整结算信息
     * @param orderId
     */
    public  List<Record> getUpDateOrderSiteSettlementByOrderId(String orderId){

        List<Record> sitesets = siteSettlementRecordDao.getUpdateByorderId(orderId);
        return sitesets;
    }

    public Record getPageOrderCount(String factor,String siteId,String employeId){

        return orderDao.getPageOrderCount(factor,siteId,employeId);
    }
    /**
     * 获取工程师信息
     */
    public List<Record> getEngineerList(String site_id){
        String sql="SELECT NAME,id,mobile FROM `crm_site_employee` WHERE role='2' and STATUS='0' and site_id=?";
        List<Record> records=Db.query(sql,site_id);
        return  records;
    }




    @Transactional(rollbackFor = Exception.class)
    public void updateIsConvert(String id, String siteId) {
        logger.error("ERP服务商转自接 orderId ="+id+" , siteId ="+siteId);
        SQLQuery sql = orderDao.getSession()
                .createSQLQuery("update crm_order a set a.is_convert='1' where a.site_id=:siteId and a.id =:id");
        sql.setParameter("siteId", siteId);
        sql.setParameter("id", id);
        sql.executeUpdate();
    }

    public List<Record> getSiteOrderList(String ids,String siteId){
        return orderDao.getSiteOrderList(ids,siteId);
    }


   @SuppressWarnings("unchecked")
    public Map<String, Object> checkFactoryOrder(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        OrderExcelImportHandler handler = new OrderExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        handler.setParams(params);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String hanl = handler.getErrorDetail();
            if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
                return retMap;
            }
            String result = (String) map.get("TemplateError");
            if ("TemplateError".equalsIgnoreCase(result)) {
                retMap.put("templateError", "y");//模板不匹配
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");//导入数量过多
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            logger.error("checkHistoryCustomer params : "+params+"Exception : "+e);
            e.printStackTrace();
            retMap.put("templateError", "y");//模板不匹配
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    /**
     * 导入工单。
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importFactoryOrder(Map<String, String> params, InputStream in,HttpServletRequest request) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        OrderExcelImportHandler handler = new OrderExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(3);
        handler.setParams(params);

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);
            String sql = handler.getExecuteSql();
            List<Object[]> exeSqlParams = handler.getExecuteParams();
            if (exeSqlParams != null && exeSqlParams.size() > 0) {
                //新增导入数据
                //操作无效工单同事需要清除冻结金额记录、回复冻结金额
                importOrder(handler.getExecuteParams());
              //  DBUtils.batchSaveOrUpdateSQLCus(sql, handler.getExecuteParams());
            }
            if(handler.getErrorCount() >0 && StringUtil.isNotBlank(handler.getErrorDetail())){
                String excelName = "导入失败数据.xls";
                String mchId = params.get("mchId");
                String path = request.getSession().getServletContext().getRealPath("") + "/"+mchId+"/";
                File temDir = new File(path);
                if(!temDir.exists()){
                    if (!temDir.mkdirs()) {
                        logger.error("import history customer error, mkdir failed.");
                    }
                }
                String pathName = path + excelName;
                if(!ExcelWrite.fileExist(pathName)){
                  //  ExcelWrite.createExcel(pathName,"历史用户",title);
                }

                List<Map> liatmap = handler.getListMap();
                ExcelWrite.writeToExcel(pathName,"历史用户",liatmap);

            }
            retMap.put("pass", "y");
            retMap.put("successCount", handler.getSuccessCount());//成功条数
            retMap.put("errorCount", handler.getErrorCount());		//失败条数
            retMap.put("errorDetail", handler.getErrorDetail());	//失败详情
            retMap.put("importHints", "y");
        }catch (CustomException m) {
            m.printStackTrace();
            retMap.put("code",m.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("inportHistoryCustomer params : {"+params+"} "+e);
            retMap.put("code","505");
        }
        return retMap;
    }

    public Object importOrder(List<Object[]> paramList) throws CustomException{
        Date time = new Date();
        User user = UserUtils.getUser();
        String UserName = CrmUtils.getUserXM(user);
        List<CrmOrder> listorder = Lists.newArrayList();
        List<CrmOrderOperationInfo> infos = Lists.newArrayList();

        for(Object[] item : paramList){
            String number = "DJI"+ PlantformUtils.getOrderNumber();
            CrmOrder order = new CrmOrder();
            order.setServiceType(item[0].toString());
            order.setCustomerName(item[1].toString());
            order.setCustomerMobile(item[3].toString());
            order.setCustomerTelephone(item[4] != null ? String.valueOf(item[4]):"");
            order.setProvince(item[5].toString());
            order.setCity(item[6].toString());
            order.setArea(item[7].toString());
            order.setCustomerAddress(item[8].toString());
            order.setApplianceBrand(item[9].toString());
            order.setApplianceCategory(item[10].toString());
            order.setApplianceModel(item[11] != null?String.valueOf(item[11]):"");
       /*     order.setApplianceNum(Integer.valueOf(String.valueOf(item[12])).intValue());*/
            order.setApplianceBarcode(item[13] != null ? String.valueOf(item[13]):"");
            order.setApplianceBuyTime(item[14] != null ? DateUtils.parseDate(item[14]):null);
            order.setWarrantyType(String.valueOf(item[16]));
          /*  order.setCompleteLimitLength(item[17] != null ? Integer.valueOf(item[17].toString()):0);*/
            order.setRemarks(item[18].toString());

            order.setNumber(number);
            order.setRepairTime(time);
            order.setCreateBy(user.getId());
            order.setLatestProcess(UserName+"报修");
            order.setLatestProcessTime(time);
            double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
            if(dals != null){
                order.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
            }
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(UserName);
            ta.setC(UserName + "导入");
            ta.setT(Target.NEW_ORDER);
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
            listorder.add(order);


            /**向工单操作/跟踪明细记录表添加数据
             */
            CrmOrderOperationInfo info = new CrmOrderOperationInfo();
            info.setOrder(order);
            info.setProcessDetail(str);
            infos.add(info);
            infos.add(info);
        }
        infoDao.save(infos);

        return Result.ok();
    }


    public long getComplaintOrderCount(Map<String,String> map){
        return orderDao.getComplaintOrderCount(map);
    }


    public List<Record> getApply(String orderId) {
        //备件申请记录
        List<Record> list = crmSiteFittingApplyDao.getOrderApplyList(orderId);
        for (Record record : list) {
            if (record.getStr("status").equals("0")) {
                record.set("status", "待审核");
            } else if (record.getStr("status").equals("1")){
                record.set("status", "已完成");
            }

            if (StringUtil.isNotBlank(record.getStr("refundStatus"))) {
                if (record.getStr("refundStatus").equals("1")) {
                    record.set("return_fitting", "未到厂");
                }else if (record.getStr("refundStatus").equals("2")){
                    record.set("return_fitting", "已到厂");
                }
            } else {
                if(record.getStr("return_fitting").equals("1")) {
                    record.set("return_fitting", "未登记");
                } else if(record.getStr("return_fitting").equals("2")) {
                    record.set("return_fitting", "已登记");
                }
            }

        }
        return list;
    }

    public long getTelephoneDeviceOrderCount(String tel){
        return Db.queryLong("SELECT count(id) FROM crm_order a WHERE a.customer_mobile=? OR a.customer_telephone=? ",tel,tel);
    }

    public Boolean checkPhoneBlack(Map<String,String> map){
        Boolean flag=false;
        if(StringUtil.isBlank(map.get("userId"))){
            return flag;
        } if(StringUtil.isBlank(map.get("customerMobile"))){
            return flag;
        }if(StringUtil.isBlank(map.get("remarks"))){
            return flag;
        }if(StringUtil.isBlank(map.get("psId"))){
            return flag;
        }
        if(StringUtil.isEmpty(map.get("type"))){
            if(StringUtil.isBlank(map.get("deviceName"))){
                return flag;
            }
        }
        return true;
    }

    public static Map<String,String>  addressResolution(String str){
        Map<String,String> map=Maps.newHashMap();
        try {

            Boolean flag=false;
            int index11 = 0;
            int index1 = str.indexOf("省");
            if (index1 == -1) {
                index11 = str.indexOf("自治区");
                if (index11 != -1) {
                    map.put("province",str.substring(0, index11 + 3));
                } else {
                    index11=str.indexOf("特别行政区");
                    if(index11 !=-1){
                        map.put("province",str.substring(0, index11 + 5));
                    }else{
                        flag=true;
                        map.put("province",str.substring(0, 0));
                    }
                }
            } else {
                map.put("province",str.substring(0, index1 + 1));
            }

            int index2 = str.indexOf("市");
            String areaAddre ="";
            if (index11 == -1) {
                map.put("city",str.substring(index11 + 1, index2 + 1));
                if(flag){
                    map.put("province",str.substring(index11 + 1, index2 + 1));
                }
                areaAddre = str.substring(index2 + 1);
            } else if(index2 != -1) {
                if (index11 == 0) {
                    map.put("city",str.substring(index1 + 1, index2 + 1));
                } else {
                    map.put("city",str.substring(index11 + 3, index2 + 1));
                }
                areaAddre = str.substring(index2 + 1);
            }

            int index3 = str.indexOf("县");
            if (index3 == -1) {
                index3 = areaAddre.lastIndexOf("市");
                if (index3 != -1) {
                    //  index3 = areaAddre.lastIndexOf("市");
                    map.put("area",areaAddre.substring(0, index3 + 1));
                    map.put("address",areaAddre.substring(index3 +1));
                }else if(areaAddre.lastIndexOf("区")!=-1){
                    map.put("area",areaAddre.substring(0, index3 + 1));
                    map.put("address",areaAddre.substring(index3 +1));
                }else{
                    map.put("area",str.substring(index2 + 1, index3 + 1));
                    map.put("address",str.substring(index3 +1));
                }
            } else {
                map.put("area",str.substring(index2 + 1, index3 + 1));
                map.put("address",str.substring(index3 +1));
            }
        }catch (Exception e){
            e.printStackTrace();
            return map;
        }

     //   map.put("address",areaAddre.substring(index3 +1));
            return map;
    }

   @Autowired
   private PowerStationDao powerStationDao;
    /**
     * 手机端一键报修
     */
    @Transactional(rollbackFor=Exception.class)
    public  Map<String,Object> savePhoneAddOrder(Map<String,String> map){
        logger.info("手机端一键报修 savePhoneAddOrder  :");
        Map<String,Object> resultmap=Maps.newHashMap();
        String user_id=map.get("userId");
        if(!checkPhoneBlack(map)){
            resultmap.put("code","205");
            resultmap.put("msg","必填项为空！");
            return  resultmap;
        }
        String psId=map.get("psId");
        PowerStation powerStation=powerStationDao.getPowerStationBypsId(psId);

        if(powerStation == null){
            resultmap.put("code","204");
            resultmap.put("msg","电站信息未找到！");
            return  resultmap;
        }

            Record record=Db.findFirst(" SELECT * FROM crm_power_station_device WHERE user_id=? AND device_name=? LIMIT 1" ,user_id,map.get("deviceName"));

        try{
            Date date=new Date();

            Customer customer=customerDao.getCustomerBuserId(user_id);
            String customerName=powerStation.getContactName();
            String address=powerStation.getLocation();
         //   Map<String,String>  mapAddr=addressResolution(address);
           /* String province=map.get("province");
            String city=map.get("city");
            String area=map.get("area");
            String customerAddress=map.get("customerAddress");*/
            String customerMobile=map.get("customerMobile");
            String promiseTime=map.get("promiseTime");
            String promiseLimit=map.get("promiseLimit");
            String remarks=map.get("remarks");
            String bdImgs=map.get("bdImgs"); //故障图片  最多4张  中间逗号，隔开
            String applianceCategory=map.get("applianceCategory");
            String applianceModel=map.get("applianceModel");
            String powerStationName=powerStation.getPsName();
            CrmOrder order=new CrmOrder();
            if(record!=null){
             order.setApplianceMachineCode(StringUtil.isNotBlank(record.getStr("device_code"))?record.getStr("device_code"):"");
             if(StringUtil.isNotBlank(record.getStr("factory_name"))){
               if(record.getStr("factory_name").startsWith("能辉")){
                   order.setApplianceBrand("能辉光伏");
               }else{
                   order.setApplianceBrand(record.getStr("factory_name"));
               }
             }
            }
            order.setApplianceBuyTime(DateUtils.parseDate(powerStation.getExpectInstallDate()) );
            order.setNumber("WX"+ PlantformUtils.getOrderNumber());
            order.setCustomerId(customer.getId());
            order.setCustomerName(customerName);
            order.setProvince(powerStation.getProvince());
            order.setCity(powerStation.getCity());
            order.setArea(powerStation.getArea());
            order.setCustomerAddress(address);
            order.setCustomerMobile(customerMobile);
            if(StringUtil.isNotBlank(promiseTime)){
                order.setPromiseTime(DateUtils.parseDate(promiseTime));
                order.setPromiseFlag(ApplyOrderConstants.FLAG_ONE);
            }
            if(StringUtil.isNotBlank(promiseLimit)){
                order.setPromiseLimit(promiseLimit);
            }
            order.setRemarks(remarks);
            order.setBdImgs(StringUtil.isNotBlank(bdImgs)?bdImgs:"");
            order.setApplianceCategory(StringUtil.isNotBlank(applianceCategory)?applianceCategory:"");
            order.setApplianceModel(StringUtil.isNotBlank(applianceModel)?applianceModel:"");
            order.setPowerStationName(StringUtil.isNotBlank(powerStationName)?powerStationName:"");
            order.setServiceType("维修");
            order.setRepairTime(date);
            order.setCreateTime(date);
            order.setCreateBy(customer.getUserId());
            order.setLatestProcess(customerName+"手机端一键报修");
            order.setLatestProcessTime(date);
            order.setOrderType("1");
            double[] dals = Apiutils.httpURLConectionGET(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
            if(dals != null){
                order.setCustomerLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
                double addre=  ordeCallbackDao.getCusaddress(order.getCustomerLnglat(),order.getSiteId());
                order.setMileage(new BigDecimal(addre));
            }
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(customerName);
            ta.setC(customerName + "手机端一键报修");
            ta.setT(Target.NEW_ORDER);
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
            CrmOrderOperationInfo info = new CrmOrderOperationInfo();
            info.setOrder(order);
            info.setProcessDetail(str);
            infoDao.save(info);
            orderDao.save(order);
            resultmap.put("code","200");
            resultmap.put("msg","保存成功！");
            resultmap.put("data","保存成功");
        }catch (Exception e){
            e.printStackTrace();
            resultmap.put("code","202");
            resultmap.put("msg","保存失败！");
            throw e;
        }
        return  resultmap;
    }
    /***
     * 手机端获取服务记录（已完成/未完成）
     */
    public List<Record> serviceList(LayuiPage page,Map<String,String> map){
        String user_id=map.get("userId");
        Customer customer=customerDao.getCustomerBuserId(user_id);
        String status="";
        if("1".equals(map.get("type"))){    //未完成工单
            status="1,2";
        }else if("2".equals(map.get("type"))){  //已完成
            status="3,4,5,6";
        }
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT o.id,o.number,o.repair_time,o.remarks,o.status,o.site_status, c.id AS commeId ,c.level,c.if_charge ");
        sb.append(" FROM `crm_order` o");
        sb.append(" LEFT JOIN `crm_customer_comment` c ON o.id=c.`order_id` ");
        sb.append(" WHERE o.customer_id=? ");
        sb.append(" AND o.status IN("+ StringUtil.joinInSql(status.split(","))+ ") ");
        sb.append(" ORDER BY o.create_time DESC  ");
        sb.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        return Db.find(sb.toString(),customer.getId());
    }

    /***
     * 手机端查询未完成工单数量
     */
    public long getWwcOrderNumber(Map<String,String> map){
        String user_id=map.get("userId");
        Customer customer=customerDao.getCustomerBuserId(user_id);
        String sql=" SELECT COUNT(id) FROM `crm_order` WHERE customer_id=? AND STATUS IN('1','2')";
       return  Db.queryLong(sql,customer.getId());
    }

  public Record getOrderByCustomerId(String name,String cusId){
        String sql = " select * from crm_order where (power_station_name =? or customer_id =?) and service_type='安装' LIMIT 1 ";

        return Db.findFirst(sql,name,cusId);
  }


  /**
   * 删除无效工单 -- 只有无效的才可以删除
  */
  @Transactional(rollbackFor=Exception.class)
  public Result deleteOrder(String orderId){
      CrmOrder order = orderDao.get(orderId);
      if(!ApplyOrderConstants.ORDER_STATUS_INVALID.equals(order.getStatus())){
          return Result.fail("202","该工单不是无效工单，不可删除！");
      }
      Db.update("INSERT INTO crm_order_delete SELECT *,NOW() FROM crm_order WHERE id=?" ,orderId);

      //删除原有order表数据
      SQLQuery sqlQuery = orderDao.getSession().createSQLQuery("DELETE FROM crm_order WHERE id= :orderId ");
      sqlQuery.setParameter("orderId", orderId);
      sqlQuery.executeUpdate();

      return Result.ok();
  }


}
