package io.hmit.modules.serviceOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.hmit.common.constant.Constant;
import io.hmit.common.page.PageData;
import io.hmit.common.service.impl.CrudServiceImpl;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.entity.UserEntity;
import io.hmit.modules.serviceOrder.dao.PensionOrderDao;
import io.hmit.modules.serviceOrder.dto.*;
import io.hmit.modules.serviceOrder.entity.PensionOrderDocumentEntity;
import io.hmit.modules.serviceOrder.entity.PensionOrderEntity;
import io.hmit.modules.serviceOrder.service.*;
import io.hmit.service.PushMessage;
import io.hmit.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-01-26
 */
@Service
public class PensionOrderServiceImpl extends CrudServiceImpl<PensionOrderDao, PensionOrderEntity, PensionOrderDTO> implements PensionOrderService {

    @Override
    public QueryWrapper<PensionOrderEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<PensionOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }
    @Autowired
    private RoleService roleService;

    @Autowired
    private PensionOrderDao pensionOrderDao;

    @Autowired
    private PensionOrderServiceService pensionOrderServiceService;

    @Autowired
    private PensionOrderDocumentService PensionOrderDocumentService;

    @Autowired
    private PensionOrganizationService pensionOrganizationService;

    @Autowired
    private UserService userService;

    @Autowired
    private PushMessage pushMessage;

    //查询全部订单
    @Override
    public PageData<PensionOrderDTO> getAllOrderPage(Map<String, Object> params, Long userId) {
        //分页
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<PensionOrderDTO> pensionOrderEntityIPage = pensionOrderDao.getOrderPageByStatusOrUserId(page, userId, null);
        return getPageData(pensionOrderEntityIPage, PensionOrderDTO.class);
    }

    //查询今日订单
    @Override
    public PageData<PensionOrderDTO> getTodayOrderPage(Map<String, Object> params) {
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
//        IPage<PensionOrderEntity> pensionOrderEntityIPage = pensionOrderDao.getTodayOrderPage(page, userId); //TODO 今日订单中展示未接单订单
        IPage<PensionOrderDTO> pensionOrderDTOIPage = pensionOrderDao.getTodayNoProceedOrderPage(page);
        return getPageData(pensionOrderDTOIPage, PensionOrderDTO.class);
    }

    //根据订单Id和订单状态查询 (接单时使用)
    @Override
    public PensionOrderDTO getOrderInfoByIdAndStatus(Long id, Integer status) {
        PensionOrderEntity orderEntity = pensionOrderDao.getOrderInfoByIdAndStatus(id, status);
        return ConvertUtils.sourceToTarget(orderEntity, PensionOrderDTO.class);
    }

    @Override
    public void reservation(PensionOrderDTO pensionOrderDTO) {
        save(pensionOrderDTO);
        PensionOrderServiceDTO orderServiceDTO = new PensionOrderServiceDTO().assemblePensionOrderService(pensionOrderDTO);
        pensionOrderServiceService.save(orderServiceDTO);
        pushMessage.sendWeChatMsg(pensionOrderDTO, userService.getUserByUserId(pensionOrderDTO.getCreator()).getOpenid(), "oldman");
//        pushMessage.sendSMSMsg(pensionOrderDTO, userService.getUserByUserId(pensionOrderDTO.getCreator()).getOpenid());
    }

    @Override
    public PageData<PensionOrderDTO> getOrderPageByStatus(Map<String, Object> params, Long userId, Integer status) {
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<PensionOrderDTO> pensionOrderDTOIPage = pensionOrderDao.getOrderPageByStatusOrUserId(page, userId, status);
        return getPageData(pensionOrderDTOIPage, PensionOrderDTO.class);
    }

    //根据用户ID或订单状态查询(带图)
    @Override
    public PensionOrderDTO getOrderInfoByIdAndUserIdOrStatus(Long orderId, Long userId, Integer status) {
        PensionOrderDTO pensionOrderDTO = pensionOrderDao.getOrderInfoByIdAndUserIdOrStatus(orderId, userId, status);
        return pensionOrderDTO;
    }

    @Override
    public PageData<PensionOrderDTO> getElderTodayOrderPage(Map<String, Object> params, Long creator) {
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<PensionOrderDTO> pensionOrderDTOIPage = pensionOrderDao.getElderTodayOrderPage(page, creator);
        return getPageData(pensionOrderDTOIPage, PensionOrderDTO.class);
    }

    @Override
    public PageData<PensionOrderDTO> getElderAllOrderOrByStatusPage(Map<String, Object> params, Long creator, Integer status) {
//        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        List<PensionOrderDTO> list = new ArrayList<>();
        if (null == status) {
            list = pensionOrderDao.getElderAllOrderOrByStatusList(params, creator, status);
        }else if (status != 6) {
            list = pensionOrderDao.getElderAllOrderOrByStatusList(params, creator, status);
        }else {
            List<PensionOrderDTO> list0 = pensionOrderDao.getElderAllOrderOrByStatusList(params, creator, 0);
            List<PensionOrderDTO> list1 = pensionOrderDao.getElderAllOrderOrByStatusList(params, creator, 1);
            List<PensionOrderDTO> list2 = pensionOrderDao.getElderAllOrderOrByStatusList(params, creator, 5);
            list.addAll(list0);
            list.addAll(list1);
            list.addAll(list2);
        }
//        page.setTotal(list.size());
        List<PensionOrderDTO> sortList = list.stream().sorted(Comparator.comparing(PensionOrderDTO::getAppointmentTime)).collect(Collectors.toList());
        Collections.reverse(sortList);
        return getPageData(getSubList(params, sortList), sortList.size(), PensionOrderDTO.class);
    }

    @Override
    public PageData<PensionOrderDTO> getAllOrderByCommunityUserIdPage(Map<String, Object> params, Long userId) {
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<PensionOrderDTO> pensionOrderDTOIPage = pensionOrderDao.getAllOrderByCommunityUserIdPage(page, userId);
        return getPageData(pensionOrderDTOIPage, PensionOrderDTO.class);
    }

    @Override
    public PageData<PensionOrderDTO> getElderAllOrderByCommunityUserIdPage(Map<String, Object> params, Long userId, String appointmentPerson) {
        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<PensionOrderDTO> pensionOrderDTOIPage = pensionOrderDao.getElderAllOrderByCommunityUserIdPage(page, userId, appointmentPerson);
        return getPageData(pensionOrderDTOIPage, PensionOrderDTO.class);
    }

    @Override
    public PageData<PensionOrderDTO> getOrganizationOrder(Map<String, Object> params, Long userId) {
        //登录->查询登录人员所属机构ID->机构ID查询服务ID（List）->服务ID + 状态查询订单（List）
//        IPage<PensionOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        List<Long> serviceIds = pensionOrganizationService.findServiceIdListByServiceUserId(userId);
        Integer status = null;
        if (null != params.get("status")) {
            status = Integer.parseInt(params.get("status").toString());
        }
        List<PensionOrderDTO> result = new ArrayList<>();
        for (Long id : serviceIds) {
            List<PensionOrderDTO> list = pensionOrderDao.getAllOrderByServiceId(id, status);
            result.addAll(list);
        }
//        page.setTotal(result.size());
        List<PensionOrderDTO> sortList = result.stream().sorted(Comparator.comparing(PensionOrderDTO::getAppointmentTime)).collect(Collectors.toList());
        Collections.reverse(sortList);
        return getPageData(getSubList(params, sortList), sortList.size(), PensionOrderDTO.class);
    }

    @Override
    public Boolean organizationHandle(Map<String, Object> params, Long userId) {
        //userId 可用于校验是否属于本机构的订单，暂未使用
        Long orderId = Long.parseLong(params.get("id").toString());
        PensionOrderEntity pensionOrderEntity = pensionOrderDao.selectById(orderId);
        pensionOrderEntity.setRemark(null != params.get("remark") ? params.get("remark").toString() : "");
        int status = Integer.parseInt(params.get("status").toString());
        if (status == 5) { //接单
            if (pensionOrderEntity.getStatus() == 0) {
                pensionOrderEntity.setStatus(5);
                pensionOrderEntity.setStatusName(Constant.OrderStatus.HAND_OUT.getMessage());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    pensionOrderEntity.setAppointmentTime(sdf.parse(params.get("appointmentTime").toString()));
                }catch (Exception ignored){}
                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
            }else {
                return false;
            }
        }else if (status == 1){ //派单
            Long recipient_id = Long.parseLong(params.get("recipientId").toString());
            if (pensionOrderEntity.getStatus() == 5 || pensionOrderEntity.getStatus() == 0) {
                pensionOrderEntity.setStatus(1);
                pensionOrderEntity.setStatusName(Constant.OrderStatus.ORDER.getMessage());
                UserEntity recipient = userService.getUserByUserId(recipient_id);
                pensionOrderEntity.setOrderRecipientId(recipient_id);
                pensionOrderEntity.setOrderRecipientName(recipient.getUsername());
                pensionOrderEntity.setOrderRecipientPhone(recipient.getMobile());
                pensionOrderEntity.setOrderRecipientTime(new Date());
                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
            }else {
                return false;
            }
        }else if (status == 3) {
            if (pensionOrderEntity.getStatus() != 2 && pensionOrderEntity.getStatus() != 4) {
                pensionOrderEntity.setStatus(3);
                pensionOrderEntity.setStatusName(Constant.OrderStatus.CANCEL.getMessage());
                pensionOrderEntity.setCancelReason(params.get("cancelReason").toString());
                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
            } else {
                return false;
            }
        }else if (status == 4) {
            if (pensionOrderEntity.getStatus() == Constant.OrderStatus.ORDER.geStatus()) {
                pensionOrderEntity.setStatus(Constant.OrderStatus.WAIT_EVALUATE.geStatus());
                pensionOrderEntity.setStatusName(Constant.OrderStatus.WAIT_EVALUATE.getMessage());
                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
            }
        }
        return true;
    }

    @Override
    public Boolean elderFamilyCancel(Long id, String reason) {
        PensionOrderEntity pensionOrderEntity = pensionOrderDao.selectById(id);
        if (null != pensionOrderEntity.getStatus() && pensionOrderEntity.getStatus() != 2 && pensionOrderEntity.getStatus() != 4) {
            pensionOrderEntity.setStatus(3);
            pensionOrderEntity.setStatusName(Constant.OrderStatus.CANCEL.getMessage());
            pensionOrderEntity.setCancelReason(reason);
            update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
            return true;
        }
        return false;
    }

    @Override
    public void staffFinishedOrder(StaffFinishDTO dto) {
        if (null != dto.getImages()) {
            saveFilesToDB(dto.getOrderId(), dto.getImages(), dto.getRoleId());
        }
        if (null != dto.getVoice()) {
            saveFilesToDB(dto.getOrderId(), dto.getVoice(), dto.getRoleId());
        }
        PensionOrderEntity pensionOrderEntity = pensionOrderDao.selectById(dto.getOrderId());
        pensionOrderEntity.setStatus(4);
        pensionOrderEntity.setStatusName(Constant.OrderStatus.WAIT_EVALUATE.getMessage());
        pensionOrderEntity.setContent(dto.getContent());
        pensionOrderEntity.setLocation(dto.getLocation());
        update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
        pushMessage.sendWeChatMsg(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class), userService.getUserByUserId(pensionOrderEntity.getCreator()).getOpenid(), "oldman");
    }

    //对List进行手动分页
    private List<PensionOrderDTO> getSubList(Map<String, Object> params, List<PensionOrderDTO> list){
        Integer pageNum = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        Integer count = list.size();
        Integer pageNo = (pageNum - 1) * pageSize;
        List<PensionOrderDTO> list2 ;
        if (pageNo+pageSize > count) {
            if (pageNo > count){
                list2 = new ArrayList<>();
            }else {
                list2 = list.subList(pageNo, count);
            }
        }else {
            list2 = list.subList(pageNo, pageNo+pageSize);
        }
        return list2;
    }

    //将文件保存到数据库
    @Override
    public void saveFilesToDB(Long orderId,String files[],Long roleId){

        Arrays.stream(files).forEach(item->{
            PensionOrderDocumentDTO orderDocumentDTO = new PensionOrderDocumentDTO();

            orderDocumentDTO.setFilePath(item);
            orderDocumentDTO.setOrderId(orderId);
            orderDocumentDTO.setCreateDate(new Date());

/*            RoleDTO roleDTO = roleService.get(roleId);
            if(roleDTO != null && roleDTO.getName().contains("老人")){
                orderDocumentDTO.setRemark("3");
            }

            if(roleDTO != null && roleDTO.getName().contains("服务")){
                String fileName = item.toLowerCase();
                orderDocumentDTO.setRemark("1");
                if (fileName.endsWith(".mp3")) {
                    orderDocumentDTO.setRemark("2");
                }

            }*/
            if (item.toLowerCase().endsWith(".mp3")) {
                orderDocumentDTO.setRemark("2");
            } else {
                orderDocumentDTO.setRemark("1");
            }
            PensionOrderDocumentService.save(orderDocumentDTO);

        });

    }

    @Override
    public void evaluationDone(PensionOrderEvaluationDTO dto) {
        PensionOrderDTO pensionOrderDTO = get(dto.getOrderId());
        if (pensionOrderDTO != null){
            pensionOrderDTO.setStatus(Constant.OrderStatus.DONE.geStatus());
            pensionOrderDTO.setStatusName(Constant.OrderStatus.DONE.getMessage());
        }
        update(pensionOrderDTO);
//        saveFilesToDB(dto.getOrderId(),dto.getFiles(),dto.getRoleId());
        pushMessage.sendWeChatMsg(pensionOrderDTO, userService.getUserByUserId(pensionOrderDTO.getCreator()).getOpenid(), "oldman");
    }

}
