package com.xjrsoft.module.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.google.gson.JsonObject;
import com.xjrsoft.common.enums.GenderIntEnum;
import com.xjrsoft.module.attendance.vo.VisitorInfoVo;
import com.xjrsoft.module.hikvision.entity.HikvisionData;
import com.xjrsoft.module.hikvision.mapper.HikvisionDataMapper;
import com.xjrsoft.module.hikvision.util.ApiUtil;
import com.xjrsoft.module.personnel.entity.ReservationSchoolPeople;
import com.xjrsoft.module.personnel.mapper.ReservationSchoolPeopleMapper;
import com.xjrsoft.module.personnel.entity.ReservationSchool;
import com.xjrsoft.module.personnel.mapper.ReservationSchoolMapper;
import com.xjrsoft.module.personnel.service.IReservationSchoolService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
* @title: 预约进校
* @Author dzx
* @Date: 2024-05-11
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class ReservationSchoolServiceImpl extends MPJBaseServiceImpl<ReservationSchoolMapper, ReservationSchool> implements IReservationSchoolService {
    private final ReservationSchoolMapper reservationSchoolMapper;

    private final ReservationSchoolPeopleMapper reservationSchoolPeopleMapper;

    private final HikvisionDataMapper hikvisionDataMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ReservationSchool reservationSchool) {
        reservationSchoolMapper.insert(reservationSchool);
        for (ReservationSchoolPeople reservationSchoolPeople : reservationSchool.getReservationSchoolPeopleList()) {
            reservationSchoolPeople.setReservationSchooId(reservationSchool.getId());
            reservationSchoolPeopleMapper.insert(reservationSchoolPeople);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ReservationSchool reservationSchool) {
        reservationSchoolMapper.updateById(reservationSchool);
        //********************************* ReservationSchoolPeople  增删改  开始 *******************************************/
        {
            // 查出所有子级的id
            List<ReservationSchoolPeople> reservationSchoolPeopleList = reservationSchoolPeopleMapper.selectList(Wrappers.lambdaQuery(ReservationSchoolPeople.class).eq(ReservationSchoolPeople::getReservationSchooId, reservationSchool.getId()).select(ReservationSchoolPeople::getId));
            List<Long> reservationSchoolPeopleIds = reservationSchoolPeopleList.stream().map(ReservationSchoolPeople::getId).collect(Collectors.toList());
            //原有子表单 没有被删除的主键
            List<Long> reservationSchoolPeopleOldIds = reservationSchool.getReservationSchoolPeopleList().stream().map(ReservationSchoolPeople::getId).filter(Objects::nonNull).collect(Collectors.toList());
            //找到需要删除的id
            List<Long> reservationSchoolPeopleRemoveIds = reservationSchoolPeopleIds.stream().filter(item -> !reservationSchoolPeopleOldIds.contains(item)).collect(Collectors.toList());

            for (ReservationSchoolPeople reservationSchoolPeople : reservationSchool.getReservationSchoolPeopleList()) {
                //如果不等于空则修改
                if (reservationSchoolPeople.getId() != null) {
                    reservationSchoolPeopleMapper.updateById(reservationSchoolPeople);
                }
                //如果等于空 则新增
                else {
                    //已经不存在的id 删除
                    reservationSchoolPeople.setReservationSchooId(reservationSchool.getId());
                    reservationSchoolPeopleMapper.insert(reservationSchoolPeople);
                }
            }
            //已经不存在的id 删除
            if(reservationSchoolPeopleRemoveIds.size() > 0){
                reservationSchoolPeopleMapper.deleteBatchIds(reservationSchoolPeopleRemoveIds);
            }
        }
        //********************************* ReservationSchoolPeople  增删改  结束 *******************************************/

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        reservationSchoolMapper.deleteBatchIds(ids);
        reservationSchoolPeopleMapper.delete(Wrappers.lambdaQuery(ReservationSchoolPeople.class).in(ReservationSchoolPeople::getReservationSchooId, ids));

        return true;
    }

    /**
     * 预约免登记
     * @param dataObj
     * @return
     */
    @Override
    public Boolean registration(ReservationSchool dataObj) {
        String apiPath = "/api/visitor/v1/appointment/registration";
        ApiUtil apiUtil = new ApiUtil();

        //查询被访人id
        HikvisionData hikvisionData = hikvisionDataMapper.selectOne(
                new QueryWrapper<HikvisionData>().lambda()
                        .eq(HikvisionData::getSourceId, dataObj.getRespondentUserId())
                        .eq(HikvisionData::getTableName, "base_teacher")
        );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00");
        List<ReservationSchoolPeople> peopleList = dataObj.getReservationSchoolPeopleList();
        for (ReservationSchoolPeople people : peopleList) {
            JsonObject paramJson = new JsonObject();
            paramJson.addProperty("receptionistId", hikvisionData.getHikvisionId());

            paramJson.addProperty("visitStartTime", sdf.format(dataObj.getStartTime()));
            paramJson.addProperty("visitEndTime", sdf.format(dataObj.getEndTime()));

            //查询来访人数
            paramJson.addProperty("personNum", dataObj.getReservationSchoolPeopleList().size());
            paramJson.addProperty("visitorInfo", dataObj.getReservationSchoolPeopleList().size());
            paramJson.addProperty("personNum", dataObj.getReservationSchoolPeopleList().size());
            JsonObject visitorInfo = new JsonObject();
            visitorInfo.addProperty("visitorName", people.getName());
            visitorInfo.addProperty("gender", GenderIntEnum.getValue(people.getGender()));
            visitorInfo.addProperty("phoneNo", people.getPhone());
            if("是".equals(people.getIsCar())){
                visitorInfo.addProperty("plateNo", people.getPlateNumber());
            }
            visitorInfo.addProperty("certificateNo", people.getIdentityCard());
            visitorInfo.addProperty("certificateType", "111");
            paramJson.add("visitorInfo", visitorInfo);

            String result = apiUtil.doPost(apiPath, paramJson.toString(), null);

            people.setRegistrationResult(result);
            reservationSchoolPeopleMapper.updateById(people);
        }

        return true;
    }

    @Override
    public List<VisitorInfoVo> getVisionList(String date) {
        return reservationSchoolMapper.getVisionList(date);
    }
}
