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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.datascope.annotation.DataScope;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.consume.domain.ConsumePeopleDay;
import com.dcsoft.system.consume.mapper.ConsumePeopleDayMapper;
import com.dcsoft.system.consume.service.IConsumePeopleDayService;
import com.dcsoft.system.domain.HkPeopleRecord;
import com.dcsoft.system.domain.SysPeople;
import com.dcsoft.system.mapper.HkPeopleRecordMapper;
import com.dcsoft.system.mapper.SysPeopleMapper;
import com.dcsoft.system.visitor.domain.Visitor;
import com.dcsoft.system.visitor.domain.VisitorRecordVo;
import com.dcsoft.system.visitor.mapper.VisitorMapper;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * 人员餐补信息Service业务层处理
 *
 * @author dcsoft
 * @date 2024-09-20
 */
@Service
public class ConsumePeopleDayServiceImpl implements IConsumePeopleDayService
{
    @Autowired
    private ConsumePeopleDayMapper consumePeopleDayMapper;

    @Autowired
    private HkPeopleRecordMapper hkPeopleRecordMapper;

    @Autowired
    private SysPeopleMapper sysPeopleMapper;

    @Autowired
    private VisitorMapper visitorMapper;


    @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 ConsumePeopleDay selectConsumePeopleDayById(Long id)
    {
        return consumePeopleDayMapper.selectConsumePeopleDayById(id);
    }

    @Override
    public ConsumePeopleDay selectConsumePeopleDayByRecordId(String recordId) {
        return consumePeopleDayMapper.selectConsumePeopleDayByRecordId(recordId);
    }

    /**
     * 查询人员餐补信息列表
     *
     * @param consumePeopleDay 人员餐补信息
     * @return 人员餐补信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<ConsumePeopleDay> selectConsumePeopleDayList(ConsumePeopleDay consumePeopleDay)
    {
        return consumePeopleDayMapper.selectConsumePeopleDayList(consumePeopleDay);
    }

    /**
     * 新增人员餐补信息
     *
     * @param consumePeopleDay 人员餐补信息
     * @return 结果
     */
    @Override
    public int insertConsumePeopleDay(ConsumePeopleDay consumePeopleDay)
    {
        consumePeopleDay.setCreateTime(DateUtils.getNowDate());
        return consumePeopleDayMapper.insertConsumePeopleDay(consumePeopleDay);
    }

    /**
     * 修改人员餐补信息
     *
     * @param consumePeopleDay 人员餐补信息
     * @return 结果
     */
    @Override
    public int updateConsumePeopleDay(ConsumePeopleDay consumePeopleDay)
    {
        consumePeopleDay.setUpdateTime(DateUtils.getNowDate());
        return consumePeopleDayMapper.updateConsumePeopleDay(consumePeopleDay);
    }

    /**
     * 批量删除人员餐补信息
     *
     * @param ids 需要删除的人员餐补信息主键
     * @return 结果
     */
    @Override
    public int deleteConsumePeopleDayByIds(Long[] ids)
    {
        return consumePeopleDayMapper.deleteConsumePeopleDayByIds(ids);
    }

    /**
     * 删除人员餐补信息信息
     *
     * @param id 人员餐补信息主键
     * @return 结果
     */
    @Override
    public int deleteConsumePeopleDayById(Long id)
    {
        return consumePeopleDayMapper.deleteConsumePeopleDayById(id);
    }

    @Override
    public JSONObject queryPeopleDay(Map<String, Object> paramMap) {
        JSONObject obj=new JSONObject();
        ConsumePeopleDay consumePeopleDay=new ConsumePeopleDay();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf1.parse(paramMap.get("recordDateTime")+"");
            consumePeopleDay.setConsumeTime(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        consumePeopleDay.setEmpId(paramMap.get("code")+"");
        consumePeopleDay.setConsumeInterval(paramMap.get("consumeInterval")+"");
        List<ConsumePeopleDay> list=consumePeopleDayMapper.selectConsumePeopleDayList(consumePeopleDay);
        if(list.size()>0){
            ConsumePeopleDay consumePeople=list.get(0);
            if("1".equals(consumePeople.getIsConsume())){
                obj.put("code","2");
                obj.put("msg",consumePeople.getAccountName()+"重复就餐");
                return obj;
            }else{
                obj.put("code","0");
                obj.put("msg",consumePeople.getAccountName()+"核验通过");
                consumePeople.setIsConsume("1");
                consumePeople.setUpdateTime(new Date());
                consumePeopleDayMapper.updateConsumePeopleDay(consumePeople);
                return obj;
            }
        }else{
            obj.put("code","1");
            obj.put("msg","未报餐");
        }
        return obj;
    }

    @Override
    public int syncHkRecord(ConsumePeopleDay consumePeopleDay) {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        String date=sdf.format(consumePeopleDay.getConsumeTime());
        int totalPage=syncHkRecordAll(1,date);
        for(int pageNo=2;pageNo<=totalPage;pageNo++){
            syncHkRecordAll(pageNo,date);
        }
        int totalPageCar=syncHkRecordAllCar(1,date);
        for(int pageNo1=2;pageNo1<=totalPageCar;pageNo1++){
            syncHkRecordAllCar(pageNo1,date);
        }
        //夜餐人员进行最后离开时间更新
        queryPeopleNight(consumePeopleDay);
        return totalPage;
    }

    private void queryPeopleNight(ConsumePeopleDay consumePeopleDay) {
        consumePeopleDay.setConsumeInterval("3");
        List<ConsumePeopleDay> list=consumePeopleDayMapper.selectConsumePeopleDayList(consumePeopleDay);
        for(ConsumePeopleDay day:list){
            HkPeopleRecord people=new HkPeopleRecord();
            people.setEmployeeNo(day.getGuid());
            people.setDateTime(consumePeopleDay.getConsumeTime());
            List<HkPeopleRecord> list1=hkPeopleRecordMapper.selectHkPeopleRecordList(people);
            if(list1.size()>0){
                HkPeopleRecord record=list1.get(0);
                if(record.getDateTime().getTime()>day.getCreateTime().getTime()){
                    day.setLeaveTime(record.getDateTime());
                    consumePeopleDayMapper.updateConsumePeopleDay(day);
                }

            }
        }

    }

    private int syncHkRecordAll(int pageNo,String date) {
        int i=0;
        ArtemisConfig config = new ArtemisConfig();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/acs/v2/door/events";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray eventTypes=new JSONArray();
        paramMaps.put("pageNo",pageNo);
        paramMaps.put("pageSize",100);
        eventTypes.add(196893);
        paramMaps.put("eventTypes",eventTypes);
        paramMaps.put("startTime",date+"T00:00:00+08:00");
        paramMaps.put("endTime",date+"T23:59:59+08:00");
        paramMaps.put("order","asc");
        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");
        i= (int) jsons1.get("totalPage");
        JSONArray list= (JSONArray) jsons1.get("list");
        for(Object obj:list){
            JSONObject objs= (JSONObject)obj;
            if (!"null".equals(objs.get("personName")+"")){
                //如果是访客部门的数据放置在访客上
                SysPeople sysPeople=sysPeopleMapper.selectSysPeopleByGh(objs.get("jobNo")+"");
                HkPeopleRecord people=new HkPeopleRecord();
                people.setEventId(objs.get("eventId")+"");
                try {
                    people.setDateTime(sdf.parse(objs.get("eventTime")+""));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                if(sysPeople!=null){
                    people.setEmployeeNo(objs.get("personId")+"");
                    people.setGh(objs.get("jobNo")+"");
                    people.setPeopleName(objs.get("personName")+"");
                    people.setCardNo(objs.get("cardNo")+"");
                    people.setDeviceSerial(objs.get("devIndexCode")+"");
                    people.setDeviceName(objs.get("devName")+"");
                    people.setEventCode("10114");
                    hkPeopleRecordMapper.insertHkPeopleRecord(people);
                }else{
                    Visitor visitor=visitorMapper.selectByGuid(objs.get("personId")+"");
                    if(visitor!=null){
                        VisitorRecordVo recordVo=new VisitorRecordVo();
                        recordVo.setVisitorId(visitor.getId()+"");
                        recordVo.setStartTimeTxt(sdf1.format(people.getDateTime()));
                        List<VisitorRecordVo>  list1=visitorMapper.queryVisitorRecordList(recordVo);
                        if (list1.size()>0) {
                            recordVo.setId(list1.get(0).getId());
                            visitor.setEndTime(people.getDateTime());
                            visitorMapper.updateVisitorRecord(recordVo);
                        }
                        visitor.setStartTime(people.getDateTime());
                        visitorMapper.saveVisitorRecord(recordVo);
                        visitorMapper.updateVisitor(visitor);
                    }
                }
            }
        }
        return i;
    }

    private int syncHkRecordAllCar(int pageNo,String date) {
        int i=0;
        ArtemisConfig config = new ArtemisConfig();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/pms/v1/crossRecords/page";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray eventTypes=new JSONArray();
        paramMaps.put("pageNo",pageNo);
        paramMaps.put("pageSize",100);
        paramMaps.put("eventTypes",eventTypes);
        paramMaps.put("startTime",date+"T00:00:00.839+08:00");
        paramMaps.put("endTime",date+"T23:59:59.839+08:00");
        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");
        i= (int) jsons1.get("total");
        i=i/100;
        JSONArray list= (JSONArray) jsons1.get("list");
        for(Object obj:list){
            JSONObject objs= (JSONObject)obj;
                HkPeopleRecord people=new HkPeopleRecord();
                people.setEventId(objs.get("eventId")+"");
                try {
                    people.setDateTime(sdf.parse(objs.get("crossTime")+""));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                SysPeople peoples=sysPeopleMapper.queryPeopleByCarNo(objs.get("plateNo")+"");
                if(peoples!=null){
                    people.setEmployeeNo(peoples.getGuid());
                    people.setEventCode("1157632001");
                    people.setRemark(objs.get("plateNo")+"");
                    hkPeopleRecordMapper.insertHkPeopleRecord(people);
                }else{
                    Visitor visitor=visitorMapper.selectVisitorByCarNo(objs.get("plateNo")+"");
                    if(visitor!=null){
                 /*       people.setEmployeeNo(visitor.getGuid());
                        people.setEventCode("1157632001");
                        people.setRemark("访客"+visitor.getName()+objs.get("plateNo")+"");
                        hkPeopleRecordMapper.insertHkPeopleRecord(people);
                        */
                        VisitorRecordVo recordVo=new VisitorRecordVo();
                        recordVo.setVisitorId(visitor.getId()+"");
                        recordVo.setStartTimeTxt(sdf1.format(people.getDateTime()));
                        List<VisitorRecordVo>  list1=visitorMapper.queryVisitorRecordList(recordVo);
                        if (list1.size()>0) {
                            recordVo.setId(list1.get(0).getId());
                            visitor.setEndTime(people.getDateTime());
                            visitorMapper.updateVisitorRecord(recordVo);
                        }
                        visitor.setStartTime(people.getDateTime());
                        visitorMapper.saveVisitorRecord(recordVo);
                        visitorMapper.updateVisitor(visitor);
                    }


                }
        }
        return i;
    }

}
