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.AccessFacePushRecordsDto;
import com.sptg.estate.api.entity.AccessFacePushRecords;
import com.sptg.estate.api.feigns.AccessFacePushRecordsFeign;
import com.sptg.estate.biz.service.AccessFacePushRecordsServiceInterface;
import com.sptg.estate.biz.service.AccessFacePushRecordsServiceInterface;
import com.sptg.estate.biz.service.BaseUserServiceInterface;
import com.sptg.estate.biz.service.UserServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    private final BaseUserServiceInterface baseUserServiceInterface;
    private final AccessFacePushRecordsServiceInterface accessFacePushRecordsServiceInterface;
    private final DeviceFeign deviceFeign;

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

    @Override
    @PostMapping(value = "/accessFacePushRecords/showAccessFacePushRecordsList")
    public ResultBean<Page<AccessFacePushRecords>> showAccessFacePushRecordsList(@RequestBody AccessFacePushRecordsDto accessFacePushRecordsDto) {
        return this.accessFacePushRecordsServiceInterface.showAccessFacePushRecordsList(accessFacePushRecordsDto);
    }

    private final UserServiceInterface userServiceInterface;

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

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

    /**
     * 更新用户授权下发记录
     * @param accessFacePushRecordsDto 授权下发记录业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessFacePushRecords/updateAccessFacePushRecords")
    public ResultBean<Boolean> updateAccessFacePushRecords(@RequestBody AccessFacePushRecordsDto accessFacePushRecordsDto) {
        Long userId = accessFacePushRecordsDto.getUserId();
        Assert.notNull(userId, "用户ID为空，不能记录用户授权下发记录");
        List<AccessFacePushRecords> accessFacePushRecordsList = this.getAccessFacePushRecordsList(accessFacePushRecordsDto);
        Assert.notEmpty(accessFacePushRecordsList, "没有需要更新的记录");

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

    /**
     * 完善授权下发业务对象（需要新增一条记录）
     * @param recordsDto
     */
    private AccessFacePushRecords buildAccessFacePushRecords(AccessFacePushRecordsDto recordsDto){
        AccessFacePushRecords records = new AccessFacePushRecords();
        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<AccessFacePushRecords> buildAccessFacePushRecordsList(AccessFacePushRecordsDto recordsDto){
        List<Long> deviceIdList = recordsDto.getDeviceIdList();
        Long deviceId= recordsDto.getDeviceId();
        if(deviceIdList != null && deviceIdList.size() > 0){
            List<AccessFacePushRecords> list = new ArrayList<>();
            deviceIdList.forEach(item -> {
                recordsDto.setDeviceId(item); //以deviceIdList内的设备ID为主
                list.add(this.buildAccessFacePushRecords(recordsDto));
            });
            return list;
        }else{
            if(deviceId != null){
                List<AccessFacePushRecords> list = new ArrayList<>();
                list.add(this.buildAccessFacePushRecords(recordsDto));
                return list;
            }else{
                return null;
            }
        }
    }

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

    @Override
    @PostMapping(value = "/accessFacePushRecords/addOrUpdateAccessFacePushRecords")
    public ResultBean<Boolean> addOrUpdateAccessFacePushRecords(@RequestBody AccessFacePushRecordsDto dto) {
        List<AccessFacePushRecords> pushRecords = this.accessFacePushRecordsServiceInterface.findAccessFacePushRecordsByUserId(dto.getUserId());
        boolean result = this.accessFacePushRecordsServiceInterface.insert(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @GetMapping(value = "/accessFacePushRecords/findAccessFacePushRecordsById/{id}")
    public AccessFacePushRecords findAccessFacePushRecordsById(@PathVariable(value = "id") Long id) {
        return this.accessFacePushRecordsServiceInterface.findAccessFacePushRecordsById(id);
    }

    @Override
    public List<AccessFacePushRecords> findAccessFacePushRecordsByUserId(Long userId) {
        return this.accessFacePushRecordsServiceInterface.findAccessFacePushRecordsByUserId(userId);
    }

    @Override
    @PostMapping(value = "/accessFacePushRecords/deleteAccessFacePushRecords")
    public ResultBean<Boolean> deleteAccessFacePushRecords(@RequestBody AccessFacePushRecordsDto accessFacePushRecordsDto) {
        Long userId = accessFacePushRecordsDto.getUserId();
        Integer accessUserType = accessFacePushRecordsDto.getAccessUserType();
        ResultBean<AccessFacePushRecords> resultBean = this.accessFacePushRecordsServiceInterface.getListByUserId(userId, accessUserType, null);
        List<AccessFacePushRecords> pushList = resultBean.getList();
        if(pushList != null && pushList.size() > 0){
            List<Long> delIds = new ArrayList<>();
            pushList.forEach(del ->{
                delIds.add(del.getId());
            });
            if(this.accessFacePushRecordsServiceInterface.deleteBatchIds(delIds)){
                return new ResultBean<>(ResultEnum.SUCCESS, true);
            }else{
                return new ResultBean<>(ResultEnum.ERROR, false);
            }
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
    }

    @Override
    @PostMapping(value = "/accessFacePushRecords/getAccessFacePushRecordsCount")
    public Long getAccessFacePushRecordsCount(@RequestBody AccessFacePushRecordsDto accessFacePushRecordsDto) {
        return this.accessFacePushRecordsServiceInterface.getAccessFacePushRecordsCount(accessFacePushRecordsDto);
    }

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

}
