/*
*  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.dmVisitorsApply.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dm.dmLane.service.DmLaneService;
import me.zhengjie.modules.dm.dmLane.service.dto.DmLaneDto;
import me.zhengjie.modules.dm.dmLane.service.dto.DmLaneQueryCriteria;
import me.zhengjie.modules.dm.dmVisitorsApply.domain.DmVisitorsApply;
import me.zhengjie.modules.dm.dmVisitorsApply.service.dto.DmVisXq;
import me.zhengjie.modules.dm.dmVisitorsApply.service.dto.DmVisitorsDto;
import me.zhengjie.modules.dm.dmVisitorsUser.domain.DmVisitorsUser;
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.dmConsumeDevices.domain.DmConsumeDevices;
import me.zhengjie.modules.dmuser.service.mapstruct.DmUserMapper;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
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.dmVisitorsApply.repository.DmVisitorsApplyRepository;
import me.zhengjie.modules.dm.dmVisitorsApply.service.DmVisitorsApplyService;
import me.zhengjie.modules.dm.dmVisitorsApply.service.dto.DmVisitorsApplyDto;
import me.zhengjie.modules.dm.dmVisitorsApply.service.dto.DmVisitorsApplyQueryCriteria;
import me.zhengjie.modules.dm.dmVisitorsApply.service.mapstruct.DmVisitorsApplyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author juan
* @date 2021-11-19
**/
@Service
@RequiredArgsConstructor
public class DmVisitorsApplyServiceImpl implements DmVisitorsApplyService {
    @Value("${mfUrl}")
    private String mfUrl;
    @Value("${erCodeUrl}")
    private String erCodeUrl;
    private final UserService userService;
    private final DmUserMapper dmUserMapper;
    private final DmVisitorsApplyRepository dmVisitorsApplyRepository;
    private final DmVisitorsApplyMapper dmVisitorsApplyMapper;
    private final DmVisitorsUserRepository dmVisitorsUserRepository;
    private final DmLaneService dmLaneService;
    private final UserRepository userRepository;
    @PersistenceContext
    private EntityManager em;

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

//    @Override
//    public JSONArray getVisApp(String userNumber,Pageable pageable) {
//        List<Map<String,String>> mapList = dmVisitorsApplyRepository.getVisApp(userNumber, pageable);
//        List<Map<String,String>> newMapList = new ArrayList<>(mapList);
//        JSONArray array = new JSONArray();
//        for(Map<String,String> map : newMapList){
//            JSONObject object = new JSONObject();
//            object.put("id",String.valueOf(map.get("id")));
//            object.put("start_time",map.get("start_time"));
//            object.put("for_visiting",map.get("for_visiting"));
//            object.put("approve_state",map.get("approve_state"));
//            array.add(object);
//        }
//        return array;
//    }

    @Override
    public JSONArray getVisApp(String userNumber,Pageable pageable) {
        List<Map<String,String>> mapList = dmVisitorsApplyRepository.getVisApp(userNumber, pageable);
        List<Map<String,String>> newMapList = new ArrayList<>(mapList);
        JSONArray array = new JSONArray();
        for(Map<String,String> map : newMapList){
            JSONObject object = new JSONObject();
            object.put("id",String.valueOf(map.get("id")));
            object.put("start_time",map.get("start_time"));
            object.put("for_visiting",map.get("for_visiting"));
            object.put("visitor_name",map.get("visitor_name"));
            array.add(object);
        }
        return array;
    }
    @Override
    public JSONArray getVisitantApp(String userNumber,Pageable pageable) {
        List<Map<String,String>> mapList = dmVisitorsApplyRepository.getVisitantApp(userNumber, pageable);
        List<Map<String,String>> newMapList = new ArrayList<>(mapList);
        JSONArray array = new JSONArray();
        for(Map<String,String> map : newMapList){
            JSONObject object = new JSONObject();
            object.put("id",String.valueOf(map.get("id")));
            object.put("start_time",map.get("start_time"));
            object.put("for_visiting",map.get("for_visiting"));
            object.put("visitor_name",map.get("visitor_name"));
            array.add(object);
        }
        return array;
    }
    @Override
    public Map<String, Object> getVisApp2(String userNumber, Pageable pageable) {
        //sql参数
        Map<String,Object> queryParams = new HashMap<>();
        //拼接sql
        StringBuffer querySql = new StringBuffer();//查询sql
        querySql.append(
                " SELECT id,start_time as startTime,for_visiting as forVisiting,approve_state as approveState "
        );
        String columns = "id,startTime,forVisiting,approveState";

        StringBuffer countSql = new StringBuffer();
        countSql.append("select count(*) ");

        StringBuffer baseSql = new StringBuffer();
        baseSql.append(
                " FROM dm_visitors_apply WHERE type = '00' AND (user_number = :userId OR request_user = :userId) ORDER BY start_time DESC ");
        queryParams.put("userId",userNumber);

        querySql.append(baseSql);
        countSql.append(baseSql);
        Query query = em.createNativeQuery(querySql.toString());
        Query countQuery = em.createNativeQuery(countSql.toString());

        for (Map.Entry<String,Object> entry : queryParams.entrySet()) {
            query.setParameter(entry.getKey(),entry.getValue());
            countQuery.setParameter(entry.getKey(),entry.getValue());
        }
        BigInteger total = (BigInteger) countQuery.getSingleResult();
        //设置分页
        Integer offset = (int)pageable.getOffset();
        Integer pageSize = pageable.getPageSize();
        if(offset != null && pageSize != null){
            query.setFirstResult(offset);
            query.setMaxResults(pageSize);
        }
        List<Object[]> list = query.getResultList();
        List<Map<String,String>> result = queryResultToMap(list,columns);
        Page<Map<String,String>> page = new PageImpl<>(result,pageable,total.longValue());
        return PageUtil.toPage(page);
    }

    @Override
    public Map<String, Object> getVisitorVisitList(String phone, Pageable pageable) {
        //sql参数
        Map<String,Object> queryParams = new HashMap<>();
        //拼接sql
        StringBuffer querySql = new StringBuffer();//查询sql
        querySql.append(
                " SELECT id,start_time as startTime,for_visiting as forVisiting,approve_state as approveState "
        );
        String columns = "id,startTime,forVisiting,approveState";

        StringBuffer countSql = new StringBuffer();
        countSql.append("select count(*) ");

        StringBuffer baseSql = new StringBuffer();
        baseSql.append(
                " FROM dm_visitors_apply as va LEFT JOIN dm_visitors_user vu ON va.id = vu.apply_id WHERE va.type = '00' AND vu.visitor_phone = :phone ORDER BY va.start_time DESC ");
        queryParams.put("phone",phone);

        querySql.append(baseSql);
        countSql.append(baseSql);
        Query query = em.createNativeQuery(querySql.toString());
        Query countQuery = em.createNativeQuery(countSql.toString());

        for (Map.Entry<String,Object> entry : queryParams.entrySet()) {
            query.setParameter(entry.getKey(),entry.getValue());
            countQuery.setParameter(entry.getKey(),entry.getValue());
        }
        BigInteger total = (BigInteger) countQuery.getSingleResult();
        //设置分页
        Integer offset = (int)pageable.getOffset();
        Integer pageSize = pageable.getPageSize();
        if(offset != null && pageSize != null){
            query.setFirstResult(offset);
            query.setMaxResults(pageSize);
        }
        List<Object[]> list = query.getResultList();
        List<Map<String,String>> result = queryResultToMap(list,columns);
        Page<Map<String,String>> page = new PageImpl<>(result,pageable,total.longValue());
        return PageUtil.toPage(page);
    }

    /**
     * query查询结果转换为Map对象集合
     * @param queryResult
     * @param columns 字段名称,要与返回的Object数组个数对上
     * @return
     */
    public static List<Map<String,String>> queryResultToMap(List<Object[]> queryResult,String columns){
        List<Map<String,String>> mapList = new ArrayList<>();
        String[] col_arr = columns.split(",");
        for(Object[] arr : queryResult){
            Map<String,String> map = new HashMap<>();
            for(int i = 0; i < arr.length; i++){
                map.put(col_arr[i],String.valueOf(arr[i]));
            }
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public List<DmVisitorsApplyDto> queryAll(DmVisitorsApplyQueryCriteria criteria){
        return dmVisitorsApplyMapper.toDto(dmVisitorsApplyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<DmVisitorsApplyDto> queryAllXq(DmVisitorsApplyQueryCriteria criteria){

        return dmVisitorsApplyMapper.toDto(dmVisitorsApplyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmVisitorsApplyDto findById(Long id) {
        DmVisitorsApply dmVisitorsApply = dmVisitorsApplyRepository.findById(id).orElseGet(DmVisitorsApply::new);
        ValidationUtil.isNull(dmVisitorsApply.getId(),"DmVisitorsApply","id",id);
        return dmVisitorsApplyMapper.toDto(dmVisitorsApply);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmVisitorsApplyDto create(DmVisitorsDto resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        UserDto user= userService.findById(SecurityUtils.getCurrentUserId());
        Map body  = new HashMap();
        body.put("visitorName",resources.getVisotors().get(0).getVisitorName());
        body.put("visitorPhone",resources.getVisotors().get(0).getVisitorPhone());
        body.put("startTime",resources.getStartTime());
        body.put("endTime",resources.getEndTime());
        body.put("reason",resources.getForVisiting());
        body.put("greeterName",resources.getDmUser().getName());
        body.put("greeterPhone",resources.getDmUser().getContacts());
        body.put("cardType",0);
        body.put("cardNum",null);
        body.put("depId",resources.getDept().getId());
        body.put("depName",resources.getDept().getName());
        body.put("gender",null);
        body.put("companyName",null);
        body.put("visitorNum",Integer.valueOf(resources.getVisNumber()));
        body.put("belongings",null);
        body.put("carNum",null);
        body.put("note",null);
        System.out.println("body:"+ JSONUtils.toJSONString(body));
        String res = HttpRequest.post(erCodeUrl).form(body).execute().body();
        JSONObject json = JSONObject.parseObject(res);
        String qrCode = json.getString("qrCode");
        if(StringUtils.isNotBlank(qrCode)) {
            DmVisitorsApply dmVisitorsApply = new DmVisitorsApply();
            dmVisitorsApply.setId(snowflake.nextId());
            dmVisitorsApply.setDmUser(resources.getDmUser());
            dmVisitorsApply.setDept(resources.getDept());
            dmVisitorsApply.setStartTime(resources.getStartTime());
            dmVisitorsApply.setEndTime(resources.getEndTime());
            dmVisitorsApply.setAdministration(resources.getAdministration());
            dmVisitorsApply.setVisNumber(resources.getVisNumber());
            dmVisitorsApply.setForVisiting(resources.getForVisiting());
            dmVisitorsApply.setType("01");
            dmVisitorsApply.setRequestUser(dmUserMapper.toEntity(user.getDmUser()));
            dmVisitorsApply.setQrCode(qrCode);
            dmVisitorsApply.setApplyStatus(0);
            dmVisitorsApplyRepository.save(dmVisitorsApply);

            for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()) {
                DmVisitorsUser visitorsUser = new DmVisitorsUser();
                visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                visitorsUser.setVisitorsApply(dmVisitorsApply);
                dmVisitorsUserRepository.save(visitorsUser);
                //车牌登记
//                String url = "http://10.208.128.14:9999/api/park/addfreecar";
                JSONObject generateProcJson = new JSONObject();
                generateProcJson.put("name",dmVisitorsUser.getVisitorName());
                generateProcJson.put("phone",dmVisitorsUser.getVisitorPhone());
                generateProcJson.put("carplate",dmVisitorsUser.getPlateNumber());
                SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
                generateProcJson.put("startdate",formater2.format(resources.getStartTime()));
                generateProcJson.put("enddate",formater2.format(resources.getEndTime()));
                generateProcJson.put("cardtype","A");
                List<DmLaneDto> list = dmLaneService.queryAll(new DmLaneQueryCriteria());
                List<Integer> sb = new ArrayList<>();
                for (DmLaneDto dmLaneDto : list){
                    sb.add(dmLaneDto.getId());
                }
                generateProcJson.put("controllers", Joiner.on(",").join(sb));
                String generateProcData = BeanMapUtils.doPostForm(mfUrl,generateProcJson);
                JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
                System.out.println("add免费车:"+generateProcDataJson);
            }
            if(StringUtils.equals(resources.getDmUser().getUsertype(),"01")){
                sendTemplate(resources);
            }
        } else {
            throw new BadRequestException("获取二维码信息时失败！");
        }

        return null;
    }

    /**
     * 发送公众号模板信息
     * @param resources  访客信息
     */
    public void sendTemplate(DmVisitorsDto resources){
        String msgUrl = "https://smartpark.caih.com/zkxt/api/thirdparty/v1/message/sendMsg";
        JSONObject param = new JSONObject();
        param.put("userId",resources.getDmUser().getId());
        param.put("data",getMessageData(resources));
        param.put("templateId","FkQaiUdUEdlh5ZF819rvxsFngtnxncgECtGo2bUc7Ag");
        Map<String,Object> token = SecurityUtils.getToken("DMERPYT!@#$QWER2021+{:>");
        param.put("detailUrl","https://smartpark.caih.com/h5/#/visitorDetail?id="+resources.getId()+"&token="+token.get("token")+"&nonce="+token.get("nonce")+"&timestamp="+token.get("timestamp"));
        HttpRequest.get(msgUrl).header("XYTACCESSTOKEN", token.get("token").toString()).body(param.toJSONString()).execute().body();
    }

    public Map<String,Object> getMessageData(DmVisitorsDto resources){
        Map<String, Object> map = new HashMap<>();
        map.put("first",getMap("恭喜您申请成功，请通知您的访客，同事系统会以短信的方式通知访客。",null));
        map.put("keyword1",getMap(resources.getVisitorName(),null));
        map.put("keyword2",getMap("成功",null));
        map.put("keyword3",getMap(resources.getForVisiting(),null));
        map.put("keyword4",getMap(DateUtil.parseTimestampFormatyMdHms(resources.getStartTime()),null));
        map.put("keyword5",getMap(DateUtil.parseTimestampFormatyMdHms(resources.getEndTime()),null));
        map.put("remark",getMap("如有疑问，请及时在线联系我们的客服！",null));
        return map;
    }

    public Map<String,Object> getMap(Object value,String color){
        Map<String,Object> map = new HashMap<>();
        map.put("value",value);
        map.put("color",color);
        return map;
    }

    @Override
    public List<DmVisXq> getVisitors (Long userNumber) {
//        Page<DmVisitorsDto> page = dmVisitorsApplyRepository.getVisitors(userNumber);
        return dmVisitorsApplyRepository.getVisitors(userNumber);
    }

    //@Override
    public String visitorsApplyAdd2(DmVisitorsDto resources){
        Boolean isPlateNumber = false;
        String number =  "";
        for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()) {
            if(!ObjectUtils.isEmpty(dmVisitorsUser.getPlateNumber()) || StringUtils.isNotBlank(dmVisitorsUser.getPlateNumber())){
                isPlateNumber = true;
                number = dmVisitorsUser.getPlateNumber();
                break;
            }
        }
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        if(!isPlateNumber){
            Map body  = new HashMap();
            body.put("visitorName",resources.getVisotors().get(0).getVisitorName());
            body.put("visitorPhone",resources.getVisotors().get(0).getVisitorPhone());
            body.put("startTime",resources.getStartTime());
            body.put("endTime",resources.getEndTime());
            body.put("reason",resources.getForVisiting());
            body.put("greeterName",resources.getDmUser().getName());
            body.put("greeterPhone",resources.getDmUser().getContacts());
            body.put("cardType",0);
            body.put("cardNum",null);
            body.put("depId",resources.getDept().getId());
            body.put("depName",resources.getDept().getName());
            body.put("gender",null);
            body.put("companyName",null);
            body.put("visitorNum",Integer.valueOf(resources.getVisNumber()));
            body.put("belongings",null);
            body.put("carNum",null);
            body.put("note",null);
            System.out.println("body:"+ JSONUtils.toJSONString(body));
            DmVisitorsApply dmVisitorsApply = null;
            String res = HttpRequest.post(erCodeUrl).form(body).execute().body();
            JSONObject json = JSONObject.parseObject(res);
            String qrCode = json.getString("qrCode");
            if(StringUtils.isNotBlank(qrCode)) {
                dmVisitorsApply = new DmVisitorsApply();
                dmVisitorsApply.setId(snowflake.nextId());
                dmVisitorsApply.setDmUser(resources.getDmUser());
                dmVisitorsApply.setDept(resources.getDept());
                dmVisitorsApply.setStartTime(resources.getStartTime());
                dmVisitorsApply.setEndTime(resources.getEndTime());
                dmVisitorsApply.setAdministration(resources.getAdministration());
                dmVisitorsApply.setVisNumber(resources.getVisNumber());
                dmVisitorsApply.setForVisiting(resources.getForVisiting());
                dmVisitorsApply.setType("00");//app
                dmVisitorsApply.setRequestUser(resources.getRequestUser());//dmUserMapper.toEntity(user.getDmUser())
                dmVisitorsApply.setQrCode(qrCode);
                dmVisitorsApply.setApplyStatus(0);
                dmVisitorsApply.setApproveState("01");
                dmVisitorsApplyRepository.save(dmVisitorsApply);

                for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()) {
                    DmVisitorsUser visitorsUser = new DmVisitorsUser();
                    visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                    visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                    visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                    visitorsUser.setVisitorsApply(dmVisitorsApply);
                    visitorsUser.setStartTime(resources.getStartTime());
                    visitorsUser.setEndTime(resources.getEndTime());
                    dmVisitorsUserRepository.save(visitorsUser);
                    //车牌登记
//                String url = "http://10.208.128.14:9999/api/park/addfreecar";
                    JSONObject generateProcJson = new JSONObject();
                    generateProcJson.put("name",dmVisitorsUser.getVisitorName());
                    generateProcJson.put("phone",dmVisitorsUser.getVisitorPhone());
                    generateProcJson.put("carplate",dmVisitorsUser.getPlateNumber());
                    SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
                    generateProcJson.put("startdate",formater2.format(resources.getStartTime()));
                    generateProcJson.put("enddate",formater2.format(resources.getEndTime()));
                    generateProcJson.put("cardtype","A");
                    generateProcJson.put("controllers", "5,6");
                    String generateProcData = BeanMapUtils.doPostForm(mfUrl,generateProcJson);
                    JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
                    System.out.println("add免费车:"+generateProcDataJson);
                }
            } else {
                throw new BadRequestException("获取二维码信息时失败！");
            }
            String id = dmVisitorsApply.getId().toString();
            return id;
        } else {
            String url = "https://portal.caih.com/api-third-party/busi/comm/collaboration/process/generateProc";
            String taskId = UUID.randomUUID().toString();
            JSONObject generateProcJson = new JSONObject();
            JSONObject formData = new JSONObject();
            formData.put("taskId",taskId);
            formData.put("number",number);
            formData.put("text",resources.getForVisiting());
            formData.put("carType","访客车牌");
            formData.put("taskType","3");
            generateProcJson.put("formData",formData);
            User user = userRepository.getUserByDmUserId(resources.getDmUser().getId());
            JSONObject caihRuRequestInfo = new JSONObject();
            caihRuRequestInfo.put("compId", user.getUserRootGroupId());
            caihRuRequestInfo.put("compName", user.getUserRootGroupName());
            caihRuRequestInfo.put("orgId", user.getDept().getId());
            caihRuRequestInfo.put("orgName", user.getDept().getName());
            caihRuRequestInfo.put("userId",user.getId());
            caihRuRequestInfo.put("userName",user.getNickName());
            caihRuRequestInfo.put("mobile",user.getPhone());
            generateProcJson.put("caihRuRequestInfo",caihRuRequestInfo);
            generateProcJson.put("procDefKey","CUST_e8d0cec5-2042-4730-a9ae-81bf4c2dd3e6");
            generateProcJson.put("procName","办公-永天流程申请");
            generateProcJson.put("tarTaskDefKey", "taskDefinitionKey2");
            generateProcJson.put("tenantId","caih");
            String generateProcData = HttpRequest.get(url).body(generateProcJson.toJSONString()).execute().body();
            System.out.println("generateProcData:"+generateProcData);
            System.out.println("formData:"+generateProcJson);
            DmVisitorsApply dmVisitorsApply = new DmVisitorsApply();
            dmVisitorsApply.setId(snowflake.nextId());
            dmVisitorsApply.setDmUser(resources.getDmUser());
            dmVisitorsApply.setDept(resources.getDept());
            dmVisitorsApply.setStartTime(resources.getStartTime());
            dmVisitorsApply.setEndTime(resources.getEndTime());
            dmVisitorsApply.setAdministration(resources.getAdministration());
            dmVisitorsApply.setVisNumber(resources.getVisNumber());
            dmVisitorsApply.setForVisiting(resources.getForVisiting());
            dmVisitorsApply.setType("00");//app
            dmVisitorsApply.setRequestUser(resources.getRequestUser());//dmUserMapper.toEntity(user.getDmUser())
            dmVisitorsApply.setApplyStatus(0);
            dmVisitorsApply.setApproveState("00");
            dmVisitorsApply.setTaskId(taskId);
            dmVisitorsApplyRepository.save(dmVisitorsApply);

            for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()) {
                DmVisitorsUser visitorsUser = new DmVisitorsUser();
                visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                visitorsUser.setVisitorsApply(dmVisitorsApply);
                visitorsUser.setStartTime(resources.getStartTime());
                visitorsUser.setEndTime(resources.getEndTime());
                dmVisitorsUserRepository.save(visitorsUser);
            }

            String id = dmVisitorsApply.getId().toString();
            return id;
        }
    }

    @Override
    public String visitorsApplyAdd(DmVisitorsDto resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
            Map body = new HashMap();
            body.put("visitorName", resources.getVisotors().get(0).getVisitorName());
            body.put("visitorPhone", resources.getVisotors().get(0).getVisitorPhone());
            body.put("startTime", resources.getStartTime());
            body.put("endTime", resources.getEndTime());
            body.put("reason", resources.getForVisiting());
            body.put("greeterName", resources.getDmUser().getName());
            body.put("greeterPhone", resources.getDmUser().getContacts());
            body.put("cardType", 0);
            body.put("cardNum", null);
            body.put("depId", resources.getDept().getId());
            body.put("depName", resources.getDept().getName());
            body.put("gender", null);
            body.put("companyName", null);
            body.put("visitorNum", Integer.valueOf(resources.getVisNumber()));
            body.put("belongings", null);
            body.put("carNum", null);
            body.put("note", null);
            System.out.println("body:" + JSONUtils.toJSONString(body));
            DmVisitorsApply dmVisitorsApply = null;
            String res = HttpRequest.post(erCodeUrl).form(body).execute().body();
            JSONObject json = JSONObject.parseObject(res);
            String qrCode = json.getString("qrCode");
            if (StringUtils.isNotBlank(qrCode)) {
                dmVisitorsApply = new DmVisitorsApply();
                dmVisitorsApply.setId(snowflake.nextId());
                dmVisitorsApply.setDmUser(resources.getDmUser());
                dmVisitorsApply.setDept(resources.getDept());
                dmVisitorsApply.setStartTime(resources.getStartTime());
                dmVisitorsApply.setEndTime(resources.getEndTime());
                dmVisitorsApply.setAdministration(resources.getAdministration());
                dmVisitorsApply.setVisNumber(resources.getVisNumber());
                dmVisitorsApply.setForVisiting(resources.getForVisiting());
                dmVisitorsApply.setType("00");//app
                dmVisitorsApply.setRequestUser(resources.getRequestUser());//dmUserMapper.toEntity(user.getDmUser())
                dmVisitorsApply.setQrCode(qrCode);
                dmVisitorsApply.setApplyStatus(0);
                dmVisitorsApply.setApproveState("01");
                dmVisitorsApplyRepository.save(dmVisitorsApply);

                for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()) {
                    DmVisitorsUser visitorsUser = new DmVisitorsUser();
                    visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                    visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                    visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                    visitorsUser.setVisitorsApply(dmVisitorsApply);
                    visitorsUser.setStartTime(resources.getStartTime());
                    visitorsUser.setEndTime(resources.getEndTime());
                    dmVisitorsUserRepository.save(visitorsUser);
                    //车牌登记
//                String url = "http://10.208.128.14:9999/api/park/addfreecar";
                    JSONObject generateProcJson = new JSONObject();
                    generateProcJson.put("name", dmVisitorsUser.getVisitorName());
                    generateProcJson.put("phone", dmVisitorsUser.getVisitorPhone());
                    generateProcJson.put("carplate", dmVisitorsUser.getPlateNumber());
                    SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
                    generateProcJson.put("startdate", formater2.format(resources.getStartTime()));
                    generateProcJson.put("enddate", formater2.format(resources.getEndTime()));
                    generateProcJson.put("cardtype", "A");
                    generateProcJson.put("controllers", "5,6");
                    String generateProcData = BeanMapUtils.doPostForm(mfUrl, generateProcJson);
                    JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
                    System.out.println("add免费车:" + generateProcDataJson);
                }


            } else {
                throw new BadRequestException("获取二维码信息时失败！");
            }
            String id = dmVisitorsApply.getId().toString();
            return id;

    }

    @Override
    public DmVisitorsApply newVisitorsApplyAdd(DmVisitorsDto resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        DmVisitorsApply dmVisitorsApply = new DmVisitorsApply();
        dmVisitorsApply.setId(snowflake.nextId());
        dmVisitorsApply.setDmUser(resources.getDmUser());
        dmVisitorsApply.setDept(resources.getDept());
        dmVisitorsApply.setStartTime(resources.getStartTime());
        dmVisitorsApply.setEndTime(resources.getEndTime());
        dmVisitorsApply.setAdministration(resources.getAdministration());
        dmVisitorsApply.setForVisiting(resources.getForVisiting());
        dmVisitorsApply.setType("00");//app
        dmVisitorsApply.setRequestUser(resources.getRequestUser());//dmUserMapper.toEntity(user.getDmUser())
        dmVisitorsApply.setApplyStatus(0);
        dmVisitorsApply.setApproveState("03");
        if(ObjectUtils.isEmpty(resources.getVisotors()) || resources.getVisotors().size()==0) {
            dmVisitorsApply.setApplyType("00");
            dmVisitorsApplyRepository.save(dmVisitorsApply);
        } else {
            dmVisitorsApply.setVisNumber(String.valueOf(resources.getVisotors().size()));
            dmVisitorsApply.setApplyType("01");
            DmVisitorsApply newDmVisitorsApply = dmVisitorsApplyRepository.save(dmVisitorsApply);
            for(DmVisitorsUser dmVisitorsUser : resources.getVisotors()){
                dmVisitorsUser.setVisitorsApply(newDmVisitorsApply);
                dmVisitorsUser.setStartTime(resources.getStartTime());
                dmVisitorsUser.setEndTime(resources.getEndTime());
                dmVisitorsUserRepository.save(dmVisitorsUser);
            }
        }
        return dmVisitorsApply;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmVisitorsDto resources) {
        DmVisitorsApply dmVisitorsApply = dmVisitorsApplyRepository.findById(resources.getId()).orElseGet(DmVisitorsApply::new);
        ValidationUtil.isNull( dmVisitorsApply.getId(),"DmVisitorsApply","id",resources.getId());
        DmVisitorsApply visitorsApply = new DmVisitorsApply();
        visitorsApply.setDmUser(resources.getDmUser());
        visitorsApply.setDept(resources.getDept());
        visitorsApply.setStartTime(resources.getStartTime());
        visitorsApply.setEndTime(resources.getEndTime());
        visitorsApply.setAdministration(resources.getAdministration());
        visitorsApply.setVisNumber(resources.getVisNumber());
        visitorsApply.setForVisiting(resources.getForVisiting());
        dmVisitorsApply.copy(visitorsApply);
        dmVisitorsApplyRepository.save(dmVisitorsApply);

        for (DmVisitorsUser dmVisitorsUser : resources.getVisotors()){
            if (dmVisitorsUser.getVisitorId() == null){
                DmVisitorsUser visitorsUser = new DmVisitorsUser();
                visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                visitorsUser.setVisitorsApply(dmVisitorsApply);
                dmVisitorsUserRepository.save(visitorsUser);
            }else {
                DmVisitorsUser dmVisitorsUser1 = dmVisitorsUserRepository.findById(dmVisitorsUser.getVisitorId()).orElseGet(DmVisitorsUser::new);
                ValidationUtil.isNull( dmVisitorsUser1.getVisitorId(),"DmVisitorsUser","VisitorId",dmVisitorsUser.getVisitorId());
                DmVisitorsUser visitorsUser = new DmVisitorsUser();
                visitorsUser.setVisitorName(dmVisitorsUser.getVisitorName());
                visitorsUser.setVisitorPhone(dmVisitorsUser.getVisitorPhone());
                visitorsUser.setPlateNumber(dmVisitorsUser.getPlateNumber());
                dmVisitorsUser1.copy(visitorsUser);
                dmVisitorsUserRepository.save(visitorsUser);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDmVisitorsApply(DmVisitorsApply resources) {
        DmVisitorsApply dmVisitorsApply = dmVisitorsApplyRepository.findById(resources.getId()).orElseGet(DmVisitorsApply::new);
        ValidationUtil.isNull( dmVisitorsApply.getId(),"DmVisitorsApply","id",resources.getId());
        dmVisitorsApply.copy(resources);
        dmVisitorsApplyRepository.save(dmVisitorsApply);
    }

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

    @Override
    public void download(List<DmVisitorsApplyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmVisitorsApplyDto dmVisitorsApply : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("被访人员工号", dmVisitorsApply.getDmUser().getUserNumber());
            map.put("到访部门", dmVisitorsApply.getDept().getName());
            map.put("到访开始时间", dmVisitorsApply.getStartTime());
            map.put("到访结束时间", dmVisitorsApply.getEndTime());
            map.put("访客二维码", dmVisitorsApply.getQrCode());
            map.put("到访事由", dmVisitorsApply.getForVisiting());
            map.put("申请者", dmVisitorsApply.getCreateBy());
            map.put("更新者", dmVisitorsApply.getUpdateBy());
            map.put("申请时间", dmVisitorsApply.getCreateTime());
            map.put("更新时间", dmVisitorsApply.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public int updateDmVisitorsApplyStatus(List<String> list, Integer status) {
        return this.dmVisitorsApplyRepository.updateDmVisitorsApplyStatus(list,status);
    }

    @Override
    public DmVisitorsApply findDmVisitorsApplyByTaskId( String taskId){
        return dmVisitorsApplyRepository.findDmVisitorsApplyByTaskId(taskId);
    }
}