package com.dcsoft.system.visitor.service.impl;

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

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.enums.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.common.core.web.page.TableDataInfoPage;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.domain.vo.TreeSelect;
import com.dcsoft.system.ladder.domain.*;
import com.dcsoft.system.ladder.mapper.TEmpowerManageMapper;
import com.dcsoft.system.ladder.mapper.TLadderConfigMapper;
import com.dcsoft.system.ladder.mapper.TLadderRuleMapper;
import com.dcsoft.system.mapper.SysBlackListMapper;
import com.dcsoft.system.mapper.SysBranchMapper;
import com.dcsoft.system.mapper.SysDictDataMapper;
import com.dcsoft.system.utils.FloorUtil;
import com.dcsoft.system.utils.ImageToBase64Utils;
import com.dcsoft.system.visitor.domain.*;
import com.dcsoft.system.visitor.mapper.VisitorMapper;
import com.dcsoft.system.visitor.service.IVisitorService;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.dcsoft.common.datascope.annotation.DataScope;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import static com.dcsoft.common.core.utils.PageUtils.startPage;

/**
 * 访客信息Service业务层处理
 *
 * @author 倪春
 * @date 2023-03-09
 */
@Slf4j
@Service
public class VisitorServiceImpl implements IVisitorService
{
    @Resource
    private VisitorMapper visitorMapper;

    @Resource
    private SysBlackListMapper sysBlackListMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Value("${system.type}")
    public String systemType;

    /**
     * 卡权限创建接口
     */
    public static final String create = "/cardinfo/create";

    @Value("${artemis.url}")
    public String url;
    @Value("${artemis.appKey}")
    public String appKey;
    @Value("${artemis.appSecret}")
    public String appSecret;

    private static final String ARTEMIS_PATH = "/artemis";

    /**
     * 查询访客信息
     *
     * @param id 访客信息主键
     * @return 访客信息
     */
    @Override
    public Visitor selectVisitorById(Long id)
    {
        return visitorMapper.selectVisitorById(id);
    }

    /**
     * 查询访客信息列表
     *
     * @param visitor 访客信息
     * @return 访客信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Visitor> selectVisitorList(Visitor visitor)
    {
        return visitorMapper.selectVisitorList(visitor);
    }

    /**
     * 新增访客信息
     *
     * @param visitor 访客信息
     * @return 结果
     */
    @Override
    public int insertVisitor(Visitor visitor)
    {
        return visitorMapper.insertVisitor(visitor);
    }

    /**
     * 修改访客信息
     *
     * @param visitor 访客信息
     * @return 结果
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public int updateVisitor(Visitor visitor)
    {
        visitor.setUpdateTime(new Date());
        return visitorMapper.updateVisitor(visitor);
    }

    /**
     * 批量删除访客信息
     *
     * @param ids 需要删除的访客信息主键
     * @return 结果
     */
    @Override
    public int deleteVisitorByIds(Long[] ids)
    {
        return visitorMapper.deleteVisitorByIds(ids);
    }

    /**
     * 删除访客信息信息
     *
     * @param id 访客信息主键
     * @return 结果
     */
    @Override
    public int deleteVisitorById(Long id)
    {
        return visitorMapper.deleteVisitorById(id);
    }

    @Override
    public List<Visitor> selectVisitorItemList(Visitor visitor) {
        return visitorMapper.selectVisitorItemList(visitor);
    }

    @Override
    public int deleteVisitorItemByParentId(Long parentId) {
        return visitorMapper.deleteVisitorItemByParentId(parentId);
    }

    @Override
    public Visitor selectByGuid(String guid) {
        return visitorMapper.selectByGuid(guid);
    }

    @Override
    public Visitor selectVisitorByPhone(String phone) {
        return visitorMapper.selectVisitorByPhone(phone);
    }

    /**
     * 查询访客预约信息
     */
    @Override
    public TableDataInfoPage queryVisitorAppointment(VisitorParamVo paramVo) {
        List<Visitor> visitors = visitorMapper.queryVisitorAppointment(paramVo);
        List<Visitor> result = visitors.stream()
                .skip((long) (paramVo.getPageNum() - 1) * paramVo.getPageSize())
                .limit(paramVo.getPageSize())
                .collect(Collectors.toList());
        return new TableDataInfoPage(result, visitors.size(), paramVo.getPageNum(), result.size());
    }

    /**
     * 查询黑名单
     */
    @Override
    public TableDataInfoPage selectSysBlackListList(VisitorParamVo paramVo) {
        List<SysBlackList> sysBlackLists = sysBlackListMapper.selectSysBlackListList(new SysBlackList());
        List<SysBlackList> result = sysBlackLists.stream()
                .skip((long) (paramVo.getPageNum() - 1) * paramVo.getPageSize())
                .limit(paramVo.getPageSize())
                .collect(Collectors.toList());
        return new TableDataInfoPage(result, sysBlackLists.size(), paramVo.getPageNum(), result.size());
    }

    /**
     * 查询访客人员信息
     */
    @Override
    public PersonnelInfoVo queryPersonnelInfo(List<String> list) {
        PersonnelInfoVo sysEmpowerRecords = sysBlackListMapper.queryPersonnelInfo(list);
        List<PersonnelInfoVo> infoVos = sysBlackListMapper.queryGeneralInfo(sysEmpowerRecords.getId());
        sysEmpowerRecords.setList(infoVos);
        return sysEmpowerRecords;
    }

    /**
     * 查询被访人
     */
    @Override
    public List<PersonnelInfoVo> queryPeople(Visitor paramVo) {
        return sysBlackListMapper.queryPeople(paramVo);
    }

    /**
     * 查询已审核状态信息
     */
    @Override
    public VisitorParamVo queryAuditedVisitor(Visitor paramVo) {
        return sysBlackListMapper.queryAuditedVisitor(paramVo);
    }

    /**
     * 查询详情
     */
    @Override
    public VisitorInfoVo queryVisitorInfo(Visitor paramVo) {
        VisitorParamVo visitorParamVo = sysBlackListMapper.queryAuditedVisitor(paramVo);
        if(visitorParamVo != null) {
            checkVisitor(visitorParamVo);
        }

        VisitorInfoVo visitorInfoVo = sysBlackListMapper.queryVisitorInfo(paramVo);
        if(visitorInfoVo != null) {
            Visitor infoVo = new Visitor();
            infoVo.setId(visitorInfoVo.getId());
            visitorInfoVo.setItemList(sysBlackListMapper.queryFollowUp(infoVo));
            String s = dictDataMapper.selectDictLabel("vis_info_reason", visitorInfoVo.getMatter());
            visitorInfoVo.setMatter(s);
            visitorInfoVo.setDeptName(dictDataMapper.selectDictLabel("sys_company_type", visitorInfoVo.getDeptId()));
        }


        return visitorInfoVo;
    }

    /**
     * 修改状态
     */
    @Override
    public int updateState(Visitor paramVo) {
        VisitorParamVo visitorParamVo = sysBlackListMapper.queryAuditedVisitor(paramVo);
        if(visitorParamVo != null) {
            checkVisitor(visitorParamVo);
        }

        VisitorInfoVo visitorInfo = sysBlackListMapper.queryVisitorType(paramVo);
        if("2".equals(paramVo.getType()) && StringUtils.isEmpty(visitorInfo.getInTime())) {
            throw new ServiceException("您未签到");
        }
        if("2".equals(paramVo.getType()) && "2".equals(visitorInfo.getType())) {
            throw new ServiceException("您已经签离");
        }
        if("1".equals(paramVo.getType()) && "2".equals(visitorInfo.getType())) {
            throw new ServiceException("您已经签离");
        }

        List<VisitorInfoVo> visitorInfoVos = sysBlackListMapper.queryFollowUp(paramVo);
        // 修改同行人
        for (VisitorInfoVo visitorInfoVo : visitorInfoVos) {
            Visitor visitor = new Visitor();
            visitor.setId(visitorInfoVo.getId());
            if(Constants.ONE.equals(paramVo.getType())) {
                visitor.setInTime(new Date());
                visitor.setType("1");
            }
            if(Constants.TWO.equals(paramVo.getType())) {
                visitor.setType("2");
                visitor.setOutTime(new Date());
            }
            visitorMapper.updateVisitor(visitor);
        }
        if("1".equals(paramVo.getType())) {
            paramVo.setInTime(new Date());
        }
        if("2".equals(paramVo.getType())) {
            paramVo.setOutTime(new Date());
        }
        return visitorMapper.updateVisitorInfo(paramVo);
    }

    /**
     * 查询访客预约数
     */
    @Override
    public int queryVisitor(Visitor visitor) {
        return visitorMapper.queryVisitor(visitor);
    }

    /**
     * 访客信息
     */
    @Override
    public PersonnelInfoVo queryVisitorInfoById(String id) {
        return visitorMapper.queryVisitorInfoById(id);
    }

    /**
     * 查询未签离列表
     */
    @Override
    public List<Visitor> queryVisitorUnsigned(VisitorParamVo paramVo) {
        startPage();
        return visitorMapper.queryVisitorUnsigned(paramVo);
    }

    @Override
    public int updateSignOut(Visitor paramVo) {
        List<VisitorInfoVo> visitorInfoVos = sysBlackListMapper.queryFollowUp(paramVo);
        Visitor visitorInfo = new Visitor();
        // 修改同行人
        for (VisitorInfoVo visitorInfoVo : visitorInfoVos) {
            Visitor visitor = new Visitor();
            visitor.setId(visitorInfoVo.getId());
            if(Constants.ONE.equals(paramVo.getType())) {
                visitor.setInTime(new Date());
            }
            if(Constants.TWO.equals(paramVo.getType())) {
                visitor.setOutTime(new Date());
            }
            visitorMapper.updateVisitor(visitor);
        }
        if("1".equals(paramVo.getType())) {
            visitorInfo.setInTime(new Date());
        }
        if("2".equals(paramVo.getType())) {
            visitorInfo.setOutTime(new Date());
        }
        visitorInfo.setId(paramVo.getId());
        return visitorMapper.updateVisitor(visitorInfo);
    }

    @Override
    public void saveVisCheckCode(CheckCodeVo codeVo) {
        visitorMapper.saveVisCheckCode(codeVo);
    }

    @Override
    public CheckCodeVo queryVisCheckCodeById(String qrData) {
        return visitorMapper.queryVisCheckCodeById(qrData);
    }

    @Override
    public String queryVisCheckCode(String visitorId) {
        return visitorMapper.queryVisCheckCode(visitorId);
    }

    @Override
    public Visitor selectVisitorInfo(SysPeople people) {
        return visitorMapper.selectVisitorInfo(people);
    }

    /**
     * 查询被访人授权记录
     * @param userId
     * @return
     */
    @Override
    public List<SysManageRecord> querySysManageRecord(Long userId) {
        return visitorMapper.querySysManageRecord(userId);
    }

    /**
     * 保存访客guid
     */
    @Override
    public void updateVisitorInfoGuid(List<Visitor> listVisitorId) {
        visitorMapper.updateVisitorInfoGuid(listVisitorId);
    }

    @Override
    public Visitor queryVisitorGuid(String guid) {
        return visitorMapper.queryVisitorGuid(guid);
    }

    /**
     * 查询是否进入
     * @param id
     */
    @Override
    public int queryVisitorRecord(Long id) {
        return visitorMapper.queryVisitorRecord(id);
    }

    /**
     * 更新离开时间
     * @param record
     */
    @Override
    public void updateVisitorRecord(VisitorRecordVo record) {
        visitorMapper.updateVisitorRecord(record);
    }

    /**
     * 新增访客识别记录
     * @param record
     */
    @Override
    public void saveVisitorRecord(VisitorRecordVo record) {
        visitorMapper.saveVisitorRecord(record);
    }

    /**
     * 查询访客记录列表
     * @param visitor
     * @return
     */
    @Override
    public List<VisitorRecordVo> queryVisitorRecordList(VisitorRecordVo visitor) {
        return visitorMapper.queryVisitorRecordList(visitor);
    }

    /**
     * 删除访客记录
     * @param ids
     */
    @Override
    public void deleteVisitorRecordList(Long[] ids) {
        visitorMapper.deleteVisitorRecordList(ids);
    }

    @Override
    public List<SysBranch> querySysBranch() {
        return visitorMapper.querySysBranch();
    }

    /**
     * 查询访客数量（今日，本周，本月）
     * @param recordVo
     * @return
     */
    @Override
    public VisitorCountVo queryVisitorCount(VisitorRecordVo recordVo) {
        VisitorCountVo visitorCountVo = new VisitorCountVo();
        recordVo.setType(systemType);
        int dayCount = visitorMapper.queryVisitorDayCount(recordVo);
        int weekCount = visitorMapper.queryVisitorWeekCount(recordVo);
        int monthCount = visitorMapper.queryVisitorMonthCount(recordVo);
        visitorCountVo.setDayCount(dayCount);
        visitorCountVo.setWeekCount(weekCount);
        visitorCountVo.setMonthCount(monthCount);
        return visitorCountVo;
    }

    /**
     * 首页头像展示
     * @param recordVo
     * @return
     */
    @Override
    public List<VisitorRecordVo> queryVisitorAvatar(VisitorRecordVo recordVo) {
        return visitorMapper.queryVisitorAvatar(recordVo);
    }



    /**
     * 访客校验
     */
    private void checkVisitor(VisitorParamVo visitorParamVo) {
//        if(visitorParamVo == null) {
//            throw new ServiceException("未查询到预约信息");
//        }
        if(Constants.ZERO.equals(visitorParamVo.getReviewStatus())) {
            throw new ServiceException("您未审核");
        }
        if(Constants.TWO.equals(visitorParamVo.getReviewStatus())) {
            throw new ServiceException("您审核未通过");
        }

        if(visitorParamVo.getEndTime().getTime() < new Date().getTime()) {
            throw new ServiceException("您得预约时间已超时");
        }

    }

    @Override
    public Visitor addHkVis(Visitor visitor) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v2/person/single/add";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personName", visitor.getName());
        if(com.dcsoft.common.core.utils.StringUtils.isEmpty(visitor.getSex())){
            visitor.setSex("0");
        }
        paramMaps.put("gender", visitor.getSex());
        paramMaps.put("orgIndexCode","bfd4f1be-7458-46fb-ba18-3add8e3663a3" );//访客部门
        paramMaps.put("phoneNo", visitor.getPhone());
        paramMaps.put("certificateNo", visitor.getIdcard());
        paramMaps.put("jobNo", visitor.getPhone());
        if(com.dcsoft.common.core.utils.StringUtils.isNotEmpty(visitor.getAvatar())){
            String base64= ImageToBase64Utils.getImgUrlToBase64(visitor.getAvatar());
            JSONArray faces=new JSONArray();
            Map<String, Object> face = new HashMap<String, Object>();
            face.put("faceData", base64);
            faces.add(face);
            paramMaps.put("faces", faces );
        }
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        String personId= (String) jsons1.get("personId");
        String faceId= (String) jsons1.get("faceId");
        visitor.setGuid(personId);
        visitor.setFaceGuid(faceId);
        visitorMapper.updateVisitor(visitor);
        return visitor;

    }

    @Override
    public Visitor addHkCar(Visitor visitor) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/vehicle/batch/add";
        JSONArray array=new JSONArray();

        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("clientId", 1);
        paramMaps.put("plateNo", visitor.getCarNo());
        paramMaps.put("personId", visitor.getGuid());
        array.add(paramMaps);
        String body = JSON.toJSON(array).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return visitor;
    }

    @Override
    public int delHkvisitor(String admitGuids) {
        String[] guids=admitGuids.split(",");
        int i=guids.length;
        JSONArray personIds=new JSONArray();
        for(String s:guids){
            personIds.add(s);
        }
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/person/batch/delete";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personIds", personIds);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return i;
    }

    @Override
    public int personHkDelete(String admitGuid) {
        int i=1;
        JSONArray personIds=new JSONArray();
        personIds.add(admitGuid);
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/person/batch/delete";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personIds", personIds);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return i;
    }

    @Override
    public int delHkCarVisitor(String carNo) {
        String vehicleId=findvehicleInfo(carNo);

        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/vehicle/batch/delete";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray vehicleIds=new JSONArray();
        vehicleIds.add(vehicleId);
        paramMaps.put("vehicleIds", vehicleIds);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return vehicleIds.size();
    }

    private String findvehicleInfo(String carNo) {
        String  vehicleId = null;
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/vehicle/plateNo/vehicleInfo";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("plateNo", carNo);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        System.out.println("海康车辆获取情况====="+jsons);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        vehicleId= (String) jsons1.get("vehicleId");

        return  vehicleId;
    }


}
