package com.sptg.estate.biz.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.dto.AccessCardPushRecordsDto;

import com.sptg.estate.api.entity.AccessCardPushRecords;
import com.sptg.estate.api.entity.AccessFacePushRecords;
import com.sptg.estate.api.feigns.AccessCardPushRecordsFeign;
import com.sptg.estate.biz.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * title: AccessCardPushRecordsController
 * package: com.sptg.estate.biz.controller
 * description:授权下发记录 控制器
 *
 *
 *
 */
@RestController
@RequiredArgsConstructor
public class AccessCardPushRecordsController implements AccessCardPushRecordsFeign {

    private final BaseUserServiceInterface baseUserServiceInterface;
    private final AccessCardPushRecordsServiceInterface accessCardPushRecordsServiceInterface;
    private final DeviceFeign deviceFeign;

    /* -------------------------------------------------------------------------------------------------------------- */

    @Override
    @PostMapping(value = "/accessCardPushRecords/showAccessCardPushRecordsList")
    public ResultBean<Page<AccessCardPushRecords>> showAccessCardPushRecordsList(@RequestBody AccessCardPushRecordsDto accessCardPushRecordsDto) {
        return this.accessCardPushRecordsServiceInterface.showAccessCardPushRecordsList(accessCardPushRecordsDto);
    }

    private final UserServiceInterface userServiceInterface;

    /**
     * 添加一条用户授权下发记录
     * @param recordsDto 授权下发记录业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessCardPushRecords/addAccessCardPushRecords")
    public ResultBean<Boolean> addAccessCardPushRecords(@RequestBody AccessCardPushRecordsDto recordsDto) {
        Long userId = recordsDto.getUserId();
        Long deviceId = recordsDto.getDeviceId();
        Assert.notNull(userId, "用户ID为空，不能记录用户授权下发记录");
        Assert.notNull(deviceId, "设备ID为空，不能记录用户授权下发记录");
        AccessCardPushRecords records = this.buildAccessCardPushRecords(recordsDto);
        this.accessCardPushRecordsServiceInterface.addAccessCardPushRecords(records);
        return new ResultBean<>(ResultEnum.SUCCESS,true);
    }

    @Override
    @PostMapping(value = "/accessCardPushRecords/addAccessCardPushRecordsByDevices")
    public ResultBean<Boolean> addAccessCardPushRecordsByDevices(@RequestBody AccessCardPushRecordsDto recordsDto) {
        Long userId = recordsDto.getUserId();
        List<Long> deviceIdList = recordsDto.getDeviceIdList();
        Assert.notNull(userId, "用户ID为空，不能记录用户授权下发记录");
        Assert.notEmpty(deviceIdList, "没有下发的设备，不能记录用户授权下发记录");
        List<AccessCardPushRecords> recordsList = this.buildAccessCardPushRecordsList(recordsDto);
        Assert.notEmpty(recordsList, "没有下发的设备，不能记录用户授权下发记录");
        boolean result = this.accessCardPushRecordsServiceInterface.insertBatch(recordsList);
        return new ResultBean<>(ResultEnum.SUCCESS, result);
    }

    /**
     * 更新用户授权下发记录
     * @param recordsDto 授权下发记录业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessCardPushRecords/updateAccessCardPushRecords")
    public ResultBean<Boolean> updateAccessCardPushRecords(@RequestBody AccessCardPushRecordsDto recordsDto) {
        Long userId = recordsDto.getUserId();
        Assert.notNull(userId, "用户ID为空，不能记录用户授权下发记录");
        List<AccessCardPushRecords> accessCardPushRecordsList = this.getAccessCardPushRecordsList(recordsDto);
        Assert.notEmpty(accessCardPushRecordsList, "没有需要更新的记录");

        //如果是更新则更新有效时间
        if (recordsDto.getEnable() == OperationConstant.ONE){
            for(int i = 0; i < accessCardPushRecordsList.size(); i++){
                AccessCardPushRecords records = accessCardPushRecordsList.get(i);
                records.setBeginDate(recordsDto.getBeginDate());
                records.setEndDate(recordsDto.getEndDate());
            }
        }
        if(this.accessCardPushRecordsServiceInterface.updateBatchById(accessCardPushRecordsList)){
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, false);
    }

    /**
     * 完善授权下发业务对象（需要新增一条记录）
     * @param recordsDto
     */
    private AccessCardPushRecords buildAccessCardPushRecords(AccessCardPushRecordsDto recordsDto){
        AccessCardPushRecords records = new AccessCardPushRecords();
        BeanUtils.copyProperties(recordsDto, records);
        Date today = new Date();
        records.setAccessDate(today);
        records.setCreateDate(today);
        records.setBeginDate(recordsDto.getBeginDate());
        records.setEndDate(recordsDto.getEndDate());
        return records;
    }

    /**
     * 构建授权下发业务对象（需要新增多条记录或一条记录）
     * @param recordsDto
     */
    private List<AccessCardPushRecords> buildAccessCardPushRecordsList(AccessCardPushRecordsDto recordsDto){
        List<Long> deviceIdList = recordsDto.getDeviceIdList();
        Long deviceId= recordsDto.getDeviceId();
        if(deviceIdList != null && deviceIdList.size() > 0){
            List<AccessCardPushRecords> list = new ArrayList<>();
            deviceIdList.forEach(item -> {
                recordsDto.setDeviceId(item); //以deviceIdList内的设备ID为主
                list.add(this.buildAccessCardPushRecords(recordsDto));
            });
            return list;
        }else{
            if(deviceId != null){
                List<AccessCardPushRecords> list = new ArrayList<>();
                list.add(this.buildAccessCardPushRecords(recordsDto));
                return list;
            }else{
                return null;
            }
        }
    }

    /**
     * 更新授权下发记录（一条或者多条记录更新）
     * @param dto
     */
    private List<AccessCardPushRecords> getAccessCardPushRecordsList(AccessCardPushRecordsDto dto){
        // pushType 下发类型：1 仅人脸、2 仅门禁卡、 3 人脸和门禁卡
//        Integer pushType = dto.getPushType();
        Date today = new Date();
//        if(pushType.equals(OperationConstant.ONE)){
//            List<AccessCardPushRecords> recordsList = this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(dto.getUserId());
//            for(int i = 0; i < recordsList.size(); i++){
//                AccessCardPushRecords records = recordsList.get(i);
//                records.setFaceUri(dto.getFaceUri());
//                records.setAccessDate(today);
//            }
//            return recordsList;
//        }
//        else if(pushType.equals(OperationConstant.TWO)){
            List<AccessCardPushRecords> recordsList = this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(dto.getUserId());
            for(int i = 0; i < recordsList.size(); i++){
                AccessCardPushRecords records = recordsList.get(i);
                records.setCardNo(dto.getCardNo());
                records.setBeginDate(dto.getBeginDate());
                records.setEndDate(dto.getEndDate());
                records.setEnable(dto.getEnable());
                records.setAccessDate(today);
            }
            return recordsList;
//        }
//        else if(pushType.equals(OperationConstant.THREE)){
//            List<AccessCardPushRecords> recordsList = this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(dto.getUserId());
//            for(int i = 0; i < recordsList.size(); i++){
//                AccessCardPushRecords records = recordsList.get(i);
//                records.setFaceUri(dto.getFaceUri());
//                records.setCardNo(dto.getCardNo());
//                records.setAccessDate(today);
//            }
//            return recordsList;
//        }
//        return null;
    }

    @Override
    @PostMapping(value = "/accessCardPushRecords/addOrUpdateAccessCardPushRecords")
    public ResultBean<Boolean> addOrUpdateAccessCardPushRecords(@RequestBody AccessCardPushRecordsDto dto) {
        List<AccessCardPushRecords> pushRecords = this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(dto.getUserId());
        boolean result = this.accessCardPushRecordsServiceInterface.insert(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @GetMapping(value = "/accessCardPushRecords/findAccessCardPushRecordsById/{id}")
    public AccessCardPushRecords findAccessCardPushRecordsById(@PathVariable(value = "id") Long id) {
        return this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsById(id);
    }

    @Override
    public List<AccessCardPushRecords> findAccessCardPushRecordsByUserId(Long userId) {
        return this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(userId);
    }

    /**
     * 禁用门禁卡
     * @param accessCardPushRecordsDto 授权下发记录业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessCardPushRecords/deleteAccessCardPushRecords")
    public ResultBean<Boolean> deleteAccessCardPushRecords(@RequestBody AccessCardPushRecordsDto accessCardPushRecordsDto) {
        List<AccessCardPushRecords> dellist = this.accessCardPushRecordsServiceInterface.findAccessCardPushRecordsByUserId(accessCardPushRecordsDto.getUserId());
        List<Long> delIds = new ArrayList<>();
        dellist.forEach(del -> {
            delIds.add(del.getId());
        });
        if(delIds.size() > 0){
            if(this.accessCardPushRecordsServiceInterface.deleteBatchIds(delIds)){
                return new ResultBean<>(ResultEnum.SUCCESS, true);
            }else{
                return new ResultBean<>(ResultEnum.ERROR, false);
            }
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
        /*for(int i = 0; i < dellist.size(); i++){
            dellist.get(0).setEnable(OperationConstant.TWO);
        }
        if(this.accessCardPushRecordsServiceInterface.updateBatchById(dellist)){
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }else{
            return new ResultBean<>(ResultEnum.ERROR, false);
        }*/
    }

    @Override
    @PostMapping(value = "/accessCardPushRecords/getAccessCardPushRecordsCount")
    public Long getAccessCardPushRecordsCount(@RequestBody AccessCardPushRecordsDto accessCardPushRecordsDto) {
        return this.accessCardPushRecordsServiceInterface.getAccessCardPushRecordsCount(accessCardPushRecordsDto);
    }

    @Override
    @PostMapping(value = "/accessCardPushRecords/getListByUserId/{userId}/{accessUserType}/{specialDevice}")
    public ResultBean<AccessCardPushRecords> getListByUserId(@PathVariable("userId") Long userId, @PathVariable("accessUserType") Integer accessUserType, @PathVariable("specialDevice") Integer specialDevice) {
        return this.accessCardPushRecordsServiceInterface.getListByUserId(userId, accessUserType, specialDevice);
    }

}
