package com.palmnest.service.repair.impl;

import cn.superdesk.libs.common.util.CollectionUtils;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.RepairTypeDetialDto;
import com.palmnest.application.dto.input.RepairTypeItemDto;
import com.palmnest.dao.ElementGroupDao;
import com.palmnest.dao.OrgElementDao;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.repair.RepairBillDao;
import com.palmnest.model.Element;
import com.palmnest.model.ElementGroup;
import com.palmnest.model.OrgElement;
import com.palmnest.model.User;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.repair.RepairBill;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.repair.RepairBillManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import scala.annotation.meta.param;

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

@Service("repairBillManager")
public class RepairBillManagerImpl extends GenericManagerImpl<RepairBill, Long> implements RepairBillManager {


    private RepairBillDao repairBillDao;

    @Autowired
    private ElementGroupDao elementGroupDao;
    @Autowired
    private OrgElementDao orgElementDao;
    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    public void setRepairBillDao(RepairBillDao repairBillDao) {
        this.repairBillDao = repairBillDao;
        this.dao = repairBillDao;
    }

    @Override
    public Page findPageByStatus(Integer status, String repairTypeIds, Long serviceUser, int pageSize,
                                 int pageNo, Integer orgId) {
        return repairBillDao.findPageByStatus(status, repairTypeIds, serviceUser, pageSize, pageNo, orgId);
    }

    @Override
    public List<RepairBill> findBy(Long userId, Long areaId) {
        return repairBillDao.findBy(userId, areaId);
    }

    @Override
    public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {
        return repairBillDao.findPageBy(params, pageSize, pageNo);
    }

    @Override
    public List<RepairBill> findSingleOvertime() {
        return repairBillDao.findSingleOvertime();
    }

    @Override
    public List<RepairBill> findPendOvertime() {
        return repairBillDao.findPendOvertime();
    }

    @Override
    public RepairBill findByCode(String code, BigDecimal repairCost) {
        return repairBillDao.findByCode(code, repairCost);
    }

    @Override
    public List<RepairBill> findManagePendOvertime() {
        return repairBillDao.findManagePendOvertime();
    }

    @Override
    public Integer findCountBy(Integer status, String repairTypeIds, Long serviceUser, Integer orgId) {
        return repairBillDao.findCountBy(status, repairTypeIds, serviceUser, orgId);
    }

    @Override
    public RepairBill findByCode(String code) {
        return repairBillDao.findByCode(code);
    }

    @Override
    public Integer updateGrabBill(RepairBill bill, Integer version) {
        return repairBillDao.updateGrabBill(bill, version);
    }

    @Override
    public WebPageResultDto findAllTree(int pageNo, int pageSize, Map<String, String> param, String code) {
        //查询大类以及下面的小类
        List<Map<String, Object>> resultList = new ArrayList<>();
        String itemCode = param.get("itemCode");
        String itemName = param.get("itemName");
        String orgId = param.get("orgId");

        List<Map<String, Object>> mapList = findChildItem(pageNo, 1000, param, code, orgId);

        Collections.sort(mapList,new Comparator<Map<String,Object>>() {
			public int compare(Map<String,Object> o1, Map<String,Object> o2) {  
				if(null==o1.get("orderno")){
					o1.put("orderno", 9999);
				}
				if(null==o2.get("orderno")){
					o2.put("orderno", 9999);
				}
				Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
				Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
                return name1.compareTo(name2);    
        }  
		});
        if (StringUtils.isNotEmpty(itemCode) || StringUtils.isNotEmpty(itemName)) {

            if (CollectionUtils.isNotEmpty(mapList)) {

                for (Map<String, Object> map :
                        mapList) {

                    List<Map<String, Object>> childList = (List<Map<String, Object>>) map.get("childList");
                    if (CollectionUtils.isNotEmpty(childList)) {
                        boolean flag = false;
                        for (Map<String, Object> childMap :
                                childList) {
                            String childItemCode = (String) childMap.get("itemCode");
                            String childItemName = (String) childMap.get("itemName");
                            if (itemCode.equals(childItemCode) || childItemName.contains(itemName)) {
                                flag = true;
                            }
                        }
                        if (flag) {
                            resultList.add(map);
                        }
                    }
                }
            }
        } else {
            resultList.addAll(mapList);
        }
        
        Collections.sort(resultList,new Comparator<Map<String,Object>>() {
			public int compare(Map<String,Object> o1, Map<String,Object> o2) { 
				if(null==o1.get("orderno")){
					o1.put("orderno", 9999);
				}
				if(null==o2.get("orderno")){
					o2.put("orderno", 9999);
				}
				Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
				Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
                return name1.compareTo(name2);    
        }  
		});


        // 分页
        int count = resultList.size();
        if (CollectionUtils.isNotEmpty(resultList) && resultList.size() > pageSize) {
            int fromIndex = (pageNo - 1) * pageSize;
            int toIndex = pageSize * pageNo;
            resultList = resultList.subList(fromIndex, resultList.size() > toIndex ? toIndex : resultList.size());
        }
        WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", resultList);
        dto.setCount(Long.parseLong(Integer.toString(count)));
        return dto;
    }

    @Override
    public RepairTypeDetialDto getDetail(String itemId, String orgId) {
        RepairTypeDetialDto repairTypeDetialDto = new RepairTypeDetialDto();
        //查询大类信息
        Element element = elementGroupDao.getElementId(Long.parseLong(itemId));

        if ("0".equals(element.getIsenabled())) {
            return repairTypeDetialDto;
        }

        TbOrganization org = organizationDao.getOrganizationById(Integer.parseInt(orgId));
        if (null != element) {
            repairTypeDetialDto.setItemCode(element.getItemcode());
            repairTypeDetialDto.setItemId(Long.parseLong(itemId));
            repairTypeDetialDto.setItemName(element.getItemname());
            repairTypeDetialDto.setOrgId(org.getId());
            repairTypeDetialDto.setOrgName(org.getName());
            repairTypeDetialDto.setDisplayOrder(element.getOrderno());
            //查询小类
            List<Element> elements = elementGroupDao.getElementsByGroupName(element.getItemcode());
            List<RepairTypeItemDto> repairTypeItemDtoList = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(elements)) {
                for (Element element1 :
                        elements) {

                    if ("0".equals(element1.getIsenabled())) {
                        continue;
                    }

                    RepairTypeItemDto repairTypeItemDto = new RepairTypeItemDto();
                    repairTypeItemDto.setItemCode(element1.getItemcode());
                    repairTypeItemDto.setItemId(element1.getId());
                    repairTypeItemDto.setItemName(element1.getItemname());
                    repairTypeItemDto.setDisplayOrder(element1.getOrderno());
                    repairTypeItemDtoList.add(repairTypeItemDto);
                }
                Collections.sort(repairTypeItemDtoList,new Comparator<RepairTypeItemDto>() {
        			public int compare(RepairTypeItemDto o1, RepairTypeItemDto o2) { 
        				if(null==o1.getDisplayOrder()){
        					o1.setDisplayOrder(9999L);;
        				}
        				if(null==o2.getDisplayOrder()){
        					o2.setDisplayOrder(9999L);;
        				}
        				Integer name1 =Integer.parseInt(o1.getDisplayOrder().toString());//name1是从你list里面拿出来的一个  
        				Integer name2= Integer.parseInt(o2.getDisplayOrder().toString());//name1是从你list里面拿出来的第二个name      
                        return name1.compareTo(name2);    
                }  
        		});
            }
            
            
            repairTypeDetialDto.setList(repairTypeItemDtoList);
        }

        return repairTypeDetialDto;
    }

    @Override
    public void saveRepair(RepairTypeDetialDto param, User user) {

        TbOrganization organization = organizationDao.getOrganizationById(param.getOrgId());

        if (null == organization) {
            return;
        }
        //更新大类
        if (null == param.getItemId()) {
            ElementGroup elementGroup = elementGroupDao.getElementGroupByCode(Constants.REPAIR_TYPE_CODE);

            if (null == elementGroup) {
                elementGroup = new ElementGroup();
                elementGroup.setId(103L);
            }
            //新增大类小类
            saveRepairTypeElement(param, user, elementGroup, organization);
        } else {
            //更新已有的大类小类
            updateRepairTypeElement(param, user);
        }
    }

    private void updateRepairTypeElement(RepairTypeDetialDto param, User user) {
        Element e = elementGroupDao.getElementId(param.getItemId());
        if (null == e) {
            return;
        }

        ElementGroup elementGroup = elementGroupDao.getElementGroupByCode(e.getItemcode());
        //先更新小类，再更新大类
        if (null == elementGroup) {
            return;
        }
        String oldItemCode = elementGroup.getGroupcode();
        elementGroup.setGroupcode(param.getItemCode());
        elementGroup.setGroupname(param.getItemName());

        List<Element> elements = elementGroupDao.getElementListByGroup(elementGroup.getId());

        if (CollectionUtils.isNotEmpty(elements)) {
            //修改小类
            List<RepairTypeItemDto> dtos = param.getList();

            if (CollectionUtils.isNotEmpty(dtos)) {
                List<Long> ids = new ArrayList<>();
                for (Element element :
                        elements) {
                    ids.add(element.getId());
                }
                //过滤获取已删除的数据id
                List<Long> deletIds = getDeletData(ids, dtos);

                for (RepairTypeItemDto repairTypeItemDto :
                        param.getList()) {
                    long optversion = this.elementGroupDao.getTabMaxOptVersion(Constants.TB_DICTIONARY_ITEM);
                    if (null == repairTypeItemDto.getItemId()) {
                        //新增
                        Element ele = new Element();
                        ele.setItemcode(StringUtils.isEmpty(repairTypeItemDto.getItemCode()) ?
                                UUID.randomUUID().toString() : repairTypeItemDto.getItemCode());
                        ele.setItemname(StringUtils.trim(repairTypeItemDto.getItemName()));
                        ele.setElementGroup(elementGroup);
                        ele.setCreateBy(user.getUsername() + "," + user.getFullName());// 添加人
                        ele.setCreatedTime(new Date());// 添加时间
                        ele.setOpratetype(ElementConstant.OPRATETYPE_ADD);
                        ele.setOprateversion(optversion + 1);
                        ele.setIsenabled(ElementConstant.YESORNO_1);
                        ele.setOrderno(repairTypeItemDto.getDisplayOrder());
                        elementGroupDao.saveElement(ele);

                    } else {
                        Element element = elementGroupDao.getElementId(repairTypeItemDto.getItemId());
                        //修改
                        element.setItemcode(repairTypeItemDto.getItemCode());
                        element.setItemname(StringUtils.trim(repairTypeItemDto.getItemName()));
                        element.setElementGroup(elementGroup);
                        element.setLastUpdatedBy(user.getUsername() + "," + user.getFullName());// 添加人
                        element.setLastUpdatedTime(new Date());// 添加时间
                        element.setOpratetype(ElementConstant.OPRATETYPE_UPD);
                        element.setOrderno(repairTypeItemDto.getDisplayOrder());
                        elementGroupDao.saveElement(element);
                    }
                }
                //删除
                if (CollectionUtils.isNotEmpty(deletIds)) {
                    Long[] idsArray = new Long[deletIds.size()];
                    deletIds.toArray(idsArray);
                    elementGroupDao.removeElement(idsArray);
                }
            } else {
                //删除小类
                List<Long> ids = new ArrayList<>();
                for (Element item :
                        elements) {
                    ids.add(item.getId());
                }
                Long[] idsArray = new Long[ids.size()];
                ids.toArray(idsArray);
                elementGroupDao.removeElement(idsArray);
            }
        } else {
            //新增小类
            for (RepairTypeItemDto repairTypeItemDto :
                    param.getList()) {
                long optversion = this.elementGroupDao.getTabMaxOptVersion(Constants.TB_DICTIONARY_ITEM);
                Element ele = new Element();
                ele.setItemcode(StringUtils.isEmpty(repairTypeItemDto.getItemCode()) ?
                        UUID.randomUUID().toString() : repairTypeItemDto.getItemCode());
                ele.setItemname(StringUtils.trim(repairTypeItemDto.getItemName()));
                ele.setElementGroup(elementGroup);
                ele.setCreateBy(user.getUsername() + "," + user.getFullName());// 添加人
                ele.setCreatedTime(new Date());// 添加时间
                ele.setOpratetype(ElementConstant.OPRATETYPE_ADD);
                ele.setOprateversion(optversion + 1);
                ele.setIsenabled(ElementConstant.YESORNO_1);
                ele.setOrderno(repairTypeItemDto.getDisplayOrder());
                elementGroupDao.saveElement(ele);
            }
        }
        //修改org绑定
        e.setItemname(param.getItemName());
        e.setItemcode(param.getItemCode());
        e.setOrderno(param.getDisplayOrder());
        elementGroupDao.saveElement(e);
        elementGroupDao.saveObj(elementGroup);

        OrgElement orgElement = elementGroupDao.getOrgElementByCode(oldItemCode, param.getOrgId());
        orgElement.setItemname(param.getItemName());
        orgElement.setCode(param.getItemCode());
        if(null!=param.getDisplayOrder()){
        	orgElement.setOrderno(Integer.parseInt(param.getDisplayOrder()+""));
        }
        orgElementDao.save(orgElement);
    }

    private void saveRepairTypeElement(RepairTypeDetialDto param, User user, ElementGroup elementGroup,
                                       TbOrganization organization) {
        String code = UUID.randomUUID().toString();

        long optversion = this.elementGroupDao.getTabMaxOptVersion(Constants.TB_DICTIONARY_ITEM);
        Element element = new Element();
        element.setItemcode(StringUtils.isEmpty(param.getItemCode()) ?
                code : param.getItemCode());
        element.setItemname(StringUtils.trim(param.getItemName()));
        element.setElementGroup(elementGroup);
        element.setCreateBy(user.getUsername() + "," + user.getFullName());// 添加人
        element.setCreatedTime(new Date());// 添加时间
        element.setOpratetype(ElementConstant.OPRATETYPE_ADD);
        element.setOprateversion(optversion + 1);
        element.setIsenabled(ElementConstant.YESORNO_1);
        element.setOrderno(param.getDisplayOrder());
        elementGroupDao.saveElement(element);

        ElementGroup group = new ElementGroup();
        group.setGroupcode(StringUtils.isEmpty(param.getItemCode()) ?
                code : param.getItemCode()); //生成唯一字符编号
        group.setGroupname(StringUtils.trim(param.getItemName()));
        group.setOpratetype("1");
        group.setOprateversion(elementGroup.getId());
        group.setCreateBy(user.getUsername() + "," + user.getFullName());
        group.setCreatedTime(new Date());
        group.setIsenabled(ElementConstant.YESORNO_1);
        group = elementGroupDao.save(group);

        if (group.getId() != null) {
            //绑定orgId
            OrgElement orgElement = new OrgElement();
            orgElement.setItemname(param.getItemName());
            orgElement.setElementGroup(elementGroup);
            orgElement.setIsenabled(1);
            orgElement.setCreator(user);
            orgElement.setCreatetime(new Date());
            orgElement.setOrganization(organization);
            orgElement.setCode(group.getGroupcode());
            if(null!=param.getDisplayOrder()){
            	orgElement.setOrderno(Integer.parseInt(param.getDisplayOrder()+""));
            }
            orgElementDao.save(orgElement);

            //新增小类
            for (RepairTypeItemDto repairTypeItemDto :
                    param.getList()) {
                long optversion2 = this.elementGroupDao.getTabMaxOptVersion(Constants.TB_DICTIONARY_ITEM);
                String uuid = UUID.randomUUID().toString();
                Element ele = new Element();
                ele.setItemcode(StringUtils.isEmpty(repairTypeItemDto.getItemCode()) ?
                        uuid : repairTypeItemDto.getItemCode());
                ele.setItemname(StringUtils.trim(repairTypeItemDto.getItemName()));
                ele.setElementGroup(group);
                ele.setCreateBy(user.getUsername() + "," + user.getFullName());// 添加人
                ele.setCreatedTime(new Date());// 添加时间
                ele.setOpratetype(ElementConstant.OPRATETYPE_ADD);
                ele.setOprateversion(optversion2 + 1);
                ele.setIsenabled(ElementConstant.YESORNO_1);
                ele.setOrderno(repairTypeItemDto.getDisplayOrder());
                elementGroupDao.saveElement(ele);
            }
        }
    }

    private List<Long> getDeletData(List<Long> ids, List<RepairTypeItemDto> dtos) {
        List<Long> pIds = new ArrayList<>();

        for (RepairTypeItemDto dto :
                dtos) {
            if (dto.getItemId() != null) {
                pIds.add(dto.getItemId());
            }
        }


        List<Long> resultIds = new ArrayList<>();
        for (Long id : ids) {
            if (!pIds.contains(id)) {
                resultIds.add(id);
            }
        }

        return resultIds;
    }


    public List<Map<String, Object>> findChildItem(int pageNo, int pageSize, Map<String, String> param, String code,
                                                   String orgId) {
        //查询分类
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<OrgElement> orgElementList = null;
        if (null != param) {
            param.put("groupCode", code);
            orgElementList = elementGroupDao.getElementListByAllOrgAndGroupAsPage(pageNo, pageSize, param);
            if (CollectionUtils.isEmpty(orgElementList)) {
                return new ArrayList<>();
            }
        }

        List<Element> elements = elementGroupDao.getElementsByGroupName(code);
        if (orgElementList != null && orgElementList.size() > 0) {

            for (int i = 0; i < orgElementList.size(); i++) {
                OrgElement orgEl = orgElementList.get(i);

                if (orgEl != null) {
                    Element el = elementGroupDao.getByItemCode(code, orgEl.getCode());
                    if (el != null) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("itemId", el.getId().toString());
                        map.put("itemCode", el.getItemcode());
                        map.put("itemName", el.getItemname());
                        map.put("groupId", el.getElementGroup().getId());
                        map.put("orgId", orgEl.getOrganization().getId());
                        map.put("orgName", orgEl.getOrganization() == null ? "" : orgEl.getOrganization().getName());
                        map.put("orderno", orgEl.getOrderno());
                        if (StringUtil.isNotEmpty(el.getItemcode())) {

                            List<Map<String, Object>> childList = findChildItem(pageNo, pageSize,
                                    null, el.getItemcode(), orgId);
                            
                            Collections.sort(mapList,new Comparator<Map<String,Object>>() {
                    			public int compare(Map<String,Object> o1, Map<String,Object> o2) {
                    				if(null==o1.get("orderno")){
                    					o1.put("orderno", 9999);
                    				}
                    				if(null==o2.get("orderno")){
                    					o2.put("orderno", 9999);
                    				}
                    				Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
                    				Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
                                    return name1.compareTo(name2);    
                            }  
                    		});
                            map.put("childList", childList);
                        }
                        mapList.add(map);
                    }
                }
            }

        } else if (elements != null && elements.size() > 0) {

            for (int i = 0; i < elements.size(); i++) {
                Element el = elements.get(i);
                if (el != null) {

                    Map<String, Object> map = new HashMap<>();
                    map.put("itemId", el.getId().toString());
                    map.put("itemCode", el.getItemcode());
                    map.put("itemName", el.getItemname());
                    map.put("groupId", el.getElementGroup().getId());
                    map.put("orgId", orgId);
                    map.put("orgName", null);
                    map.put("orderno", el.getOrderno());
                    if (StringUtil.isNotEmpty(el.getItemcode())) {
                        List<Map<String, Object>> childList = findChildItem(pageNo, pageSize,
                                null, el.getItemcode(), orgId);
                        Collections.sort(mapList,new Comparator<Map<String,Object>>() {
                			public int compare(Map<String,Object> o1, Map<String,Object> o2) {  
                				Integer name1 =Integer.parseInt(o1.get("orderno").toString());//name1是从你list里面拿出来的一个  
                				Integer name2= Integer.parseInt(o2.get("orderno").toString());//name1是从你list里面拿出来的第二个name      
                                return name1.compareTo(name2);    
                        }  
                		});
                        
                        map.put("childList", childList);
                    }
                    mapList.add(map);
                }
            }
        }
        return mapList;
    }


    @Override
    public void delete(String itemId, User user) {
        if (StringUtils.isEmpty(itemId)) {
            return;
        }

        Element element = elementGroupDao.getElementId(Long.parseLong(itemId));
        if (null == element) {
            return;
        }
        element.setIsenabled("0");
        elementGroupDao.saveElement(element);

        ElementGroup elementGroup = elementGroupDao.getElementGroupByCode(element.getItemcode());
        if (null != elementGroup) {
            elementGroup.setIsenabled("0");
            elementGroupDao.saveObj(elementGroup);
        }
    }

    @Override
    public List<RepairBill> getTotalByDateAndRepairType(Long repairTypeDetailId, Integer type, String date,
                                                        String endDate, String orgIds) {
        List<RepairBill> repairBillList;

        switch (type) {
            case 1: //年
                repairBillList = getBillTotalAsYear(repairTypeDetailId, date, orgIds);
                break;
            case 2://季度
                repairBillList = getBillTotalAsQuarter(repairTypeDetailId, date, orgIds);
                break;
            case 3://月
                repairBillList = getBillTotalAsMonth(repairTypeDetailId, date, orgIds);
                break;
            case 4://日
                repairBillList = getBillTotalAsDay(repairTypeDetailId, date, endDate, orgIds);
                break;
            default://默认为年
                repairBillList = getBillTotalAsYear(repairTypeDetailId, date, orgIds);
                break;
        }

        return repairBillList;
    }

    @Override
    public Page findPageByRepairUser(Map<String, Object> params, int pageSize, int pageNo) {
        return repairBillDao.findPageByRepairUser(params, pageSize, pageNo);
    }

    @Override
    public Page findBordPage(Map<String, Object> conditions, int pageSize, int pageNo) {
        return repairBillDao.findBordPage(conditions, pageSize, pageNo);
    }

    @Override
    public List<RepairBill> getByOrg(String orgIds) {
        return repairBillDao.findByOrg(orgIds);
    }

    /**
     * 查询指定天区间段的工单总数
     *
     * @param repairTypeDetailId
     * @param date
     * @param endDate
     * @return
     */
    private List<RepairBill> getBillTotalAsDay(Long repairTypeDetailId, String date, String endDate, String orgIds) {
        Date dateFrom = DateHelper.parseToDate(date  + " 00:00:00");
        Date dateTo = DateHelper.parseToDate(endDate + " 23:59:59");

        return repairBillDao.getTotalByRepairTypeId(repairTypeDetailId, dateFrom, dateTo, orgIds);
    }

    /**
     * 查询指定月份的工单总数
     *
     * @param repairTypeDetailId
     * @param date
     * @return
     */
    private List<RepairBill> getBillTotalAsMonth(Long repairTypeDetailId, String date, String orgIds) {
        String[] arrDate = StringUtils.split(date, "-");
        Calendar calDateTo = Calendar.getInstance();
        Calendar calDateFrom = Calendar.getInstance();
        calDateFrom.set(Integer.parseInt(arrDate[0]), Integer.parseInt(arrDate[1]) - 1, 1,
                0, 0, 0);

        calDateTo.setTime(calDateFrom.getTime());
        calDateTo.add(Calendar.MONTH, 1);
        Date dateFrom = calDateFrom.getTime();
        Date dateTo = calDateTo.getTime();

        return repairBillDao.getTotalByRepairTypeId(repairTypeDetailId, dateFrom, dateTo, orgIds);
    }

    /**
     * 查询指定季度的工单总数
     *
     * @param repairTypeDetailId
     * @param date
     * @return
     */
    private List<RepairBill> getBillTotalAsQuarter(Long repairTypeDetailId, String date, String orgIds) {
        String[] arrDate = StringUtils.split(date, "-");
        String dateStr;
        Calendar calDateTo = Calendar.getInstance();
        if ("1".equals(arrDate[1])) {
            //第一季度，一月~3月
            dateStr = String.format("%s-01-01", arrDate[0]);
        } else if ("2".equals(arrDate[1])) {
            //第二季度 4月~6月
            dateStr = String.format("%s-04-01", arrDate[0]);
        } else if ("3".equals(arrDate[1])) {
            //第三季度 7月~9月
            dateStr = String.format("%s-07-01", arrDate[0]);
        } else {
            //第四季度 10月~12月
            dateStr = String.format("%s-10-01", arrDate[0]);
        }

        Date dateFrom = DateHelper.parseToDate(dateStr);
        calDateTo.setTime(dateFrom);
        calDateTo.add(Calendar.MONTH, 3);
        Date dateTo = calDateTo.getTime();

        return repairBillDao.getTotalByRepairTypeId(repairTypeDetailId, dateFrom, dateTo, orgIds);
    }

    /**
     * 查询指定年的工单总数
     *
     * @param repairTypeDetailId
     * @param date
     * @return
     */
    private List<RepairBill> getBillTotalAsYear(Long repairTypeDetailId, String date, String orgIds) {

        Calendar calDateTo = Calendar.getInstance();

        Date dateFrom = DateHelper.parseToDate(String.format("%s-01-01", date));
        calDateTo.setTime(dateFrom);
        calDateTo.add(Calendar.YEAR, 1);
        Date dateTo = calDateTo.getTime();

        return repairBillDao.getTotalByRepairTypeId(repairTypeDetailId, dateFrom, dateTo, orgIds);
    }

	@Override
	public OrgElement findByCodeAndOrgId(String code, Integer orgId) {
		return orgElementDao.findByCodeAndOrgId(code, orgId);
	}
	
	@Override
	public OrgElement findByCodeAndOrgIdAndId(String code, Integer orgId,Long id) {
		return orgElementDao.findByCodeAndOrgIdAndId(code, orgId,id);
	}
	
	@Override
	public Element findByCodeAndId(String code, Integer orgId,Long id) {
		return orgElementDao.findByCodeAndId(code, orgId,id);
	}

	/**
	 * 获取微信端创建的所有工单数、收费数、费用
	 * @param orgId
	 * @param virtId
	 * @param type
	 * @param date
	 * @param endDate
	 * @return
	 */
	@Override
	public Page getAllWxOrder(Map<String, Object> conditions, int type,
			int pageNo, int pageSize) {
		return repairBillDao.getAllWxOrder(conditions, type, pageNo, pageSize);
	}

	/**
	 * 获取订单明细
	 * @param orgId
	 * @param virtId
	 * @param isFree  ==1获取所有工单数的明细 ==0获取收费工单数的明细
	 * @param type
	 * @param date
	 * @param endDate
	 * @return
	 */
	@Override
	public Page getWxAmountOrder(Map<String, Object> conditions, int isFree,
			int type, int pageNo, int pageSize) {
		return repairBillDao.getWxAmountOrder(conditions, isFree, type, pageNo, pageSize);
	}

	/**
	 * 获取微信端创建的所有工单数、收费数、费用
	 * @param orgId
	 * @param virtId
	 * @param type
	 * @param date
	 * @param endDate
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getExportAllWxOrder(Map<String, Object> conditions, int type) {
		return repairBillDao.getExportAllWxOrder(conditions, type);
	}

    @Override
    public List<Map<String, Object>> getSendUserData(Integer userId) {
        return repairBillDao.getSendUserData(userId);
    }

    @Override
    public Integer updateSendUserData(String sendBillIds) {
        return repairBillDao.updateSendUserData(sendBillIds);
    }

    /**
	 * 获取订单明细
	 * @param orgId
	 * @param virtId
	 * @param isFree  ==1获取所有工单数的明细 ==0获取收费工单数的明细
	 * @param type
	 * @param date
	 * @param endDate
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getExportWxAmountOrder(Map<String, Object> conditions, int isFree, int type) {
		return repairBillDao.getExportWxAmountOrder(conditions, isFree, type);
	}

    @Override
    public Page getPeoplecOrderList(Map<String, Object> conditions, int type,int pageNo, int pageSize) {
        return repairBillDao.getPeoplecOrderList(conditions, type,pageNo, pageSize);
    }

    @Override
    public List<Integer> getAutomaticHighPraiseRepairData() {
        return repairBillDao.getAutomaticHighPraiseRepairData();
    }

    @Override
    public Page getBillCommentList(Map<String, Object> conditions, int type,int pageNo, int pageSize) {

        return repairBillDao.getBillCommentList(conditions, type,pageNo, pageSize);
    }

}
