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

import com.alibaba.fastjson.JSONObject;
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.common.utils.DateUtils;
import io.hmit.common.utils.HttpRequestUtil;
import io.hmit.common.utils.MD5;
import io.hmit.common.utils.sm.SMUtil;
import io.hmit.entity.UserEntity;
import io.hmit.modules.appointment.dao.AppointmentOrderDao;
import io.hmit.modules.appointment.dto.AppointmentOrderDTO;
import io.hmit.modules.appointment.dto.ReservationOrderInfoDTO;
import io.hmit.modules.appointment.dto.YynumberDTO;
import io.hmit.modules.appointment.entity.AppointmentOrderEntity;
import io.hmit.modules.appointment.service.AppointmentOrderService;
import io.hmit.modules.appointment.service.AppointmentServiceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.*;

/**
 * 预约订单表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-02-13
 */
@Service
public class AppointmentOrderServiceImpl extends CrudServiceImpl<AppointmentOrderDao, AppointmentOrderEntity, AppointmentOrderDTO> implements AppointmentOrderService {

    @Resource
    private AppointmentOrderDao appointmentOrderDao;
    @Resource
    private AppointmentOrderService appointmentOrderService;

    @Resource
    private AppointmentServiceService appointmentServiceService;

    /**
     * 电话号码校验（不包含港澳台手机号）
     */
    final static String VALIDATE_PHONE = "^(13[0-9]|14[579]|15[0-3,5-9]|16[0-9]|17[0135678]|18[0-9]|19[89])\\d{8}$";

    /**
     * 身份证校验
     */
    final static String ID_NUMBER ="^[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";

    @Override
    public QueryWrapper<AppointmentOrderEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String userId = (String)params.get("userId");
        String flag = (String)params.get("flag");
        String status = (String)params.get("status");
        String phone = (String)params.get("appointmentPhone");
        String idCard = (String)params.get("appointmentIdCard");

        /*
         * 如果传进的 phone 和 idCard 值为为加密，则此处进行加密
         */
        if (!ObjectUtils.isEmpty(phone) && phone.matches(VALIDATE_PHONE)) {
            phone = SMUtil.SM4Encrypt(phone);
        }
        if (!ObjectUtils.isEmpty(idCard) && idCard.matches(ID_NUMBER)) {
            idCard = SMUtil.SM4Encrypt(idCard);
        }

        QueryWrapper<AppointmentOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.le(StringUtils.isNotBlank(flag) && "Y".equals(flag), "status", 2);
        wrapper.ge(StringUtils.isNotBlank(flag) && "Q".equals(flag), "status", 3);
        wrapper.eq(StringUtils.isNotBlank(status), "status", status)
                .eq(StringUtils.isNotBlank(phone), "appointment_phone", phone)
                .eq(StringUtils.isNotBlank(idCard), "appointment_id_card", idCard);



        return wrapper;
    }

    @Override
    public List<ReservationOrderInfoDTO> getAppointmentInfoPage(String identity) {
        String phone = null;
        String idCard = null;
        if (identity.matches(VALIDATE_PHONE)) {
            phone = identity;
        }
        if (identity.matches(ID_NUMBER)) {
            idCard = identity;
        }


        String now = DateUtils.format(new Date());
        String hour = DateUtils.format(new Date(),"HH:mm:ss");

        List<AppointmentOrderEntity> appointmentOrderEntities = new ArrayList<>();

        List<AppointmentOrderEntity> appointmentOrders = baseDao.selectList(new QueryWrapper<AppointmentOrderEntity>()
                .eq(StringUtils.isNotBlank(phone), "appointment_phone", SMUtil.SM4Encrypt(phone))
                .eq(StringUtils.isNotBlank(idCard), "appointment_id_card", SMUtil.SM4Encrypt(idCard))
                .eq("status",Constant.ReservationStatus.RESERVATION.getValue())
                .like("appointment_time",now));

        if(appointmentOrders.size()==0){
            return null;
        }
        appointmentOrders.stream().forEach(item->{
            List<String > hours = new ArrayList<>();
            Arrays.stream(item.getAppointmentTime().substring(11).split("-"))
                    .forEach(time->hours.add(time));
            if(hours.get(0).compareTo(hour)<0 && hours.get(1).compareTo(hour)>0){
                item.setSid(appointmentServiceService.selectById(item.getServiceId()).getSid());
                appointmentOrderEntities.add(item);
            }
        });
        return ConvertUtils.sourceToTarget(appointmentOrderEntities, ReservationOrderInfoDTO.class);
    }

/*
 //Page版本V1.0
    @Override
    public PageData<AppointmentOrderDTO> getAppointmentInfoPage(Map<String, Object> params, String identity) {
        String phone = null;
        String idCard = null;
        if (identity.matches(VALIDATE_PHONE)) {
            phone = identity;
        }
        if (identity.matches(ID_NUMBER)) {
            idCard = identity;
        }
        IPage<AppointmentOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
        IPage<AppointmentOrderDTO> appointmentOrderDTOIPage = appointmentOrderDao.getAppointmentInfo(page, phone, idCard);
        return getPageData(appointmentOrderDTOIPage, AppointmentOrderDTO.class);
    }

*/

//    public PageData<AppointmentOrderDTO> page( Map<String, Object> params){
//        //分页
//        IPage<AppointmentOrderEntity> page = getPage(params, Constant.CREATE_DATE, false);
//
//        //查询
////        List<AppointmentOrderEntity> list = appointmentOrderDao.;
//
////        for (AppointmentOrderEntity appointmentOrderEntity : list) {
////            YynumberDTO yynumberDTO = appointmentOrderService.findByYuNumber(appointmentOrderEntity.getAppointmentNum());
////            appointmentOrderEntity.setYynumberDTO(yynumberDTO);
////        }
//        return  getPageData(list, page.getTotal(), AppointmentOrderDTO.class);
//    }
    @Override
    public Integer waitingNum(String appointmentTime) {

        return appointmentOrderDao.waitingNum(appointmentTime);
    }

    @Override
    public Integer reservationAccount(Long serviceId, String appointmentTime) {
        Integer account = baseDao.selectCount(new QueryWrapper<AppointmentOrderEntity>()
                .eq("service_id",serviceId).eq("appointment_time",appointmentTime));

        return account;
    }

    @Override
    public Integer serviceWaitingNum(Long serviceId) {

        return appointmentOrderDao.serviceWaitingNum(serviceId) ;
    }

    @Override
    public YynumberDTO findByYuNumber(String sPaperNumber) {
        //调用取号机接口，。
//        String url = "http://IP:8223/smartqueue/getpaperwait?sPaperNumber=" +sPaperNumber;
//        String url = "http://192.168.1.97:8223/smartqueue/getpaperwait?sPaperNumber=" +sPaperNumber;
//        String s = HttpRequestUtil.sendGetAndRetrieveContent(url);
        String s = "{\"nStatus\":1,\"sMsg\":\"号码已被呼叫\",\"nWait\":0,\"sCallTime\":\"2021-03-08 16:27:09\",\"sRegTime\":\"2021-03-08 16:26:55\",\"sQueueName\":\"不动产档案查询\",\"listWin\":[\"38号窗口\",\"39号窗口\",\"40号窗口\",\"41号窗口\",\"42号窗口\",\"43号窗口\"]}";
        YynumberDTO yynumberDTO = JSONObject.parseObject(s,YynumberDTO.class);
        return  yynumberDTO;

    }


}
