package com.ssm.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.HttpClientUtil;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.*;
import com.ssm.manage.dto.BlackListDto;
import com.ssm.manage.dto.JobContentListDto;
import com.ssm.manage.entity.BlackList;
import com.ssm.manage.entity.JobContentList;
import com.ssm.manage.entity.RegionList;
import com.ssm.manage.response.JobContentListVo;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.JobContentListService;
import com.ssm.manage.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 工作内容
 * (JobContentList)表服务实现类
 *
 * @author makejava
 * @since 2023-12-19 13:56:51
 */
@Service("jobContentListService")
@Slf4j
public class JobContentListServiceImpl extends BaseServiceImpl<JobContentList> implements JobContentListService {
    @Autowired
    private JobContentListDao jobContentListDao;
    @Autowired
    private RegionListDao regionListDao;

    @Autowired
    private BlackListDao blackListDao;

    @Autowired
    private StaffTemporaryDao staffTemporaryDao;

    @Override
    public BaseDao<JobContentList> getDao() {
        return jobContentListDao;
    }

    @Override
    public PageInfo<JobContentListVo> selectPage(JobContentListDto dto) {
        List<String> snNum = new ArrayList<>();
        snNum.add("TBB5235000125");
        snNum.add("TBB5235000149");
        snNum.add("TBB5235000151");
        snNum.add("TBB5235000152");
        snNum.add("TBB5235000243");
        snNum.add("TBB5235000254");
        Example example = new Example(JobContentList.class);
        Example.Criteria criteria = example.createCriteria();
        if (Objects.nonNull(dto.getStartTime())){
            criteria.andBetween(JobContentListDto.Fields.checkTime,dto.getStartTime(),dto.getLastTime());
        }
        if(StringUtils.isNotBlank(dto.getStaffName())){
            criteria.andLike(JobContentListDto.Fields.staffName,dto.getStaffName());
        }
        if(Objects.nonNull(dto.getType())){
            criteria.andEqualTo(JobContentListDto.Fields.type,dto.getType());
        }
        if(StringUtils.isNotBlank(dto.getMobilePhone())){
            criteria.andLike(JobContentListDto.Fields.mobilePhone,dto.getMobilePhone());
        }
        if(Objects.nonNull(dto.getSex())){
            criteria.andEqualTo(JobContentListDto.Fields.sex,dto.getSex());
        }
        if(StringUtils.isNotBlank(dto.getIdentityCard())){
            criteria.andEqualTo(JobContentListDto.Fields.identityCard,dto.getIdentityCard());
        }
        criteria.andIn(JobContentListDto.Fields.equipmentNum,snNum);
        criteria.andEqualTo(JobContentListDto.Fields.storeId,dto.getStoreId());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<JobContentList> list = this.jobContentListDao.selectByExample(example);
        List<JobContentListVo> voList = new ArrayList<>();
        for (JobContentList jobContentList : list) {
            JobContentListVo vo = new JobContentListVo();
            BeanUtils.copyProperties(jobContentList,vo);
            BlackList blackList = new BlackList();
            blackList.setIdentityCard(jobContentList.getIdentityCard());
            vo.setBlackList(blackListDao.select(blackList).get(0));
            RegionList regionList = regionListDao.selectByPrimaryKey(jobContentList.getRegionId());
            vo.setRegionList(regionList);

            voList.add(vo);
        }
        PageInfo<JobContentList> pageInfo = new PageInfo<>(list);
        PageInfo<JobContentListVo> info = new PageInfo<>();
        BeanUtils.copyProperties(pageInfo,info);
        info.setList(voList);
        return info;
    }
    @Value("${zhongkong.key}")
    private String key;
    @Value("${zhongkong.host}")
    private String host;

    @Override
    @Transactional
    public PageInfo<JobContentListVo> getJobContext(StaffResponse staffResponse,String starttime,String endtime) throws IOException, ParseException {
        //调中控
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> includeEquipmentNums = new ArrayList<>();
        includeEquipmentNums.add("TBB5235000125");
        includeEquipmentNums.add("TBB5235000149");
        includeEquipmentNums.add("TBB5235000151");
        includeEquipmentNums.add("TBB5235000152");
        includeEquipmentNums.add("TBB5235000243");
        includeEquipmentNums.add("TBB5235000254");
        String url = "http://"+host+"/api/v2/transaction/get/?key="+key;
        Map<String, Object> map1 = new HashMap<>();
        map1.put("starttime",starttime);
//        map1.put("starttime","2024-01-01 00:00:00");
        map1.put("endtime",endtime);
//        map1.put("endtime","2024-01-09 23:59:59");
        JSONObject jsonObject = new JSONObject(map1);
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("param",JSON.toJSON(jsonObject)) ;
        String response = HttpClientUtil.doPost(url, jsonobject);

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = objectMapper.readValue(response, Map.class);
        if (map.containsKey("ret")&&map.get("ret").toString().equals("0")){
            //循环遍历map
            Map<String,Object> data = objectMapper.convertValue( map.get("data"), Map.class);
            List<Map<String,Object>> list = (List<Map<String,Object>>) data.get("items");
            for (Map<String, Object> jobMap : list) {
                Object sn = jobMap.get("sn");
                if (!includeEquipmentNums.contains(sn)) {
                    log.info("Exclude:{}", jobMap);
                    continue;   // 不在设备列表的, 直接排除
                }

                //查询员工信息
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo(BlackListDto.Fields.staffNum,jobMap.get("pin"));
                List<BlackList> blackLists = blackListDao.selectByExample(example);
                if (!CollectionUtils.isEmpty(blackLists)) {
                    Date checkTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(jobMap.get("checktime").toString());

                    BlackList blackList = blackLists.get(0);
                    Example jobExampl = new Example(JobContentList.class);
                    jobExampl.setOrderByClause("check_time desc");
                    Example.Criteria jobExamplCriteria = jobExampl.createCriteria();
                    jobExamplCriteria.andEqualTo(JobContentListDto.Fields.staffNum,jobMap.get("pin"));
                    jobExamplCriteria.andIn(JobContentListDto.Fields.equipmentNum, includeEquipmentNums);
                    jobExamplCriteria.andBetween(JobContentListDto.Fields.checkTime, starttime, endtime);
                    List<JobContentList> contentLists = jobContentListDao.selectByExample(jobExampl);
                    /*if (!CollectionUtils.isEmpty(contentLists) && contentLists.size()==1){
                        JobContentList contentList = contentLists.get(0);
                        contentList.setCheckEndTime(format.parse(jobMap.get("checktime").toString()));
                        jobContentListDao.updateByPrimaryKey(contentList);
                        continue;
                    }*/

                    JobContentList jobContentList = new JobContentList();
                    jobContentList.setStaffName(blackList.getStaffName());
                    jobContentList.setStaffId(blackList.getId());
                    jobContentList.setSex(blackList.getSex());
                    jobContentList.setMobilePhone(blackList.getMobilePhone());
                    jobContentList.setIdentityCard(blackList.getIdentityCard());
                    jobContentList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    jobContentList.setStaffNum(jobMap.get("pin").toString());
                    jobContentList.setDeptNumber(jobMap.get("deptnumber").toString());
                    jobContentList.setDeptName(jobMap.get("deptname").toString());
                    jobContentList.setCheckTime(format.parse(jobMap.get("checktime").toString()));
                    jobContentList.setEquipmentNum(jobMap.get("sn").toString());
                    jobContentList.setEquipmentName(jobMap.get("alias").toString());
                    jobContentList.setCheckContent(jobMap.get("photograph") == null ? "" : jobMap.get("photograph").toString());
                    jobContentList.setType(jobMap.get("stateno") == null ? null : Integer.valueOf(jobMap.get("stateno").toString()));
//                    jobContentList.setType(blackList.getType());
                    jobContentList.setCheckContent(jobMap.get("state") == null ? null : jobMap.get("state").toString());
                    if ((Integer) jobMap.get("verify") == 15)
                        jobContentList.setVerify("人脸");

                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contentLists)) {
                        AtomicReference<Date> earliestTimeAtom = new AtomicReference<>(checkTime);
                        AtomicReference<Date> latestTimeAtom = new AtomicReference<>(checkTime);
                        AtomicReference<JobContentList> fullJcl = new AtomicReference<>(jobContentList);

                        // 查找最早和最晚时间
                        contentLists.forEach(jobCL -> {
                            Date ct = jobCL.getCheckTime();
                            Date checkEndTime = jobCL.getCheckEndTime();
                            Date earliestTime = earliestTimeAtom.get();
                            Date latestTime = latestTimeAtom.get();
                            if (earliestTime == null || earliestTime.after(ct)) {
                                earliestTimeAtom.set(ct);
                                fullJcl.set(jobCL);
                            }
                            if (checkEndTime != null) {
                                ct = checkEndTime;
                            }
                            if (latestTime == null || latestTime.before(ct)) {
                                latestTimeAtom.set(ct);
                            }
                        });

                        // 合并成一条,并移除其它冗余记录
                        JobContentList contentList = fullJcl.get();
                        boolean equals = jobContentList.equals(contentList);
                        if (!equals) {
                            contentLists.remove(contentList);
                        }

                        contentLists.forEach(jcl -> jobContentListDao.delete(jcl));

                        boolean contains = contentLists.contains(contentList);
                        contentList.setCheckTime(earliestTimeAtom.get());
                        contentList.setCheckEndTime(latestTimeAtom.get());
                        if (!equals || contains) {
                            jobContentListDao.updateByPrimaryKey(contentList);
                            continue;
                        }
                    }

                    jobContentList.setStoreId(staffResponse.getStoreId());
                    try {
                        jobContentListDao.insert(jobContentList);
                    } catch (Exception e) {
                        log.error("数据插入失败");
                    }
                }
            }
        }
        return null;
    }
}
