package com.zcloud.primeport.gatewayimpl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
import com.zcloud.gbscommon.todolistmq.event.TodoListAddEvent;
import com.zcloud.gbscommon.todolistmq.event.TodoListCompleteEvent;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.primeport.domain.gateway.PersonApplyGateway;
import com.zcloud.primeport.domain.model.PersonApplyE;
import com.zcloud.primeport.domain.model.XgfApplyPersonE;
import com.zcloud.primeport.persistence.dataobject.PersonApplyDO;
import com.zcloud.primeport.persistence.dataobject.PersonMessageDO;
import com.zcloud.primeport.persistence.dataobject.XgfApplyPersonDO;
import com.zcloud.primeport.persistence.repository.PersonApplyRepository;
import com.zcloud.primeport.persistence.repository.PersonMessageRepository;
import com.zcloud.primeport.persistence.repository.XgfApplyPersonRepository;
import com.zcloud.primeport.plan.mjDevice.OnePersonUtil;
import jodd.util.Base64;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * web-infrastructure
 *
 * @Author makejava
 * @Date 2026-03-05 11:33:22
 */
@Service
@AllArgsConstructor
public class PersonApplyGatewayImpl implements PersonApplyGateway {
    private final PersonApplyRepository personApplyRepository;
    private final XgfApplyPersonRepository xgfApplyPersonRepository;
    private final PersonMessageRepository personMessageRepository;
    private final OnePersonUtil onePersonUtil;

    @Override
    public Boolean add(PersonApplyE personApplyE) {
        PersonApplyDO d = new PersonApplyDO();
        BeanUtils.copyProperties(personApplyE, d);
        personApplyRepository.save(d);
        return true;
    }

    @Override
    public Boolean update(PersonApplyE personApplyE) {
        PersonApplyDO d = new PersonApplyDO();
        BeanUtils.copyProperties(personApplyE, d);
        personApplyRepository.updateById(d);
        return true;
    }

    @Override
    public Boolean deletedPersonApplyById(Long id) {
        return personApplyRepository.removeById(id);
    }

    @Override
    public Boolean deletedPersonApplyByIds(Long[] ids) {
        return personApplyRepository.removeByIds(Collections.singletonList(ids));
    }

    @Override
    public void saveBatch(ArrayList<PersonApplyE> personApplyES) {
        ArrayList<PersonApplyDO> d = new ArrayList<>();
        personApplyES.forEach(item -> {
            PersonApplyDO doItem = new PersonApplyDO();
            BeanUtils.copyProperties(item, doItem);
            d.add(doItem);
        });
        personApplyRepository.saveBatch(d);
    }

    @Override
    public void xgfPersonAudit(XgfApplyPersonE build) throws Exception {
        XgfApplyPersonDO d = new XgfApplyPersonDO();
        BeanUtils.copyProperties(build, d);
        xgfApplyPersonRepository.updateById(d);
        UpdateWrapper<PersonApplyDO> objectQueryWrapper = new UpdateWrapper<>();
        objectQueryWrapper.set("mkmj_permission", build.getAuditFlag().equals(2) ? 1 : 2);
        objectQueryWrapper.eq("xgf_apply_person_id", d.getId());
        personApplyRepository.update(objectQueryWrapper);
        if (build.getAuditFlag().equals(2)) {
            // 审核通过后添加人员信息
            XgfApplyPersonDO byId = xgfApplyPersonRepository.getById(d.getId());
            QueryWrapper<PersonApplyDO> personApplyDOQueryWrapper = new QueryWrapper<>();
            personApplyDOQueryWrapper.eq("xgf_apply_person_id", d.getId());
            List<PersonApplyDO> list = personApplyRepository.list(personApplyDOQueryWrapper);
            UpdateWrapper<PersonApplyDO> personApplyDOUpdateWrapper = new UpdateWrapper<>();
            personApplyDOUpdateWrapper.set("mkmj_permission", 1);
            personApplyDOUpdateWrapper.eq("xgf_apply_person_id", d.getId());
            ArrayList<PersonMessageDO> personMessageDOS = new ArrayList<>();
            HashSet<String> userCardHashSet = new HashSet<>();
            HashMap<String, JSONObject> stringJSONObjectHashMap = new HashMap<>();
            list.forEach(item -> {
                PersonMessageDO messageDO = new PersonMessageDO();
                messageDO.setPersonBelongType(byId.getPersonBelongType());
                messageDO.setPersonApplyId(d.getId());
                messageDO.setSyncStatus(2);
                messageDO.setGateLevelAuthArea(byId.getGateLevelAuthArea());
                messageDO.setUserFaceUrl(item.getUserFaceUrl());
                messageDO.setUserCard(item.getUserCard());
                messageDO.setVisitStartTime(byId.getVisitStartTime());
                messageDO.setVisitEndTime(byId.getVisitEndTime());
                personMessageDOS.add(messageDO);
                try {
                    userCardHashSet.add(Base64.decodeToString(item.getUserCard()));
                } catch (Exception e) {
                    throw new BizException("用户身份证解析错误");
                }
                JSONObject entries = new JSONObject();
                entries.set("name", item.getEmployeePersonUserName());
                entries.set("code", "hbqa" + Base64.decodeToString(item.getUserCard()));
                entries.set("validStartTime", byId.getVisitStartTime() + " 00:00:00");
                entries.set("validEndTime", byId.getVisitEndTime() + " 23:59:59");
                entries.set("paperType", 111);
                entries.set("paperNumber", Base64.decodeToString(item.getUserCard()));
                entries.set("departmentId", 1);
                JSONObject fileInfo = new JSONObject();
                List<JSONObject> dataList = new ArrayList();
                fileInfo.set("type", 3);
                fileInfo.set("index", 1);
                fileInfo.set("path", item.getUserFaceUrl());
                dataList.add(fileInfo);
                entries.set("personBiosignatures", dataList);
                stringJSONObjectHashMap.put(Base64.decodeToString(item.getUserCard()), entries);
                // byId.getPersonBelongType()
                // onePersonUtil.dockLongTermUserByUserCardAndFaceImg()
            });
            personMessageRepository.saveBatch(personMessageDOS);
            dcokDoorEquipment(userCardHashSet, stringJSONObjectHashMap);
        }
    }

    // 对接口门设备
    public void dcokDoorEquipment(HashSet<String> userCardHashSet, HashMap<String, JSONObject> userHashMap) throws Exception {
        // 对接过的用户信息
        ArrayList<JSONObject> waitSaveUser = new ArrayList<>();
        ArrayList<JSONObject> waitEditUser = new ArrayList<>();
        ArrayList<String> dockEdUserCards = new ArrayList<>();
        JSONArray mkmjUserInfoByUserCard = onePersonUtil.getMkmjUserInfoByUserCard(new ArrayList<>(userCardHashSet));
        HashMap<String, JSONObject> mjDeviceHashMap = new HashMap<>();
        for (int i = 0; i < mkmjUserInfoByUserCard.size(); i++) {
            JSONObject jsonObject = mkmjUserInfoByUserCard.getJSONObject(i);
            mjDeviceHashMap.put(jsonObject.getStr("paperNumber"), jsonObject);
        }
        for (String s : userHashMap.keySet()) {
            JSONObject entries = userHashMap.get(s);
            if (mjDeviceHashMap.containsKey(s)) {
                JSONObject o = mjDeviceHashMap.get(s);
                // 已存在 看下今天是不是在 申请的时间里
                long validStartTime = DateUtil.fomatDate(entries.getStr("validStartTime") + "00:00:00", "yyyy-MM-dd HH:mm:ss").getTime();
                long validEndTime = DateUtil.fomatDate(entries.getStr("validEndTime") + "23:59:59", "yyyy-MM-dd HH:mm:ss").getTime();
                long time = new Date().getTime();
                if (time >= validStartTime && time <= validEndTime) {
                    // 今天在申请的时间里 需要修改
                    JSONObject entries1 = new JSONObject();
                    entries1.set("personId", o.getLong("id"));
                    entries1.set("validStartTime", DateUtil.date2Str(new Date(), "yyyy-MM-dd") + "00:00:00");
                    entries1.set("validEndTime", DateUtil.date2Str(new Date(), "yyyy-MM-dd") + "23:59:59");
                    waitEditUser.add(entries1);
                }
            } else {
                // 新增的
                waitSaveUser.add(entries);
            }
        }
//        for (int i = 0; i < mkmjUserInfoByUserCard.size(); i++) {
//            JSONObject o = mkmjUserInfoByUserCard.getJSONObject(i);
//            String str = o.getStr("paperNumber");
//            JSONObject entries = userHashMap.get(str);
//            if (userCardHashSet.add(str)) {
//                // 要新增的
//                waitSaveUser.add(entries);
//            } else {
//
//                }
//            }
//            dockEdUserCards.add(str);
//        }
            if (!waitSaveUser.isEmpty()) {
                onePersonUtil.batchSaveUser(waitSaveUser);
            }
            if (!waitEditUser.isEmpty()) {
                onePersonUtil.expirationDateRefreshedUserCard(waitEditUser);
            }
        }

        @Override
        public List<PersonApplyE> personListByxgfApplyPersonId (Long id){
            QueryWrapper<PersonApplyDO> xgfApplyPersonDOQueryWrapper = new QueryWrapper<>();
            xgfApplyPersonDOQueryWrapper.eq("xgf_apply_person_id", id);
            List<PersonApplyDO> xgfApplyPersonDOS = personApplyRepository.list(xgfApplyPersonDOQueryWrapper);
            ArrayList<PersonApplyE> xgfApplyPersonES = new ArrayList<>();
            xgfApplyPersonDOS.forEach(item -> {
                PersonApplyE xgfApplyPersonE = new PersonApplyE();
                BeanUtils.copyProperties(item, xgfApplyPersonE);
                xgfApplyPersonES.add(xgfApplyPersonE);
            });
            return xgfApplyPersonES;
        }

        @Override
        public XgfApplyPersonE getXgfApplyPersonById (Long id) {
            XgfApplyPersonDO byId = xgfApplyPersonRepository.getById(id);
            XgfApplyPersonE e = new XgfApplyPersonE();
            BeanUtils.copyProperties(byId, e);
            return e;
        }

        public static void main (String[]args){
            HashSet<String> strings = new HashSet<>();
            System.out.println(strings.add("1"));
            System.out.println(strings.add("2"));
            System.out.println(strings.add("3"));
            System.out.println(strings.add("1"));
        }
    }

