package com.mosty.bkzx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.model.dto.bkzx.TbBkRyInsertDto;
import com.mosty.base.model.dto.bkzx.TbBkRyJudgeDto;
import com.mosty.base.model.entity.bkzx.TbBkRy;
import com.mosty.base.model.query.bkzx.TbBkRySearchDto;
import com.mosty.bkzx.mapper.TbBkRyMapper;
import com.mosty.bkzx.remote.TbBaseAdaptRemoteService;
import com.mosty.bkzx.service.TbBkRyService;
import com.mosty.bkzx.sjjs.client.HttpClient;
import com.mosty.bkzx.sjjs.domain.ResponseStatusList;
import com.mosty.bkzx.sjjs.dto.SubImageListDTO;
import com.mosty.bkzx.sjjs.entity.Face;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.base.util.StringUtils;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dw
 * @since 2022/7/13
 * 布控人员服务-实现
 **/
@AllArgsConstructor
@Service
public class TbBkRyServiceImpl extends ServiceImpl<TbBkRyMapper, TbBkRy>
        implements TbBkRyService {
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    @Override
    public int addEntity(TbBkRyInsertDto dto) {
        // 查询是否有重复的数据
        TbBkRy ryItem = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbBkRy>()
                        .eq(TbBkRy::getXtSjzt, "1")
                        .eq(TbBkRy::getBklx, dto.getBklx())
                        .eq("1".equals(dto.getBklx()), TbBkRy::getSfzh, dto.getSfzh())
                        .eq("2".equals(dto.getBklx()), TbBkRy::getSjhm, dto.getSjhm())
                        .eq("3".equals(dto.getBklx()), TbBkRy::getHzhm, dto.getHzhm())
                        .eq("4".equals(dto.getBklx()), TbBkRy::getImsi, dto.getImsi())
                        .eq("5".equals(dto.getBklx()), TbBkRy::getImei, dto.getImei())
                        .last(" limit 1")
        );
        if (ryItem != null) {
            throw new BusinessException("该人员已经存在，请修改布控状态或重新录入");
        }
        UserInfo user = UserInfoManager.get();
        // 计算布控天数
        int bkts = 0;
        try {
            bkts = DateUtils.daysBetween(dto.getBkkssj(), dto.getBkjssj());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("时间格式转换异常");
        }
        TbBkRy ry = new TbBkRy();
        BeanUtils.copyProperties(dto, ry);
        ry.setBkts(bkts);
        ry.setShzt("0");
        ry.setBkzt("0");
        ry.setXtSjly("1");
        ry.setSqrid(String.valueOf(user.getUserId()));
        ry.setSqrsfzh(user.getIdEntityCard());
        ry.setSqrxm(user.getUserName());
        ry.setSsbm(user.getDeptName());
        ry.setSsbmdm(user.getDeptCode());
        ry.setSfqsbkcg("0");
        ry.setSfqsebkcg("0");
        return this.baseMapper.insert(ry);
    }

    @Override
    public IPage<TbBkRy> getPageList(TbBkRySearchDto dto) {
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        QueryWrapper<TbBkRy> qw = new QueryWrapper<>();
        IPage<TbBkRy> page = this.baseMapper.selectPage(
                new Page<>(dto.getPageNum(), dto.getPageSize()),
                qw.lambda()
                        .like(StringUtils.isNotBlank(dto.getXm()), TbBkRy::getXm, dto.getXm())
                        .likeRight(StringUtils.isNotBlank(dto.getSsbmdm()), TbBkRy::getSsbmdm, dto.getSsbmdm())
                        .eq(StringUtils.isNotBlank(dto.getBkjb()), TbBkRy::getBkjb, dto.getBkjb())
                        .eq(StringUtils.isNotBlank(dto.getShzt()), TbBkRy::getShzt, dto.getShzt())
                        .eq(StringUtils.isNotBlank(dto.getBkzt()), TbBkRy::getBkzt, dto.getBkzt())
                        .eq(StringUtils.isNotBlank(dto.getBklx()), TbBkRy::getBklx, dto.getBklx())
                        .and(StringUtils.isNotBlank(dto.getKeyword()),
                                ew -> ew.like(TbBkRy::getSfzh, dto.getKeyword())
                                        .or().like(TbBkRy::getSjhm, dto.getKeyword())
                                        .or().like(TbBkRy::getHzhm, dto.getKeyword())
                                        .or().like(TbBkRy::getImsi, dto.getKeyword())
                                        .or().like(TbBkRy::getImei, dto.getKeyword())
                        ).orderByDesc(TbBkRy::getXtCjsj)
        );
        // 查询状态是否过期
        List<TbBkRy> ryList = page.getRecords();
        ryList.forEach(item -> {
            if ("1".equals(item.getBkzt())) {
                if (new Date().getTime() >= item.getBkjssj().getTime()) {
                    item.setBkzt("2");
                    this.baseMapper.updateById(item);
                }
            }
        });
        page.setRecords(ryList);
        return page;
    }

    @Override
    public TbBkRy getInfo(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public int editPerson(TbBkRyInsertDto dto) {
        // 查询是否有重复的数据
        TbBkRy ryItem = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbBkRy>()
                        .eq(TbBkRy::getXtSjzt, "1")
                        .eq(TbBkRy::getBklx, dto.getBklx())
                        .eq("1".equals(dto.getBklx()), TbBkRy::getSfzh, dto.getSfzh())
                        .eq("2".equals(dto.getBklx()), TbBkRy::getSjhm, dto.getSjhm())
                        .eq("3".equals(dto.getBklx()), TbBkRy::getHzhm, dto.getHzhm())
                        .eq("4".equals(dto.getBklx()), TbBkRy::getImsi, dto.getImsi())
                        .eq("5".equals(dto.getBklx()), TbBkRy::getImei, dto.getImei())
                        .ne(TbBkRy::getId, dto.getId())
                        .last(" limit 1")
        );
        if (ryItem != null) {
            throw new BusinessException("该人员已经存在，请修改布控状态或重新录入");
        }
        UserInfo user = UserInfoManager.get();
        // 计算布控天数
        int bkts = 0;
        try {
            bkts = DateUtils.daysBetween(dto.getBkkssj(), dto.getBkjssj());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("时间格式转换异常");
        }
        TbBkRy ry = this.getInfo(dto.getId());
        BeanUtils.copyProperties(dto, ry);
        ry.setBkts(bkts);
        ry.setShzt("0");
        ry.setBkzt("0");
        ry.setSqrid(String.valueOf(user.getUserId()));
        ry.setSqrsfzh(user.getIdEntityCard());
        ry.setSqrxm(user.getUserName());
        ry.setSsbm(user.getDeptName());
        ry.setSsbmdm(user.getDeptCode());
        return this.baseMapper.updateById(ry);
    }

    @Override
    public int delPerson(List<String> ids) {
        return this.baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int endBk(String id) {
        TbBkRy ry = this.baseMapper.selectById(id);
        if (ry != null) {
            ry.setBkzt("2");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ry.getBkid())) {
                HttpClient.delFaces(ry.getBkid(), ry.getBkkid());
            }
            return this.baseMapper.updateById(ry);
        }
        return 0;
    }

    @Override
    public int startBk(String id) {
        TbBkRy ry = this.baseMapper.selectById(id);
        // 查看布控时间是否过期
        if (ry != null) {
            if (new Date().getTime() >= ry.getBkjssj().getTime()) {
                throw new BusinessException("布控结束时间已过，请重新修改布控时间！！");
            }
            ry.setBkzt("0");
            ry.setShzt("0");
            //删除成员
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ry.getBkid())) {
                HttpClient.delFaces(ry.getBkid(), ry.getBkkid());
            }

            return this.baseMapper.updateById(ry);
        }
        return 0;
    }

    @Override
    public int judge(TbBkRyJudgeDto dto) {
        TbBkRy ry = this.baseMapper.selectById(dto.getId());
        if (ry == null) {
            throw new BusinessException("布控人员信息不存在");
        }
        ry.setShzt(dto.getShzt());
        if ("1".equals(dto.getShzt())) {
            if (ry.getBkjssj().getTime() <= new Date().getTime() + 60 * 60 * 1000) {
                throw new BusinessException("布控结束时间不正确，请确保结束时间在1小时之后！");
            }
            ry.setBkzt("1");
        } else if ("2".equals(dto.getShzt())) {
            ry.setBkzt("3");
        }
        ry.setShsm(StringUtils.isBlank(dto.getShsm()) ? "审核通过" : dto.getShsm());
        UserInfo userInfo = UserInfoManager.get();
        ry.setShryid(String.valueOf(userInfo.getUserId()));
        ry.setShrybm(userInfo.getDeptName());
        ry.setShrybmdm(String.valueOf(userInfo.getDeptId()));
        ry.setShryxm(userInfo.getUserName());

        //通过添加到大华
        if (ry.getShzt().equals("1")) {
            try {
                Face face = new Face();
                face.setIDType("111");//默认身份证
                face.setIDNumber(ry.getSfzh());
                face.setName(ry.getXm());
                face.setGenderCode(ry.getXbdm());
                List<SubImageListDTO.SubImageInfoObjectDTO> list = new ArrayList<>();
                SubImageListDTO.SubImageInfoObjectDTO subImageInfoObjectDTO = new SubImageListDTO.SubImageInfoObjectDTO();
                //minio获取图片
//                String url = tbBaseAdaptRemoteService.downloadUrl(ry.getRxtpdz());
                String base64 = tbBaseAdaptRemoteService.downloadBaes64(ry.getRxtpdz());//照片一定不为空
                if (StringUtils.isNotEmpty(base64)) {
                    subImageInfoObjectDTO.setStoragePath(base64);
                    subImageInfoObjectDTO.setLeftTopX(0);
                    subImageInfoObjectDTO.setLeftTopY(0);
                    subImageInfoObjectDTO.setRightBtmX(0);
                    subImageInfoObjectDTO.setRightBtmY(0);
                    list.add(subImageInfoObjectDTO);
                    SubImageListDTO subImageListDTO = new SubImageListDTO();
                    subImageListDTO.setSubImageInfoObject(list);
                    face.setSubImageList(subImageListDTO);
                    //调用大华布控添加人员
                    //设置布控库人员id
                    String faceId = ry.getBkkid() + "06" + String.valueOf((int) ((Math.random() * 9 + 1) * 10000));
                    face.setFaceID(faceId);
                    //设置布控库
                    face.setTabID(ry.getBkkid());
                    String faces = HttpClient.insertFaces(face);
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(faces)) {
                        ResponseStatusList responseStatusList = JSONObject.parseObject(faces, ResponseStatusList.class);
                        if (null != responseStatusList && responseStatusList.getResponseStatusListObject().getResponseStatusObject().get(0).getStatusCode().equals("0")) {
                            //保存布控库人员id
                            ry.setBkid(faceId);
                        }
                    }
                }

            } catch (Exception e) {
                System.out.println("添加大华布控成员失败------->" + e.getMessage());
                throw new BusinessException("添加大华布控成员失败 请重试！");
            }

        } else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ry.getBkid())) {
                HttpClient.delFaces(ry.getBkid(), ry.getBkkid());
            }
        }
        return this.baseMapper.updateById(ry);
    }
}
