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.modules.serviceOrder.dao.PensionOrderDao;
import io.hmit.modules.serviceOrder.dto.PensionOrderDTO;
import io.hmit.modules.serviceOrder.entity.PensionOrderEntity;
import io.hmit.modules.serviceOrder.entity.UserEntity;
import io.hmit.modules.serviceOrder.service.PensionOrderService;
import io.hmit.modules.serviceOrder.service.PensionOrderServiceService;
import io.hmit.modules.serviceOrder.service.PensionOrganizationService;
import io.hmit.modules.serviceOrder.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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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


    @Autowired
    private PensionOrderDao pensionOrderDao;

    @Autowired
    private PensionOrderServiceService pensionOrderServiceService;

    @Autowired
    private PensionOrganizationService pensionOrganizationService;

    @Autowired
    private UserService userService;

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

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

        return wrapper;
    }


    @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") && !"".equals(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());
        Integer pageNum = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        Integer count = result.size();
        Integer pageNo = (pageNum - 1) * pageSize;
        List<PensionOrderDTO> list2 ;
        if (pageNo+pageSize > count) {
            list2 = result.subList(pageNo,count );
        }else {
            list2 = result.subList(pageNo,pageNo+pageSize);
        }
        return getPageData(list2, result.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 organizationHandle(Map<String, Object> params, Long userId) {
//        //userId 可用于校验是否属于本机构的订单，暂未使用
//        Long orderId = Long.parseLong(params.get("id").toString());
//        PensionOrderEntity pensionOrderEntity = pensionOrderDao.selectById(orderId);
//        Integer status = Integer.parseInt(params.get("status").toString());
//        if (status == 5) {//接单
//            if (pensionOrderEntity.getStatus() == 0) {
//                pensionOrderEntity.setStatus(5);
//                pensionOrderEntity.setStatusName(Constant.OrderStatus.HAND_OUT.getMessage());
//                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
//            }else {
//                return false;
//            }
//        }else if (status == 1){ //派单
//            Long recipient_id = Long.parseLong(params.get("recipient_id").toString());
//            if (pensionOrderEntity.getStatus() == 5) {
//                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("cancel_reason").toString());
//                update(ConvertUtils.sourceToTarget(pensionOrderEntity, PensionOrderDTO.class));
//            } else {
//                return false;
//            }
//        }
//        return true;
//    }
}
