/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dm.dmVisitorsUser.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dm.dmVisitorsApply.domain.DmVisitorsApply;
import me.zhengjie.modules.dm.dmVisitorsUser.domain.DmVisitorsUser;
import me.zhengjie.modules.dmParkingTraffic.domain.DmParkingTraffic;
import me.zhengjie.modules.dmParkingTraffic.service.DmParkingTrafficService;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.dmVisitorsUser.repository.DmVisitorsUserRepository;
import me.zhengjie.modules.dm.dmVisitorsUser.service.DmVisitorsUserService;
import me.zhengjie.modules.dm.dmVisitorsUser.service.dto.DmVisitorsUserDto;
import me.zhengjie.modules.dm.dmVisitorsUser.service.dto.DmVisitorsUserQueryCriteria;
import me.zhengjie.modules.dm.dmVisitorsUser.service.mapstruct.DmVisitorsUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author juan
* @date 2021-11-19
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class DmVisitorsUserServiceImpl implements DmVisitorsUserService {

    private final DmVisitorsUserRepository dmVisitorsUserRepository;
    private final DmVisitorsUserMapper dmVisitorsUserMapper;
    private final UserService userService;
    private final DmParkingTrafficService dmParkingTrafficService;

    @Override
    public Map<String,Object> queryAll(DmVisitorsUserQueryCriteria criteria, Pageable pageable){
        Page<DmVisitorsUser> page = dmVisitorsUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmVisitorsUserMapper::toDto));
    }

    @Override
    public List<DmVisitorsUserDto> queryAll(DmVisitorsUserQueryCriteria criteria){
        return dmVisitorsUserMapper.toDto(dmVisitorsUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmVisitorsUserDto findById(Long visitorId) {
        DmVisitorsUser dmVisitorsUser = dmVisitorsUserRepository.findById(visitorId).orElseGet(DmVisitorsUser::new);
        ValidationUtil.isNull(dmVisitorsUser.getVisitorId(),"DmVisitorsUser","visitorId",visitorId);
        return dmVisitorsUserMapper.toDto(dmVisitorsUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmVisitorsUserDto create(DmVisitorsUser resources) {
        return dmVisitorsUserMapper.toDto(dmVisitorsUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAll(List<DmVisitorsUser> resources) {
        if(!ObjectUtils.isEmpty(resources)){
            for(DmVisitorsUser dmVisitorsUser : resources){
                dmVisitorsUserRepository.save(dmVisitorsUser);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmVisitorsUser resources) {
        DmVisitorsUser dmVisitorsUser = dmVisitorsUserRepository.findById(resources.getVisitorId()).orElseGet(DmVisitorsUser::new);
        ValidationUtil.isNull( dmVisitorsUser.getVisitorId(),"DmVisitorsUser","id",resources.getVisitorId());
        dmVisitorsUser.copy(resources);
        dmVisitorsUserRepository.save(dmVisitorsUser);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long visitorId : ids) {
            dmVisitorsUserRepository.deleteById(visitorId);
        }
    }

    @Override
    public void download(List<DmVisitorsUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmVisitorsUserDto dmVisitorsUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("访客姓名", dmVisitorsUser.getVisitorName());
            map.put("访客电话", dmVisitorsUser.getVisitorPhone());
            map.put("部门", dmVisitorsUser.getDeptId());
            map.put("车牌", dmVisitorsUser.getPlateNumber());
            map.put("访客申请id", dmVisitorsUser.getVisitorsApply().getId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void vehicleAccessTraffic(JSONObject json) throws ParseException {
        Integer vehicleOut = json.getInteger("vehicle_out");
        log.info("vehicleOut:"+vehicleOut);
        Integer releaseResult = json.getInteger("release_result");
        log.info("releaseResult:"+releaseResult);
        String plateNo = json.getString("plate_no");
        log.info("plateNo:"+plateNo);
        String crossTime = json.getString("cross_time");
        log.info("crossTime:"+crossTime);

        DmParkingTraffic dmParkingTraffic = new DmParkingTraffic();
        dmParkingTraffic.setParkCode(json.getString("park_code"));
        dmParkingTraffic.setEntranceCode(json.getString("entrance_code"));
        dmParkingTraffic.setEntranceName(json.getString("entrance_name"));
        dmParkingTraffic.setRoadwayCode(json.getString("roadway_code"));
        dmParkingTraffic.setRoadwayName(json.getString("roadway_name"));
        dmParkingTraffic.setPlateNo(json.getString("plate_no"));
        dmParkingTraffic.setPlateColor(json.getString("plate_color"));
        dmParkingTraffic.setVehicleOut(json.getInteger("vehicle_out"));
        dmParkingTraffic.setVehicleColor(json.getInteger("vehicle_color"));
        dmParkingTraffic.setVehicleType(json.getInteger("vehicle_type"));
        dmParkingTraffic.setReleaseWay(json.getInteger("release_way"));
        dmParkingTraffic.setReleaseResult(json.getInteger("release_result"));
        dmParkingTraffic.setReleaseRemark(json.getString("release_remark"));
        dmParkingTraffic.setCrossTime(json.getTimestamp("cross_time"));
        dmParkingTrafficService.create(dmParkingTraffic);

        if(releaseResult != 0 ) {
            if (vehicleOut == 0) {
                SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = dtf.parse(crossTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                //获取日期中得年
                Integer year= cal.get(Calendar.YEAR);
                System.out.println("year:"+year);
                //获取日期中得月
                Integer month= (cal.get(Calendar.MONTH) + 1);
                System.out.println("month:"+month);
                //获取日期中得日
                Integer day= Integer.valueOf(String.format("%td", date));
                List<DmVisitorsUser> dmVisitorsUserList = dmVisitorsUserRepository.getDmVisitorsUserByPlateNumber(plateNo,year,month,day);
                if(!ObjectUtils.isEmpty(dmVisitorsUserList)){
                    for(DmVisitorsUser dmVisitorsUser : dmVisitorsUserList){
                        DmVisitorsApply dmVisitorsApply = dmVisitorsUser.getVisitorsApply();
                        DmUser dmUser = dmVisitorsApply.getDmUser();
                        UserDto user = userService.findById(dmUser.getId());
                        Map<String,Object> token = SecurityUtils.getToken("DMERPYT!@#$QWER2021+{:>");
                        JSONObject query = new JSONObject();
                        query.put("systemName","一卡通系统");
                        query.put("sendId","dm_visitors_user|plate_number|"+plateNo);
                        query.put("sendUserId",dmUser.getId());
                        JSONObject sendContentJSON = new JSONObject();
                        sendContentJSON.put("text","访客"+dmVisitorsUser.getVisitorName()+"的车辆已进入停车场，请您做好接待准备。");
                        query.put("sendContent",sendContentJSON);
                        query.put("usernames",user.getUsername());
                        JSONObject param = new JSONObject();
                        param.put("nonce",token.get("nonce"));
                        param.put("timestamp",token.get("timestamp"));
                        param.put("query",query);
                        HttpRequest.get("https://smartpark.caih.com/zkxt/api/thirdparty/v1/message/sendChatMessage")
                                .header("XYTACCESSTOKEN", token.get("token").toString())
                                .body(param.toJSONString()).execute().body();
                    }
                }
            } else if (vehicleOut == 1) {

            }
        }
    }

    @Override
    public List<DmVisitorsUser> findByApplyId(Long visitorsApplyId) {
        return dmVisitorsUserRepository.findByApplyId(visitorsApplyId);
    }

}