package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.busiz.rsp.register.AppointmentDataInfo;
import com.mortals.xhx.busiz.rsp.register.AppointmentDataItem;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.appointment.model.AppointmentPersonEntity;
import com.mortals.xhx.module.appointment.model.AppointmentPersonQuery;
import com.mortals.xhx.module.appointment.service.AppointmentPersonService;
import com.mortals.xhx.module.hik.face.service.FacePlanService;
import com.mortals.xhx.module.person.model.PersonEntity;
import com.mortals.xhx.module.person.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 同步预约人数。
 * 定时每日执行，执行前删除当天已经同步的预约人
 */
@Slf4j
@Service("SyncAppointmentPersonTask")
public class SyncAppointmentPersonTaskImpl implements ITaskExcuteService {

    @Autowired
    private PersonService personService;
    @Autowired
    private AppointmentPersonService appointmentPersonService;
    @Autowired
    private FacePlanService facePlanService;

    @Value("${php.host:''}")
    private String host;


    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("同步今天预约用户任务");
        syncAppointmentPerson();
        log.info("同步今天预约用户任务完成");

        log.info("创建每日预约人群任务");
        facePlanService.createAppointmentPersonByDay();
        log.info("创建每日预约人群完成");

    }

    private void syncAppointmentPerson() {
        //根据数量查询
        String registerPath = "/inter/Actuary/orderPeople";
        String url = host + registerPath;

        Map<String, Object> params = new HashMap<>();
        params.put("page", 1);
        params.put("size", 1);
        String respJson = HttpUtil.get(url, params);
        Rest<AppointmentDataInfo> rest = JSON.parseObject(respJson, new TypeReference<Rest<AppointmentDataInfo>>() {
        });

        if (rest.getCode() == YesNoEnum.YES.getValue()) {
            Integer total = rest.getData().getTotal();
            if (total > 1) {
                params = new HashMap<>();
                params.put("page", 1);
                params.put("size", total);
                respJson = HttpUtil.get(url, params);
                Rest<AppointmentDataInfo> restTotal = JSON.parseObject(respJson, new TypeReference<Rest<AppointmentDataInfo>>() {
                });

                if (restTotal.getCode() == YesNoEnum.YES.getValue()) {
                    //同步今天预约用户
                    List<AppointmentDataItem> appointUserList = restTotal.getData().getData();
                    log.info("预约用户总数量：{},{}", appointUserList.size(), JSON.toJSONString(appointUserList));
                    if (!ObjectUtils.isEmpty(appointUserList)) {
                        //查询今天添加的预约 并删除
                        AppointmentPersonQuery appointmentPersonQuery = new AppointmentPersonQuery();
                        appointmentPersonQuery.setCreateTimeStart(DateUtil.format(new Date(), "yyyy-MM-dd"));
                        appointmentPersonQuery.setCreateTimeEnd(DateUtil.format(new Date(), "yyyy-MM-dd"));
                        Long[] ids = appointmentPersonService.find(appointmentPersonQuery).stream().map(i -> i.getId()).toArray(Long[]::new);
                        if (!ObjectUtils.isEmpty(ids)) {
                            appointmentPersonService.remove(ids, null);
                        }
                        List<AppointmentPersonEntity> newUserList = appointUserList.stream().map(user -> {
                            if (ObjectUtils.isEmpty(user.getIdcardIDCardNo())) {
                                log.info("idCard is null . entity:{}", JSON.toJSONString(user));
                                return null;
                            }
                            AppointmentPersonEntity appointmentPersonEntity = new AppointmentPersonEntity();
                            appointmentPersonEntity.initAttrValue();

                            PersonEntity personCache = personService.getExtCache(user.getIdcardIDCardNo());
                            appointmentPersonEntity.setPersonId(personCache == null ? -1 : personCache.getId());
                            appointmentPersonEntity.setName(personCache == null ? "" : personCache.getName());
                            appointmentPersonEntity.setSiteId(user.getSiteId());
                            appointmentPersonEntity.setIdCard(user.getIdcardIDCardNo());
                            appointmentPersonEntity.setAppointmentStartTime(user.getStartTime());
                            appointmentPersonEntity.setAppointmentEndTime(user.getEndTime());
                            appointmentPersonEntity.setBussinessId(user.getBusinessId());
                            appointmentPersonEntity.setBussinessName(user.getBusinessName());
                            appointmentPersonEntity.setContactInfo(user.getPhone());
                            appointmentPersonEntity.setAppontmentNumber(user.getNumber());
                            appointmentPersonEntity.setCreateUserId(1L);
                            appointmentPersonEntity.setCreateUserName("系统管理员");
                            appointmentPersonEntity.setCreateTime(new Date());
                            return appointmentPersonEntity;
                        }).filter(f -> f != null).collect(Collectors.toList());

                        if (!ObjectUtils.isEmpty(newUserList)) {
                            log.info("预约用户新增，size:{}", newUserList.size());
                            appointmentPersonService.save(newUserList);
                        }
                    }
                }
            }
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


    public static void main(String[] args) {


        System.out.println(DateUtil.parse("19951071", "yyyyMMdd"));
    }


}
