package com.sifang.modules.smallprogram.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.site.fittingManager.service.SiteFittingApplyService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.order.dao.*;
import com.sifang.modules.order.entity.*;
import com.sifang.modules.order.utils.Target;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.supply.order.constant.ApplyOrderConstants;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.CrmAnnouncementReadInfoDao;
import com.sifang.modules.sys.entity.CrmAnnouncementReadinfo;
import com.sifang.modules.sys.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class SmallProgramOrderService extends BaseService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CrmOrderDispatchDao disDao;
    @Autowired
    private OrderOperationInfoDao infoDao;
    @Autowired
    private   CrmAnnouncementReadInfoDao crmAnnouncementReadInfoDao;
    @Autowired
    private SiteOrderDispatchDao siteOrderDispatchDao;
    @Autowired
    private OrderFeedbackDao feedDao;

    @Autowired
    private SiteFittingApplyService fittingApplyService;
   //获取工单结算信息
   public Record getSettleMessage(String orderId){
       String sql="SELECT * FROM `crm_order_site_settlement`  WHERE order_id=?  AND TYPE='0'";
       Record record=Db.findFirst(sql,orderId);
       return record;
   }
   //工程师上门
    public Result toVisit(String orderId,String userId){
        Result result = new Result();
        Date time = new Date();
     try{
         CrmOrder order = orderDao.get(orderId);

         if(!ApplyOrderConstants.SITE_STATUS_DOOR.equals(order.getSiteStatus()) && !ApplyOrderConstants.SITE_STATUS_RECEIVE.equals(order.getSiteStatus())){
             result.setCode("505");//该工单状态不可以操作上门
             return result;
         }
         Record emp = CrmUtils.getEmployeId(userId);
         order.setSiteStatus(ApplyOrderConstants.SITE_STATUS_SERVICE);
         order.setDropInTime(time);
         order.setLatestProcessTime(time);
         order.setLatestProcess("工程师"+emp.getStr("name")+" 已上门。");
         orderDao.save(order);
         CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
         if(ordis != null){
             ordis.setStatus(CrmOrder.ORDERTYPE_ONE);
             ordis.setPromiseTime(time);
             disDao.save(ordis);
         }
          SiteOrderDispatch ord=siteOrderDispatchDao.getByOrderId(orderId);
         if(ord !=null){
             ord.setDropInTime(time);
             ord.setUpdateTime(time);
             siteOrderDispatchDao.save(ord);
         }
         CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
         Target ta = new Target();
         ta.setD(DateUtils.getDateTime());
         ta.setP(emp.getStr("name"));
         ta.setC("工程师"+emp.getStr("name")+" 已上门。");
         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");
     }
        return result;
    }

/**
 * 获取服务商已请款(已到账) 和 待处理金额
 */
public Record getSiteAmount(String siteId){
    Record record=new Record();
    String sql="SELECT SUM(withdrawal_amount) AS amount FROM `crm_site_cash_out` WHERE site_id=? AND STATUS=?";
    Record record1=Db.findFirst(sql,siteId,"1");
    Record record2=Db.findFirst(sql,siteId,"2");
    record.set("dcl_amount",record1 != null?record1.getBigDecimal("amount"):new BigDecimal("0.00"));
    record.set("ytx_amount",record2 != null?record2.getBigDecimal("amount"):new BigDecimal("0.00"));
    return  record;
}

    /**
     *获取通知公告的内容
     */
    public List<Record> listMessageData(String userId,String objType,Map<String,String> map,LayuiPage<Record> page) {
        String s="";
        if(map.get("condition")!=null){
           s+="and title LIKE '%"+map.get("condition")+"%' ";
        }
        if(StringUtil.isNotBlank(map.get("province"))){
            s+="and  FIND_IN_SET('"+map.get("province")+"',c.province)  ";
        }
        SqlBuilder sb = new SqlBuilder()
                .line("select c.*,b.id as bid,DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i:%s') as createTime")
                .line("from crm_platform_announcement as c")
                .line("LEFT JOIN `crm_announcement_readinfo` AS b ")
                .line("ON c.`id`=b.platform_announcement_id AND b.read_id=? ")
                .line("where c.status='0'")
                .line(s)
                .line("and c.obj_type ='1' ")
                .line("order by c.create_time desc")
                .limit(page.getPage(), page.getLimit());
          List<Record> list=Db.find(sb.build(),userId);
         return list;
    }
    /**
     * 手机端获取当前用户的所有通知公告
    */
    public List<Record> listCustomerMessageList(String userId,Map<String,String> map,LayuiPage<Record> page) {
        String s="";
        if(map.get("condition")!=null){
            s+="and c.title LIKE '%"+map.get("condition")+"%' ";
        }
        SqlBuilder sb = new SqlBuilder()
                .line("select c.*,b.id as bid,DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i:%s') as createTime")
                .line("from crm_platform_announcement as c")
                .line("LEFT JOIN `crm_customer_notice` a on a.announcement_id = c.id ")
                .line("LEFT JOIN `crm_announcement_readinfo` AS b ")
                .line("ON c.`id`=b.platform_announcement_id AND b.read_id=? ")
                .line("where c.status='0' and a.customer_id=? ")
                .line(s)
                .line("and c.obj_type ='1' ")
                .line("order by c.create_time desc")
                .limit(page.getPage(), page.getLimit());
        List<Record> list=Db.find(sb.build(),userId,map.get("customerId"));
        return list;
    }


    /**
     * 将看过的通知公告标记为已读
     */
    public Result<Void> markAnnounce(String id,String userId,String userType,String siteId){
        Record site = null;
        if(User.USER_TYPE_FWS.equals(userType)){
           site = CrmSiteUtils.getSiteBySiteId(siteId);
        }else if(User.USER_TYPE_FWSRY.equals(userType)){
            site =CrmUtils.getEmployeId(userId);
        }

       try{
           if(site == null){
               return  Result.fail("");
           }
           SqlBuilder sb = new SqlBuilder()
                   .line("select platform_announcement_id from crm_announcement_readinfo")
                   .line("where read_id=? and platform_announcement_id=? and status='0'");
           Record record=Db.findFirst(sb.build(),userId,id);
           if(record==null){
               CrmAnnouncementReadinfo info = new CrmAnnouncementReadinfo();
               info.setReadId(site.getStr("user_id"));
               info.setReader(site.getStr("name"));
               info.setPlatformAnnouncementId(id);
               info.setStatus(SourceConstants.ONE);
               info.setCreateTime(new Date());
               info.setReaderType(SourceConstants.ONE);
               info.setParentId(siteId);
               crmAnnouncementReadInfoDao.save(info);
           }
       }catch (Exception e){
          e.printStackTrace();
          return  Result.fail("");
       }
      return  Result.ok();
    }

    /***
     * 统计不同状态下的工单数量
     */
    public Record getDifferentOrderCount(String siteId,String employeId){
        StringBuilder sf = new StringBuilder();
        sf.append("SELECT COUNT(a.id) AS qbCount, COUNT(CASE WHEN a.site_status='4' AND STATUS='2'THEN 1 END) AS djsCount,");
        sf.append("COUNT(CASE WHEN a.site_status ='3' AND STATUS='2'THEN 1 END) AS dpgCount,");
        sf.append("COUNT(CASE WHEN a.site_status IN('5','6') AND STATUS='2'THEN 1 END) AS fwzCount,");
        sf.append("COUNT(CASE WHEN a.site_status='7' AND STATUS IN('4','3','5') THEN 1 END) AS ywgCount,");
        sf.append("COUNT(CASE WHEN a.site_status='7' AND STATUS='5'THEN 1 END) AS yjsCount ");
        sf.append(" FROM `crm_order` a WHERE  STATUS !='7' AND a.site_id=? ");
        if(StringUtil.isNotBlank(employeId)){
            sf.append("and a.employe_id like '%"+employeId+"%' ");
        }
        sf.append(" ORDER BY a.create_time DESC");
        Record rd = Db.findFirst(sf.toString(),siteId);
        return  rd;
    }
    /**
     * 统计备件数量
     */
    public Record getSiteFittingApplyCount(String siteId,String employeId){
        StringBuilder sf = new StringBuilder();
        sf.append("SELECT ");
        sf.append("COUNT(CASE WHEN a.status = '0' THEN 1 END) AS dshCount, ");
        sf.append("COUNT(CASE WHEN a.status = '1' THEN 1 END) AS yshCount ");
        sf.append("FROM `crm_order` o LEFT JOIN crm_site_fitting_apply a ON o.id=a.order_id WHERE  a.site_id=?  AND a.site_id IS NOT NULL");
        if(StringUtil.isNotBlank(employeId)){
            sf.append(" AND a.employe_id like '%"+employeId+"%' ");
        }
        sf.append(" AND  DATE_FORMAT(a.create_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )");
        Record rd = Db.findFirst(sf.toString(),siteId);
        return rd;
    }

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

        CrmOrderDispatch ordis = disDao.getByOrderId(orderId);
        if(ordis != null){
            ordis.setPromiseFlag(ApplyOrderConstants.FLAG_ONE);
            ordis.setPromiseTime(time);
            disDao.save(ordis);
        }
        SiteOrderDispatch ord=siteOrderDispatchDao.getByOrderId(orderId);
        if(ord != null){
            ord.setUpdateTime(time);
            ord.setUpdateBy(user.getId());
            siteOrderDispatchDao.save(ord);
        }
        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);
    }

    //获得工单详情
public Record getOrderDetail(String orderId){
    StringBuilder sf = new StringBuilder();
    sf.append(" SELECT   ");
    sf.append("id, number, order_type, appliance_brand, appliance_category,service_cost, appliance_model, IFNULL(appliance_barcode,'') AS appliance_barcode, appliance_capacity, appliance_machine_code, customer_name, province, city, area, ");
    sf.append("customer_address, customer_mobile, customer_telephone, customer_lnglat, promise_time, promise_limit, warranty_type, service_type, service_measures, remarks, bd_imgs, site_id, site_name, ");
    sf.append(" employe_id, employe_name, employe_mobile, ");
    sf.append(" total_collections, site_status, status, disable_resource, callback_result, mileage, power_station_name, level, please_refer_mall, invoice, special_installation, warranty_flag ");
    sf.append("  ,DATE_FORMAT(a.drop_in_time,'%Y-%m-%d %H:%i:%s') drop_inTime ,DATE_FORMAT(a.dispatch_time,'%Y-%m-%d %H:%i:%s') dispatchTime ");
    sf.append("  ,DATE_FORMAT(a.repair_time,'%Y-%m-%d %H:%i:%s') createTime ,DATE_FORMAT(a.repair_time,'%Y-%m-%d %H:%i:%s') repairTime ");
    sf.append("  ,DATE_FORMAT(a.appliance_buy_time,'%Y-%m-%d') appliance_buyTime ,DATE_FORMAT(a.site_dispatch_time,'%Y-%m-%d %H:%i:%s') site_dispatchTime ");
    sf.append("  ,DATE_FORMAT(a.end_time,'%Y-%m-%d %H:%i:%s') endTime ,DATE_FORMAT(a.site_process_time,'%Y-%m-%d %H:%i:%s') site_processTime ");
    sf.append("  ,DATE_FORMAT(a.latest_process_time,'%Y-%m-%d %H:%i:%s') latest_processTime ,DATE_FORMAT(a.promise_time,'%Y-%m-%d') promiseTime ");
    sf.append("  FROM crm_order a  ");
    sf.append("  WHERE a.id=? ");
        return Db.findFirst(sf.toString(),orderId);
}

    /**
     * 服务工程师返回完工、过程反馈
     */
    @Transactional(rollbackFor=Exception.class)
    public Result SitefeedbackOrder(Map<String,String> map){
        Result result = new Result();
        try {
            String img = map.get("pickerImg");
            String type = map.get("feedbackType");
            String orderId = map.get("orderId");
            String name = map.get("feedback_name");
            String siteId = map.get("siteId");
            String serviceMeasures = map.get("serviceMeasures");
            String warrantyType = map.get("warrantyType");
            String mileageAmount = map.get("mileageAmount");//里程费
            String serviceCost = map.get("serviceCost");//服务费
            String feedback = map.get("feedback");
            String powerStationName = map.get("powerStationName");//电站
            String accountsReceivable = map.get("accountsReceivable");// 收费总额
            String pleaseReferMall  = map.get("pleaseReferMall");// 销售商
            String invoice = map.get("invoice");// 发票号码
            String deviceMachineCode = map.get("deviceMachineCode");//
            CrmOrder order = orderDao.get(orderId);

            BigDecimal Receivable = new BigDecimal(StringUtil.isNotBlank(accountsReceivable) ? accountsReceivable:"0.00");
            Date time = new Date();
            OrderFeedback feek = new OrderFeedback();
            if(!siteId.equals(order.getSiteId())){
                result.setCode("403");
                result.setMsg("工单已经被转派其他服务商");
                return result;
            }


            if("1".equals(type)){
               long count= fittingApplyService.getEmployeFittingByOrderId(orderId);
               if(count > 0){
                   result.setCode("405");
                   result.setMsg("该工单有待审核备件，不可操作完成。");
                   return result;
               }

                if(ApplyOrderConstants.SERVICE_TYPE_WX.equals(order.getServiceType())){
                    if(StringUtil.isBlank(accountsReceivable)){
                        result.setCode("406");
                        result.setMsg("收款总额为空");
                        return result;
                    }
                    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 && !accountsReceivable.equals("0")){
                        result.setCode("303");
                        result.setMsg("没有收款信息");
                        return result;
                    }
                    if(amount != null && Receivable.compareTo(amount)!=0){
                        result.setCode("501");
                        result.setMsg("收款总额不等于应收金额");
                        return result;
                    }

                    order.setServiceCost(new BigDecimal(StringUtil.isNotBlank(serviceCost)?serviceCost:"0.00"));

                    //获取备件费(保内才会收取备件费)
                    if(ApplyOrderConstants.WARRANTY_TYPE_TWO.equals(order.getWarrantyType())){
                        BigDecimal fittingPrice = fittingApplyService.getEmpFittingByOrderId(orderId);
                            order.setFittingCost(fittingPrice);

                    }

                }


            }

                StringBuilder content = new StringBuilder("");
            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP(name);
            order.setServiceMeasures(serviceMeasures);
            order.setPowerStationName(powerStationName);
            order.setPleaseReferMall(pleaseReferMall);
            order.setWarrantyType(warrantyType);
            order.setInvoice(invoice);
            if("1".equals(type)){ //  反馈状态  1:服务完成 /2过程反馈
                //首先需要判断备件状态是不是已完成状态
                feek.setFeedbackType(ApplyOrderConstants.FEEDBACK_FINISH);
                //修改order表
                order.setStatus(CrmOrder.ORDERTYPETHREE);
                order.setSiteStatus(CrmOrder.SEVEN);
                order.setSiteProcessTime(new Date());
                order.setEndTime(time);
                order.setAccountsReceivable(Receivable);
                order.setLatestProcessTime(time);
                order.setLatestProcess(name + "反馈封单完成");
                order.setCallbackResult(ApplyOrderConstants.RESULT_OK);
                //修改派工表
                SiteOrderDispatch siteDis = siteOrderDispatchDao.getByOrderId(orderId);
                siteDis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_FINISH);
                siteDis.setCompletionResult(ApplyOrderConstants.RESULT_ZERO);
                if(order.getSiteProcessTime() == null){
                    order.setSiteProcessTime(time);
                    siteDis.setProcessTime(time);
                }
                if(order.getDropInTime() == null){
                    order.setDropInTime(time);
                    siteDis.setDropInTime(time);
                }
                siteDis.setEndTime(time);
                siteOrderDispatchDao.save(siteDis);
                //修改平台派工表
                CrmOrderDispatch dis = disDao.getByOrderId(orderId);
                dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_FINISH);
                if(dis.getDropInTime() == null){
                    dis.setDropInTime(time);
                }
                dis.setEndTime(time);
                disDao.save(dis);
                ta.setT(14);

                content.append("反馈封单服务完成,反馈内容为:"+feedback)  ;
            }else{
                //过程反馈
                feek.setFeedbackType("0");
                order.setLatestProcessTime(time);
                order.setLatestProcess(name + "过程反馈");
                content.append("过程反馈,反馈内容为:"+feedback);
                ta.setT(12);
            }
            if(StringUtil.isNotBlank(order.getApplianceMachineCode()) && !order.getApplianceMachineCode().equals(map.get("applianceMachineCode"))){
                content.append("，设备序列号："+order.getApplianceMachineCode()+"修改为："+map.get("applianceMachineCode"));
            }else if(StringUtil.isBlank(order.getApplianceMachineCode()) && StringUtil.isNotBlank(map.get("applianceMachineCode"))){
                content.append("，设备序列号 修改为："+map.get("applianceMachineCode"));
            }
            if(StringUtil.isNotBlank(order.getApplianceModel()) &&!order.getApplianceModel().equals(map.get("applianceModel"))){
                content.append("，设备型号："+order.getApplianceModel()+"修改为："+map.get("applianceModel"));
            }else if(StringUtil.isBlank(order.getApplianceModel()) && StringUtil.isNotBlank(map.get("applianceModel"))){
                content.append("，设备型号 修改为："+map.get("applianceModel"));
            }
            if(order.getApplianceBuyTime()!=null && StringUtil.isNotBlank(map.get("applianceBuyTime")) &&!DateUtils.formatYMDDateTime(order.getApplianceBuyTime()).equals(DateUtils.formatYMDDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))))){
                content.append("，投运时间："+order.getApplianceBuyTime()+"修改为："+DateUtils.formatDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))));
            }else if(order.getApplianceBuyTime()==null && StringUtil.isNotBlank(map.get("applianceBuyTime"))){
                content.append("，投运时间 修改为："+DateUtils.formatDateTime(DateUtils.parseDate(map.get("applianceBuyTime"))));
            }
            if("安装".equals(order.getServiceType())){
                feek.setSteelStructureImg(map.get("steelStructureImg"));
                feek.setBracketImg(map.get("bracketImg"));
                feek.setAssemblyImg(map.get("assemblyImg"));
                feek.setDeviceImg(map.get("deviceImg"));
                feek.setShelterImg(map.get("shelterImg"));
                feek.setPanoramaImg(map.get("panoramaImg"));
            }

            order.setApplianceBuyTime(DateUtils.parseDate(map.get("applianceBuyTime")));
            order.setApplianceModel(map.get("applianceModel"));
            order.setApplianceCategory(map.get("applianceCategory"));
            order.setApplianceMachineCode(map.get("applianceMachineCode"));
            order.setAccountsReceivable(new BigDecimal(StringUtil.isNotBlank(map.get("accountsReceivable"))?map.get("accountsReceivable"):"0.00"));
            order.setMileCost(new BigDecimal(StringUtil.isNotBlank(mileageAmount)?mileageAmount:"0.00"));
            orderDao.save(order);

            feek.setOrderId(orderId);
            feek.setFeedbackTime(time);
            feek.setFeedbackId(map.get("feedback_id"));
            feek.setFeedbackName(name);
            feek.setFeedbackImg(img);
            feek.setFeedback(map.get("feedback"));
            feek.setSiteId(siteId);
            feek.setDeviceName(map.get("deviceName"));
            feek.setDeviceModel(map.get("deviceModel"));
            feek.setDeviceMachineCode(deviceMachineCode);
            feedDao.save(feek);

            //过程信息
            CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
            ta.setC(name+content);
            String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
            info.setProcessDetail(str);
            infoDao.save(info);
            result.setCode("200");
            result.setMsg("保存成功");
        }catch (Exception e){
            result.setCode("505");
            result.setMsg("保存失败");
            throw e;
        }
        return result;
    }

    public long getWeiDuCount(String userId,String customerId){
        String s="";

        SqlBuilder sb = new SqlBuilder()
                .line("select COUNT(*) from (")
                .line("select c.*,b.id as bid ")
                .line("from crm_platform_announcement as c")
                .line("LEFT JOIN `crm_customer_notice` a on a.announcement_id = c.id ")
                .line("LEFT JOIN `crm_announcement_readinfo` AS b ")
                .line("ON c.`id`=b.platform_announcement_id AND b.read_id=? ")
                .line(" WHERE c.status='0' AND c.obj_type='1' AND b.id IS NULL ")
                .line(" and a.customer_id=?  ) bids ");
        long count = Db.queryLong(sb.build(),userId,customerId);
        logger.info(sb.build() );
        logger.info("通知公告数量 count: {}",count);

        return count;
    }

    /**
     * 获取App更新版本
    */
    public Record getSysApk(String id ){
        return Db.findFirst("SELECT * FROM sys_apk WHERE id=? ",id);
    }

}

