package me.zhengjie.modules.thirdparty.v1;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Limit;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.aspect.LimitType;
import me.zhengjie.base.BaseResponse;
import me.zhengjie.base.QueryPageParams;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.modules.dm.dmCard.service.DmCardService;
import me.zhengjie.modules.dm.dmCard.service.dto.DmCardDto;
import me.zhengjie.modules.dm.dmCard.service.dto.DmCardQueryCriteria;
import me.zhengjie.modules.dm.dmPlateTraffic.domain.DmPlateTraffic;
import me.zhengjie.modules.dm.dmPlateTraffic.service.DmPlateTrafficService;
import me.zhengjie.modules.dm.dmPlateTraffic.service.dto.DmPlateTrafficDto;
import me.zhengjie.modules.dm.dmPlateTraffic.service.dto.DmPlateTrafficQueryCriteria;
import me.zhengjie.modules.dm.dmReadingRoom.domain.DmReadingRoom;
import me.zhengjie.modules.dm.dmReadingRoom.repository.DmReadingRoomRepository;
import me.zhengjie.modules.dm.dmReadingRoom.service.DmReadingRoomService;
import me.zhengjie.modules.dm.dmReadingRoom.service.dto.DmReadingRoomQueryCriteria;
import me.zhengjie.modules.dm.dmVisitorsApply.domain.DmVisitorsApply;
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.dto.DmVisitorsDto;
import me.zhengjie.modules.dm.dmVisitorsApply.service.dto.VisitorsApplyList;
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.dm.dmtsInfo.domain.DmTsInfo;
import me.zhengjie.modules.dm.dmtsInfo.service.DmTsInfoService;
import me.zhengjie.modules.dm.dmtsInfo.service.dto.DmTsInfoQueryCriteria;
import me.zhengjie.modules.dmAccessTraffic.domain.DmAccessTraffic;
import me.zhengjie.modules.dmAccessTraffic.service.DmAccessTrafficService;
import me.zhengjie.modules.dmAccessTraffic.service.dto.CallbackAccessTrafficDto;
import me.zhengjie.modules.dmAccessTraffic.service.dto.DmAccessTrafficDto;
import me.zhengjie.modules.dmAccessTraffic.service.dto.DmAccessTrafficQueryCriteria;
import me.zhengjie.modules.dmExpenseCalendar.service.DmExpenseCalendarService;
import me.zhengjie.modules.dmExpenseCalendar.service.dto.DmExpenseCalendarDto;
import me.zhengjie.modules.dmExpenseCalendar.service.dto.DmExpenseCalendarQueryCriteria;
import me.zhengjie.modules.dmParkingTraffic.service.DmParkingTrafficService;
import me.zhengjie.modules.dmParkingTraffic.service.dto.DmParkingTrafficDto;
import me.zhengjie.modules.dmParkingTraffic.service.dto.DmParkingTrafficQueryCriteria;
import me.zhengjie.modules.dmRechargeRecord.service.DmRechargeRecordService;
import me.zhengjie.modules.dmRechargeRecord.service.dto.DmRechargeRecordDto;
import me.zhengjie.modules.dmRechargeRecord.service.dto.DmRechargeRecordQueryCriteria;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.dmuser.service.DmUserService;
import me.zhengjie.modules.dmuser.service.dto.DmUserDto;
import me.zhengjie.modules.dmuser.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.DeptQueryCriteria;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.utils.*;
import me.zhengjie.ykt.domain.DmPlateNumber;
import me.zhengjie.ykt.domain.DmRoomDevice;
import me.zhengjie.ykt.service.DmPlateNumberService;
import me.zhengjie.ykt.service.DmRoomDeviceService;
import me.zhengjie.ykt.service.dto.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "用户接口")
@RequestMapping("/api/thirdparty/v1/openInterface")
public class OpenApiController {
    @Value("${AccessTraffic}")
    private String api;
    @Value("${mfUrl}")
    private String mfUrl;
    @Value("${erCodeUrl}")
    private String erCodeUrl;
    private final DmCardService dmCardService;
    private final DmRoomDeviceService dmRoomDeviceService;
    private final DmPlateTrafficService dmPlateTrafficService;
    private final DmPlateNumberService dmPlateNumberService;
    private final DmExpenseCalendarService dmExpenseCalendarService;
    private final DmRechargeRecordService dmRechargeRecordService;
    private final DmAccessTrafficService dmAccessTrafficService;
    private final DmUserService dmUserService;
    private final UserService userService;
    private final DmVisitorsApplyService dmVisitorsApplyService;
    private final DmVisitorsUserService dmVisitorsUserService;
    private final DeptService deptService;
    private final DmVisitorsUserRepository dmVisitorsUserRepository;
    private final FileProperties properties;
    private final DmReadingRoomService dmReadingRoomService;
    private final DmReadingRoomRepository dmReadingRoomRepository; //阅览室记录
    private final WxUtil wxUtil;
    private final DmTsInfoService dmTsInfoService; //图书信息
    private final DmParkingTrafficService dmParkingTrafficService;

    @Log("获取用户、人脸数据")
    @ApiOperation("获取用户、人脸数据")
    @AnonymousPostMapping(value = "/getDmUser")
    public BaseResponse<Object> getDmUser(@RequestBody QueryPageParams<DmUserQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmUserDto> map = dmUserService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @Log("获取卡数据")
    @ApiOperation("获取卡数据")
    @AnonymousPostMapping(value = "/getCard")
    public BaseResponse<Object> getCard(@RequestBody QueryPageParams<DmCardQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmCardDto> map = dmCardService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getPlateNumber")
    @Log("获取车牌数据")
    @ApiOperation("获取车牌数据")
    public BaseResponse<Object> getPlateNumber(@RequestBody QueryPageParams<DmPlateNumberQueryCriteria> criteria){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmPlateNumberDto> map = dmPlateNumberService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getRoomDevice")
    @Log("获取门禁设备数据")
    @ApiOperation("获取门禁设备数据")
    public BaseResponse<Object> getRoomDevice(@RequestBody QueryPageParams<DmRoomDeviceQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmRoomDeviceDto> map = dmRoomDeviceService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getAccessTraffic")
    @Log("获取门禁通行记录")
    @ApiOperation("获取门禁通行记录")
    public BaseResponse<Object> getAccessTraffic(@RequestBody QueryPageParams<DmAccessTrafficQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        Map<String,Object> map = dmAccessTrafficService.queryAll(criteria.getQuery(),pageable);
        List<DmAccessTrafficDto> array = JSONArray.parseArray(JSONArray.toJSONString(map.get("content")),DmAccessTrafficDto.class);
        List<DmAccessTrafficDto> newArray = new ArrayList<>();
        for(DmAccessTrafficDto dmAccessTrafficDto : array){
            String roomDevice = dmAccessTrafficDto.getRoomDevice();
            DmRoomDevice dmRoomDevice = dmRoomDeviceService.findByCode(roomDevice).get(0);
            dmAccessTrafficDto.setDmRoomDevice(dmRoomDevice);
            newArray.add(dmAccessTrafficDto);
        }
        map.put("content",newArray);
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getParkingTraffic")
    @Log("获取停车记录")
    @ApiOperation("获取停车记录")
    public BaseResponse<Object> getParkingTraffic(@RequestBody QueryPageParams<DmParkingTrafficQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        String userNumber = criteria.getQuery().getUserNumber();
        DmPlateNumberQueryCriteria dmPlateNumberQueryCriteria = new DmPlateNumberQueryCriteria();
        dmPlateNumberQueryCriteria.setUserNumber(userNumber);
        List<DmPlateNumberDto >dmPlateNumberDtoList = dmPlateNumberService.queryAll(dmPlateNumberQueryCriteria);
        Map<String,Object> map = new HashMap<>();
        for(DmPlateNumberDto dmPlateNumberDto : dmPlateNumberDtoList){
            criteria.getQuery().setPlateNo(dmPlateNumberDto.getPlateNumber());
            map.putAll(dmParkingTrafficService.queryAll(criteria.getQuery(),pageable));
        }
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getParkingTrafficByUserNumber")
    @Log("根据用户id获取停车记录")
    @ApiOperation("根据用户id获取停车记录")
    public BaseResponse<Object> getParkingTrafficByUserNumber(@RequestBody QueryPageParams<DmParkingTrafficQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
       List<Map<String,Object>> map = dmPlateTrafficService.getParkingTrafficByUserNumber(criteria.getQuery().getUserNumber(),pageable);
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getPlateTraffic")
    @Log("获取停车通行记录")
    @ApiOperation("获取停车通行记录")
    public BaseResponse<Object> getPlateTraffic(@RequestBody QueryPageParams<DmPlateTrafficQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmPlateTrafficDto> map = dmPlateTrafficService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getRechargeRecord")
    @Log("获取充值数据")
    @ApiOperation("获取充值数据")
    public BaseResponse<Object> getRechargeRecord(@RequestBody QueryPageParams<DmRechargeRecordQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmRechargeRecordDto> map = dmRechargeRecordService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/getExpenseCalendar")
    @Log("获取消费数据")
    @ApiOperation("获取消费数据")
    public BaseResponse<Object> getExpenseCalendar(@RequestBody QueryPageParams<DmExpenseCalendarQueryCriteria> criteria, Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        List<DmExpenseCalendarDto> map = dmExpenseCalendarService.queryAll(criteria.getQuery());
        return new BaseResponse<>(map);
    }

    @AnonymousPostMapping(value = "/visitorsApplyAdd")
    @Log("App访客申请")
    @ApiOperation("App访客申请")
    public BaseResponse<Object> visitorsApplyAdd(@RequestBody QueryPageParams<DmVisitorsDto> resources){
        SecurityUtils.CheckApiAuth(resources);
        //dmVisitorsApplyService.visitorsApplyAdd(resources.getQuery());
        String dmVisitorsApply = dmVisitorsApplyService.visitorsApplyAdd(resources.getQuery());
        return new BaseResponse<>(dmVisitorsApply);
    }

    @AnonymousPostMapping(value = "/visitorsApplyAdd2")
    @Log("App访客申请")
    @ApiOperation("App访客申请")
    public BaseResponse<Object> visitorsApplyAdd2(@RequestBody QueryPageParams<DmVisitorsDto> resources){
        SecurityUtils.CheckApiAuth(resources);
        //dmVisitorsApplyService.visitorsApplyAdd(resources.getQuery());
        String dmVisitorsApply = dmVisitorsApplyService.visitorsApplyAdd(resources.getQuery());
        return new BaseResponse<>(dmVisitorsApply);
    }

    @AnonymousPostMapping(value = "/getVisitors")
    @Log("App访客记录")
    @ApiOperation("App访客记录")
    public BaseResponse<Object> getVisitors(@RequestBody QueryPageParams<String> userNumber, Pageable pageable) {
        SecurityUtils.CheckApiAuth(userNumber);
        return new BaseResponse<>(dmVisitorsApplyService.getVisApp(userNumber.getQuery(),pageable));
    }
    @AnonymousPostMapping(value = "/getVisitant")
    @Log("App访客记录")
    @ApiOperation("App访客记录")
    public BaseResponse<Object> getVisitant(@RequestBody QueryPageParams<String> userNumber, Pageable pageable) {
        SecurityUtils.CheckApiAuth(userNumber);
        return new BaseResponse<>(dmVisitorsApplyService.getVisitantApp(userNumber.getQuery(),pageable));
    }

    @AnonymousPostMapping(value = "/getVisitorsXq")
    @Log("App访客详情")
    @ApiOperation("App访客详情")
    public BaseResponse<Object> getVisitorsXq(@RequestBody QueryPageParams<DmVisitorsApplyQueryCriteria> userNumber) {
        SecurityUtils.CheckApiAuth(userNumber);
        List<DmVisitorsApplyDto> list = dmVisitorsApplyService.queryAll(userNumber.getQuery());//List<DmVisitorsDto>
        DmVisitorsApplyDto dmVisitorsApplyDto = list.get(0);
        List<DmVisitorsUser> userDtos = dmVisitorsUserRepository.getVisXq(dmVisitorsApplyDto.getId());
        dmVisitorsApplyDto.setVisitorsUsers(userDtos);
        return new BaseResponse<>(list);
    }

    @AnonymousPostMapping(value = "/getVisitorsXqUser")
    @Log("App访客详情")
    @ApiOperation("App访客详情")
    public BaseResponse<Object> getVisitorsXqUser(@RequestBody QueryPageParams<DmVisitorsUserQueryCriteria> userNumber) {
        SecurityUtils.CheckApiAuth(userNumber);
        List<DmVisitorsUserDto> list = dmVisitorsUserService.queryAll(userNumber.getQuery());//List<DmVisitorsDto>
        return new BaseResponse<>(list);
    }

    @AnonymousPostMapping(value = "/createApp")
    @Log("App车牌登记")
    @ApiOperation("App车牌登记")
    public BaseResponse<Object> createApp(@RequestBody QueryPageParams<DmPlateNumber> resources) throws ParseException {
        SecurityUtils.CheckApiAuth(resources);
        dmPlateNumberService.createApp(resources.getQuery());
        return new BaseResponse<>(true);
    }

    @AnonymousPostMapping(value="/findUser")
    @Log("查询未绑定卡号的用户")
    @ApiOperation("查询未绑定卡号的用户")
    public BaseResponse<Object> findUser(@RequestBody QueryPageParams<DmUserQueryCriteria> dmUserQueryCriteria){
        SecurityUtils.CheckApiAuth(dmUserQueryCriteria);
        return new BaseResponse<>(dmUserService.findUser());
    }

    @AnonymousPostMapping(value="/findUserByDeptId")
    @Log("根据部门编号查询用户")
    @ApiOperation("根据部门编号查询用户")
    public BaseResponse<Object> findUserByDeptId(@RequestBody QueryPageParams<String> dmUserQueryCriteria){
        SecurityUtils.CheckApiAuth(dmUserQueryCriteria);
        return new BaseResponse<>(dmUserService.findUserByDeptId(dmUserQueryCriteria.getQuery()));
    }

    @ApiOperation("查询部门")
    @Log("查询部门")
    @AnonymousPostMapping("/getDept")
    public BaseResponse<Object> query(@RequestBody QueryPageParams<DeptQueryCriteria> criteria) throws Exception {
        SecurityUtils.CheckApiAuth(criteria);
        return new BaseResponse<>(deptService.getDeptAppVis());//PageUtil.toPage(deptDtos, deptDtos.size())
    }

    @ApiOperation("查询访客列表")
    @Log("查询访客列表")
    @AnonymousPostMapping("/queryDmVisitorsApply")
    public BaseResponse<Object> queryDmVisitorsApply(@RequestBody QueryPageParams<DmVisitorsApplyQueryCriteria> criteria,Pageable pageable){
        SecurityUtils.CheckApiAuth(criteria);
        return  new BaseResponse<>(dmVisitorsApplyService.queryAll(criteria.getQuery(),pageable));
    }

    @ApiOperation("修改访客状态")
    @Log("修改访客状态")
    @AnonymousPostMapping("/editDmVisitorsApplyStatus")
    public BaseResponse<Object> editDmVisitorsApplyStatus(@RequestBody QueryPageParams<String> criteria) {
        //验证是否是合法请求
        SecurityUtils.CheckApiAuth(criteria);
        // 将字符串参数转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(criteria.getQuery());
        // 为防止参数异常 特意转换为字符串
        List<String> list = JSONObject.parseArray(jsonObject.get("ids").toString(), String.class);
        // 开始修改
        int i = this.dmVisitorsApplyService.updateDmVisitorsApplyStatus(list, jsonObject.get("applyStatus") == null ? 0 : jsonObject.getInteger("applyStatus"));

        return new BaseResponse<>(i);
    }
    @ApiOperation("查询部门:根据ID获取同级与上级数据")
    @AnonymousPostMapping("/superior")
    @PreAuthorize("@el.check('user:list','dept:list')")
    public BaseResponse<Object> getSuperior(@RequestBody QueryPageParams<List<String>> ids) {
        SecurityUtils.CheckApiAuth(ids);
        Set<DeptDto> deptDtos  = new LinkedHashSet<>();
        for (String id : ids.getQuery()) {
            DeptDto deptDto = deptService.findById(id);
            List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>());
            deptDtos.addAll(depts);
        }
        return new BaseResponse<>(deptService.buildTree(new ArrayList<>(deptDtos)));
    }

    @AnonymousAccess
    @GetMapping(value = "/parkingSpot")
    @Log("pc端运营停车位统计")
    @ApiOperation("pc端运营停车位统计")
    public ResponseEntity<Object> parkingSpot(){
        return new ResponseEntity<>(dmPlateTrafficService.parkingSpot(),HttpStatus.OK);
    }

    @AnonymousAccess
    @GetMapping(value = "/yunUserRequest")
    @Log("pc端运营今日人流量统计")
    @ApiOperation("pc端运营今日人流量统计")
    public ResponseEntity<Object> YunUserRequest(){
        return new ResponseEntity<>(dmAccessTrafficService.YunUserRequest(),HttpStatus.OK);
    }

    @Log("App端运营停车位统计")
    @ApiOperation("App端运营停车位统计")
    @AnonymousPostMapping(value = "/parkingSpotApp")
    public BaseResponse<Object> parkingSpotApp(@RequestBody QueryPageParams<DmPlateTraffic> criteria){
        SecurityUtils.CheckApiAuth(criteria);
        return new BaseResponse<>(dmPlateTrafficService.parkingSpot());
    }

    @Log("App端运营今日人流量统计")
    @ApiOperation("App端运营今日人流量统计")
    @AnonymousPostMapping(value = "/yunUserRequestApp")
    public BaseResponse<Object> yunUserRequestApp(@RequestBody QueryPageParams<DmAccessTraffic> criteria){
        SecurityUtils.CheckApiAuth(criteria);
        return new BaseResponse<>(dmAccessTrafficService.YunUserRequest());
    }

//    @Log("接收通行记录")
//    @ApiOperation("接收通行记录")
//    @AnonymousPostMapping(value = "/callbackAccessTraffic")
////    @Limit(name = "接收通行记录",period = 60,count = 60,limitType = LimitType.IP)
//    public BaseResponse<Object> callbackAccessTraffic(@RequestBody JSONObject json) {
//        System.out.println("json:"+json.toJSONString());
//        dmAccessTrafficService.callbackAccessTraffic(json);
//        return new BaseResponse<>(true);
//    }

    @Log("配置接收通行记录地址")
    @ApiOperation("配置接收通行记录地址")
    @AnonymousGetMapping(value = "/SetPushRecCallBack")
    public BaseResponse<Object> SetPushRecCallBack(String url) throws IOException, ParseException {
//        String api = "http://10.208.128.14:8069/openapi/SetPushRecCallBack?callbackURL=https://smartpark.caih.com/ykt/api/thirdparty/v1/openInterface/callbackAccessTraffic";
        String res = HttpRequest.post(api).execute().body();
        System.out.println("res:"+res);
        return new BaseResponse<>(JSONObject.parse(res));
    }

    @Log("查询阅览记录")
    @ApiOperation("查询阅览记录")
    @AnonymousPostMapping(value = "/selectReadRoom")
    public  BaseResponse<Object> selectReadRoom(@RequestBody QueryPageParams<DmReadingRoomQueryCriteria> queryPageParams,Pageable pageable){
        SecurityUtils.CheckApiAuth(queryPageParams);
        return  new BaseResponse<>(dmReadingRoomService.queryAll(queryPageParams.getQuery(),pageable));
    }

    @Log("查询图书列表")
    @ApiOperation("查询图书列表")
    @AnonymousPostMapping(value = "/selectTsInfo")
    public  BaseResponse<Object> selectTsInfo(@RequestBody QueryPageParams<DmTsInfoQueryCriteria> queryPageParams,Pageable pageable){
        SecurityUtils.CheckApiAuth(queryPageParams);
        return new BaseResponse<>(dmTsInfoService.queryAll(queryPageParams.getQuery(),pageable));
    }

    @Log("查询图书列表类型")
    @ApiOperation("查询图书列表类型")
    @AnonymousGetMapping(value = "/selectTsInfoType")
    public  BaseResponse<Object> selectTsInfoType(QueryPageParams<String> queryPageParams){
//        SecurityUtils.CheckApiAuth(queryPageParams);
        return new BaseResponse<>(dmTsInfoService.getTsTypeAll());
    }

    @Log("新增阅览记录")
    @ApiOperation("新增阅览记录")
    @AnonymousPostMapping(value = "/insertReadRoom")
    public  BaseResponse<Object> insertReadRoom(@RequestBody QueryPageParams<List<DmReadingRoom>> queryPageParams){
        SecurityUtils.CheckApiAuth(queryPageParams);
        List<DmReadingRoom> query = queryPageParams.getQuery();
        for (DmReadingRoom dmReadingRoom : query) {
            Long reading_room_id = dmReadingRoom.getReadingRoomId();//主键id
            String borrow_user_card = dmReadingRoom.getDmUser().getId();//借阅人id
            String borrow_user_name = dmReadingRoom.getBorrowUserName();//借阅人用户名称
            DmTsInfo dmTsInfo = dmReadingRoom.getDmTsInfo(); // 图书对象
            String collection_sin = dmReadingRoom.getCollectionSin();//条形码
            Timestamp read_start_time = dmReadingRoom.getReadStartTime();//借阅开始时间
            Timestamp read_end_time = dmReadingRoom.getReadEndTime();//借阅结束时间
            Timestamp return_time = dmReadingRoom.getReturnTime();//还书时间
            String borrow_status = dmReadingRoom.getBorrowStatus(); //标志
            Integer overdueDay = dmReadingRoom.getOverdueDay();//预期天数
             Integer isOverdue = dmReadingRoom.getIsOverdue(); //是否预期
             //新建读者用户对象
            DmUser byCardId = this.dmUserService.findByUserCardId(borrow_user_card);
            dmReadingRoom.setDmUser(byCardId);
            dmReadingRoomRepository.save(dmReadingRoom);
        }
        return  new BaseResponse<>(null);
    }

    @Log("预约审批")
    @ApiOperation("预约审批")
    @AnonymousPostMapping("/updateApproveStatusByTaskId")
    public BaseResponse<Object> updateApproveStatusByTaskId(@RequestBody QueryPageParams<ApprovaDto> params) throws IOException {
        SecurityUtils.CheckApiAuth(params);
        String taskId = params.getQuery().getTaskId();
        System.out.println("taskId:"+taskId);
        String approveStatus = params.getQuery().getApproveStatus();
        System.out.println("approveStatus"+approveStatus);
        String remark = params.getQuery().getApproveSuggest();
        System.out.println("remark:"+remark);
        Map<String,Object> token = SecurityUtils.getToken("DMERPYT!@#$QWER2021+{:>");
        //查询会议预约信息
        DmPlateNumber dmPlateNumber = dmPlateNumberService.findDmPlateNumberByTaskId(taskId);
        if (!ObjectUtils.isEmpty(dmPlateNumber)) {
            String sendContent = "";
            if (StringUtils.equals(approveStatus,"01")) {//01、已通过
                sendContent = "您申请的停车车牌（"+dmPlateNumber.getPlateNumber()+"）已完成审批，审批结果：同意，您的车牌已录入至停车管理系统数据库。";
                //修改文印申请信息
                DmPlateNumber request = new DmPlateNumber();
                request.setId(dmPlateNumber.getId());
                request.setRegistrationStatus(approveStatus);
                request.setApproveSuggest(remark);
                dmPlateNumberService.update(request);

                if (dmPlateNumber.getVehicleType().equals("00")) {//员工
                    dmPlateNumberService.addYuePlate(dmPlateNumber);
                } else if (dmPlateNumber.getVehicleType().equals("02")) {//访客
                    dmPlateNumberService.mfReserveData(dmPlateNumber);
                }

            } else if (StringUtils.equals(approveStatus,"02")) {//02、未通过
                sendContent = "您申请的停车车牌（"+dmPlateNumber.getPlateNumber()+"）已完成审批，审批结果：不同意。";
                //修改文印申请信息
                DmPlateNumber request = new DmPlateNumber();
                request.setId(dmPlateNumber.getId());
                request.setRegistrationStatus(approveStatus);
                request.setApproveSuggest(remark);
                dmPlateNumberService.update(request);
            }
            UserDto user = userService.findById(dmPlateNumber.getUserNumber().getId());
            MessageSendUtils.sendChatMessage("dm_plate_number|task_id|"+dmPlateNumber.getTaskId(),dmPlateNumber.getUserNumber().getId(),sendContent,user.getUsername());
        } else {
            DmVisitorsApply dmVisitorsApply = dmVisitorsApplyService.findDmVisitorsApplyByTaskId(taskId);
            if(!ObjectUtils.isEmpty(dmVisitorsApply)){
                String sendContent = "";
                if (StringUtils.equals(approveStatus,"01")) {//01、已通过
                    List<DmVisitorsUser> dmVisitorsUserList = dmVisitorsUserService.findByApplyId(dmVisitorsApply.getId());
                    Map body  = new HashMap();
                    body.put("visitorName",dmVisitorsUserList.get(0).getVisitorName());
                    body.put("visitorPhone",dmVisitorsUserList.get(0).getVisitorPhone());
                    body.put("startTime",dmVisitorsApply.getStartTime());
                    body.put("endTime",dmVisitorsApply.getEndTime());
                    body.put("reason",dmVisitorsApply.getForVisiting());
                    body.put("greeterName",dmVisitorsApply.getDmUser().getName());
                    body.put("greeterPhone",dmVisitorsApply.getDmUser().getContacts());
                    body.put("cardType",0);
                    body.put("cardNum",null);
                    body.put("depId",dmVisitorsApply.getDept().getId());
                    body.put("depName",dmVisitorsApply.getDept().getName());
                    body.put("gender",null);
                    body.put("companyName",null);
                    body.put("visitorNum",Integer.valueOf(dmVisitorsApply.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");
                    //生成二维码URL
                    String outPutPath = properties.getPath().getPath() +  File.separator+dmVisitorsApply.getId()+".jpg";
                    String url = ImageUtil.CodeCreate(qrCode,300,300,outPutPath,"jpg");
                    //修改文印申请信息
                    DmVisitorsApply request = new DmVisitorsApply();
                    request.setId(dmVisitorsApply.getId());
                    request.setQrCode(qrCode);
                    request.setQrCodeUrl(url);
                    request.setApproveState(approveStatus);
                    request.setApproveSuggest(remark);
                    dmVisitorsApplyService.updateDmVisitorsApply(request);
                    for (DmVisitorsUser dmVisitorsUser : dmVisitorsUserList) {
                        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(dmVisitorsUser.getStartTime()));
                        generateProcJson.put("enddate",formater2.format(dmVisitorsUser.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);
                        sendContent = "访客"+dmVisitorsUser.getVisitorName()+"的停车申请已完成审批，审批结果：同意，请通知访客";
                        //发送短信
                        MessageSendUtils.sendMsg(dmVisitorsUser.getVisitorPhone(),"你的来访手续已完成办理，请点击下方的链接地址，下载二维码。在获准的拜访期间，凭此二维码在大楼人行道闸通行。"+url);
                    }
                } else if (StringUtils.equals(approveStatus,"02")) {//02、未通过
                    sendContent = "访客的停车申请已完成审批，审批结果：不同意，请及时沟通访客";
                    //修改文印申请信息
                    DmVisitorsApply request = new DmVisitorsApply();
                    request.setId(dmVisitorsApply.getId());
                    request.setApproveState(approveStatus);
                    request.setApproveSuggest(remark);
                    dmVisitorsApplyService.updateDmVisitorsApply(request);
                }
                UserDto user = userService.findById(dmPlateNumber.getUserNumber().getId());
                MessageSendUtils.sendChatMessage("dm_plate_number|task_id|"+dmPlateNumber.getTaskId(),dmPlateNumber.getUserNumber().getId(),sendContent,user.getUsername());
            } else {
                return new BaseResponse<>("未查询userService到车牌数据!",-1,"未查询到车牌数据!");
            }
        }
        return new BaseResponse<>(true);
    }

    @Log("接收车辆进出场记录")
    @ApiOperation("接收车辆进出场记录")
    @AnonymousPostMapping(value = "/vehicleAccessTraffic")
    public BaseResponse<Object> vehicleAccessTraffic(@RequestBody JSONObject json) throws ParseException{
        //System.out.println("接收车辆进出场记录:"+json.toJSONString());
        dmVisitorsUserService.vehicleAccessTraffic(json);
        return new BaseResponse<>(true);
    }

    @Log("接收充值记录")
    @ApiOperation("接收充值记录")
    @AnonymousPostMapping(value = "/vehicleRechargeRecord")
    public BaseResponse<Object> vehicleRechargeRecord(@RequestBody JSONObject json){
        log.info("vehicleRechargeRecordJSON:" + json);
        dmRechargeRecordService.vehicleRechargeRecord(json);
        return new BaseResponse<>(true);
    }

    @Log("接收消费记录")
    @ApiOperation("接收消费记录")
    @AnonymousPostMapping(value = "/vehicleExpenseRecord")
    public BaseResponse<Object> vehicleExpenseRecord(@RequestBody JSONObject json){
        log.info("vehicleExpenseRecordJSON:" + json);
        dmExpenseCalendarService.vehicleExpenseRecord(json);
        return new BaseResponse<>(true);
    }

    @AnonymousPostMapping(value = "/newVisitorsApplyAdd")
    @Log("访客申请")
    @ApiOperation("访客申请")
    public BaseResponse<Object> newVisitorsApplyAdd(@RequestBody QueryPageParams<DmVisitorsDto> resources){
        SecurityUtils.CheckApiAuth(resources);
        DmVisitorsApply dmVisitorsApply = dmVisitorsApplyService.newVisitorsApplyAdd(resources.getQuery());
        return new BaseResponse<>(dmVisitorsApply);
    }

    @AnonymousPostMapping(value = "/visitorsUserDetails")
    @Log("访客登记详情")
    @ApiOperation("访客登记详情")
    public BaseResponse<Object> visitorsUserDetails(@RequestBody QueryPageParams<Long> resources){
        SecurityUtils.CheckApiAuth(resources);
        DmVisitorsApplyDto dmVisitorsApplyDto = dmVisitorsApplyService.findById(resources.getQuery());
        List<DmVisitorsUser> dmVisitorsUserList = dmVisitorsUserRepository.getVisXq(dmVisitorsApplyDto.getId());
        if(!ObjectUtils.isEmpty(dmVisitorsUserList)){
            dmVisitorsApplyDto.setVisitorsUsers(dmVisitorsUserList);
        } else {
            dmVisitorsApplyDto.setVisitorsUsers(null);
        }
        return new BaseResponse<>(dmVisitorsApplyDto);
    }

    @AnonymousPostMapping(value = "/visitorsUserAdd")
    @Log("新增访客")
    @ApiOperation("新增访客")
    public BaseResponse<Object> visitorsUserAdd(@RequestBody QueryPageParams<DmVisitorsDto> resources){
        SecurityUtils.CheckApiAuth(resources);
        dmVisitorsUserService.createAll(resources.getQuery().getVisotors());
        return new BaseResponse<>(true);
    }

    private final LocalStorageService localStorageService;

    @Log("上传文件")
    @ApiOperation("上传文件")
    @AnonymousPostMapping("/uploadFile")
    public ResponseEntity<Object> create(@RequestParam String timestamp, @RequestParam String nonce, @RequestParam String name, @RequestParam("file") MultipartFile file) {
        QueryPageParams params = new QueryPageParams();
        params.setNonce(nonce);
        params.setTimestamp(timestamp);
        SecurityUtils.CheckApiAuth(params);
        LocalStorage localStorage = localStorageService.create(name, file);
        return new ResponseEntity<>(localStorage, HttpStatus.CREATED);
    }

    @Log("删除文件")
    @ApiOperation("删除文件")
    @AnonymousPostMapping("/deleteFile")
    public ResponseEntity<Object> delete(@RequestBody QueryPageParams<Long[]> params) {
        SecurityUtils.CheckApiAuth(params);
        localStorageService.deleteAll(params.getQuery());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/visitorsApplyList")
    @Log("访客申请列表")
    @ApiOperation("访客申请列表")
    public BaseResponse<Object> visitorsApplyList(@RequestBody QueryPageParams<VisitorsApplyList> resources,Pageable pageable){
        SecurityUtils.CheckApiAuth(resources);
        Map<String,Object> array = new HashMap<>();
        if(StringUtils.equals(resources.getQuery().getType(),"1")){
            array = dmVisitorsApplyService.getVisApp2(resources.getQuery().getUserId(),pageable);
        } else if(StringUtils.equals(resources.getQuery().getType(),"2")){
            array = dmVisitorsApplyService.getVisitorVisitList(resources.getQuery().getPhone(),pageable);
        }

        return new BaseResponse<>(array);
    }

    @Log("获取微信公众号权限签名")
    @ApiOperation("获取微信公众号权限签名")
    @AnonymousPostMapping(value = "/getTicket")
    public BaseResponse<Object> getTicket(@RequestBody QueryPageParams<String> criteria){
        SecurityUtils.CheckApiAuth(criteria);
        return new BaseResponse<>(wxUtil.getTicket());
    }

}