package com.sifang.modules.order.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import com.sifang.modules.order.dao.CrmOrderDispatchDao;
import com.sifang.modules.order.dao.CustomerTelephoneIncomeDao;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.utils.Tuple;
import com.sifang.modules.sunshine.financialManagement.service.CrmOrderSiteSettlementService;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.OrderDetailsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TelNotifyOrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrdeCallbackService callService;
    @Autowired
    CrmOrderDispatchDao orderDispatchDao;
    @Autowired
    CustomerTelephoneIncomeDao customerTelephoneIncomeDao;

    @Autowired
    CrmOrderSiteSettlementService siteSettlementService;
    
    /**
     * 获取来电号码对应的历史工单数据。
     *
     * @param telephone 用户来电手机号
     * @return
     */
    public OrderDetailsVo getTelephoneDeviceOrderList(String telephone, int pageNO) {

        StringBuilder sb = new StringBuilder()
        		.append("select * ")
                .append(" FROM crm_order AS a")
                .append(" WHERE ")
                .append(" (a.`customer_mobile` = ? OR a.`customer_telephone` = ?)")
                .append(" AND a.`status` IN ('1', '2', '3', '4', '5', '7')");
                 sb.append(" ORDER BY `create_time` DESC")
                .append(" LIMIT 1 OFFSET " + (pageNO - 1));


        Tuple<Long, Long> tuple = getTelephoneDeviceOrderCountTuple(telephone);

        List<Record> data = Db.find(sb.toString(), telephone, telephone);
        LayuiPage page = new LayuiPage(data,tuple.getVal1() + tuple.getVal2());
        page.setPage(pageNO);
        OrderDetailsVo vo = new OrderDetailsVo();
        vo.setUnfinishedOrderCount(tuple.getVal1());//未完成工单数量
        vo.setFinishedOrderCount(tuple.getVal2());//已完成工单数量
        vo.setPage(page);
        if (data.size() <= 0) {
            return vo;
        }
        Record order = data.get(0);
        String orderId = order.get("id");
        CrmOrder ord = orderDao.get(orderId);
        vo.setOrder(ord);
            // 回访信息
            vo.setCallback(callService.getCallbackOrder(orderId));

         /*   //信息员
            Page<Record> pages = new Page<Record>();
            pages.setPageNo(1);
            pages.setPageSize(100);
            List<Record> infomans = nonServicemanService.getAllServicemanInfo(pages, siteId, null).getList();
            vo.setInfoMans(infomans);*/
            
            // 结算信息
            vo.setSettlement(siteSettlementService.getOrderSettlement(orderId));
            // 来电次数
        vo.setCallTimes(customerTelephoneIncomeDao.getIncomingTimes(telephone));
        //  vo.setPushMessages(pushMessageService.getPushMessageByOrderId(orderId));
        // 用于展示App信息跟踪
        //    vo.setFeedbacks(orderDispatchDao.getAppFeedbacks(orderId));

        return vo;
    }

    /**
     * @param telephone 来电号码
     * @return 返回完成的和已经完成的工单数量。
     */
    private Tuple<Long, Long> getTelephoneDeviceOrderCountTuple( String telephone) {

        Tuple<Long, Long> ret1 = getTelephoneDeviceOrderCountTupleInner(telephone);
        Tuple<Long, Long> ret2 =  new Tuple<>(0L, 0L);
        return new Tuple<>(ret1.getVal1() + ret2.getVal1(), ret1.getVal2() + ret2.getVal2());
    }

    private Tuple<Long, Long> getTelephoneDeviceOrderCountTupleInner(String telephone ) {
        StringBuilder sb = new StringBuilder()
                .append("SELECT sum(case when a.status in ('0','1','2','3','4','7') then 1 else 0 end) as uCount, ")
                .append("sum(case when a.status in ('5') then 1 else 0 end) as fCount")
                .append(" FROM crm_order AS a ")
                .append("WHERE  (a.`customer_mobile` = ? OR a.`customer_telephone` = ?)");

        Record o = Db.findFirst(sb.toString(),  telephone, telephone);
        BigDecimal uCount = o.getBigDecimal("uCount");
        BigDecimal fCount = o.getBigDecimal("fCount");
        return new Tuple<>(uCount == null ? 0L : uCount.longValue(), fCount == null ? 0L : fCount.longValue());
    }

}
