package com.sptg.gateway.controller.permissions;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.constant.DeviceConstants;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.device.api.feigns.DevicePathFeign;
import com.sptg.estate.api.dto.BaseUser;
import com.sptg.estate.api.entity.AccessCardPushRecords;
import com.sptg.estate.api.entity.AccessFacePushRecords;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.feigns.AccessCardPushRecordsFeign;
import com.sptg.estate.api.feigns.AccessFacePushRecordsFeign;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.permissions.api.dto.DeviceAuthorizeDto;
import com.sptg.permissions.api.dto.RegionAuthorizeDto;
import com.sptg.permissions.api.dto.RegionDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.DeviceAuthorize;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.entity.Region;
import com.sptg.permissions.api.feigns.DeviceAuthorizeFeign;
import com.sptg.permissions.api.feigns.RegionAuthorizeFeign;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * title: DeviceAuthorizeController
 * package: com.sptg.gateway.controller.permissions
 * description: 设备授权控制器
 *
 *
 *
 */
@RestController
@AllArgsConstructor
public class DeviceAuthorizeController {

    /* -------------------------------------------------- 接口注入 -------------------------------------------------- */

    private final DeviceFeign deviceFeign;
    private final UnitFeign unitFeign;
    private final RegionAuthorizeFeign regionAuthorizeFeign;
    private final DeviceAuthorizeFeign deviceAuthorizeFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final AccessCardPushRecordsFeign accessCardPushRecordsFeign;
    private final AccessFacePushRecordsFeign accessFacePushRecordsFeign;

    /* --------------------------------------------------- 控制器 --------------------------------------------------- */

    /**
     * 功能描述: 分页查询授权的单元列表
     * @param dto
     * {
     *     selectedType :   选填,{ 1：机构,2：小区 }
     *     selectedId   :   选填
     * }
     * @param pageBean 分页条件
     * @return ResultBean<Page>
     *
     *
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/device/authorize/dy/pagingQuery")
    public ResultBean<Page> pagingQueryDy(DeviceAuthorizeDto dto,PageBean<DeviceAuthorize,DeviceAuthorizeDto> pageBean){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        //  字段校验
        ResultBean.BaseResultEnum result = checkParameter(dto,onLineUser);
        if (null != result){
            return new ResultBean<>(result,pageBean);
        }
        pageBean.setDto(dto);
        //判断是不是单元列表的下拉  等于1则是单元列表的下拉
        if (null != dto.getIsUnitList() && dto.getIsUnitList()==1){
            pageBean.setSize(99);
        }
        // 分页查询
        Page<DeviceAuthorize> page = this.deviceAuthorizeFeign.pagingQueryDy(pageBean);
        if (page.getTotal() > OperationConstant.ZERO) {
            //  获取单元Id列表
            List<Long> dyIdList = page.getRecords().stream().map(DeviceAuthorize::getDyId).collect(Collectors.toList());
            List<Unit> unitList = this.unitFeign.getListByIdListAndUnitName(dyIdList,dto.getUnitName());
            //判断机构数选择的小区或者机构
            //  构建返回值
            Page<Unit> unitPage = new Page<>(page.getCurrent(), page.getSize());
            unitPage.setTotal(page.getTotal());
            unitPage.setRecords(unitList);
            return new ResultBean<>(ResultEnum.SUCCESS,unitPage);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    private ResultBean.BaseResultEnum checkParameter(DeviceAuthorizeDto dto, Account onLineUser){
        if (null == dto){
            dto = new DeviceAuthorizeDto();
        }else {
            //  判断是否选中某个小区或机构
            if (null != dto.getSelectedId()) {
                if (null == dto.getSelectedType()) {
                    return ResultEnum.PARAMETER_ANOMALY;
                }
                //  判断选中的是小区还是机构
                switch (dto.getSelectedType()) {
                    //  机构
                    case OperationConstant.ONE:
                        //  获取此机构下的小区列表
                        RegionAuthorizeDto regionDto = new RegionAuthorizeDto();
                        regionDto.setOrgPosition(onLineUser.getOrgPosition());
                        regionDto.setPid(dto.getSelectedId());
                        List<Organization> orgList = this.regionAuthorizeFeign.getAuthorizeOrgList(regionDto);
                        if (orgList.size() == OperationConstant.ZERO) {
                            return ResultEnum.SUCCESS;
                        }
                        //  获取Id列表
                        List<Long> idList = orgList.stream().map(Organization::getId).collect(Collectors.toList());
                        dto.setXqIdList(idList);
                        break;
                    //  小区
                    case OperationConstant.TWO:
                        List<Long> xqIdList = new ArrayList<>(1);
                        xqIdList.add(dto.getSelectedId());
                        dto.setXqIdList(xqIdList);
                        break;
                    //  单元
                    case OperationConstant.THREE:
                        dto.setDyId(dto.getSelectedId());
                        break;
                    default:
                        return ResultEnum.PARAMETER_ANOMALY;
                }
            }
        }
        dto.setOrgPosition(onLineUser.getOrgPosition());
        return null;
    }

    /**
     * 功能描述: 分页查询授权的单元列表
     * @param dto
     * {
     *     selectedType :   选填,{ 1：机构,2：小区,3：单元 }
     *     selectedId   :   选填
     * }
     * @param pageBean 分页条件
     * @return ResultBean<Page>
     *
     *
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/device/authorize/pagingQuery")
    public ResultBean<Page> pagingQuery(DeviceAuthorizeDto dto,PageBean<DeviceAuthorize,DeviceAuthorizeDto> pageBean){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        //  字段校验
        ResultBean.BaseResultEnum result = checkParameter(dto,onLineUser);
        if (null != result){
            return new ResultBean<>(result,pageBean);
        }
        pageBean.setDto(dto);
        //  分页查询
        Page<DeviceAuthorize> page = this.deviceAuthorizeFeign.pagingQuery(pageBean);
        return result(page);
    }

    /**
     * 功能描述: 分页查询设置子特殊授权位置上的设备
     * @param dto
     * {
     *     selectedType :   选填,{ 1：机构,2：小区,3：单元 }
     *     selectedId   :   选填
     * }
     * @param pageBean 分页条件
     * @return ResultBean<Page>
     *
     *
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/device/specialAuthorize/pagingQuery")
    public ResultBean<Page> specialDevicesPagingQuery( DeviceAuthorizeDto dto, PageBean<DeviceAuthorize,DeviceAuthorizeDto> pageBean){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        //  字段校验
        ResultBean.BaseResultEnum result = checkParameter(dto,onLineUser);
        if (null != result){
            return new ResultBean<>(result,pageBean);
        }
        List<Device> devices = deviceFeign.getSpecialListByPathUse(dto.getXqId(), DeviceConstants.DEVICE_ACCESS_TYPE_SPECIAL);

        //判断选择的下发类型
        //0为全部  1为仅人脸   2为仅卡片
        if (dto.getPushMaterial() == null){
            dto.setPushMaterial(1);
        }
        switch (dto.getPushMaterial()){
//            case 0 :
//                //根据用户ID和用户类型获取卡片和人脸识别下发记录表的记录。
//                ResultBean<AccessCardPushRecords> accessCardPushRecordsResultBean0 = accessCardPushRecordsFeign.getListByUserId(dto.getUserId(), dto.getUserType());
//                ResultBean<AccessFacePushRecords> accessFacePushRecordsResultBean0 = accessFacePushRecordsFeign.getListByUserId(dto.getUserId(), dto.getUserType());
//                if (accessCardPushRecordsResultBean0.getList() != null && accessFacePushRecordsResultBean0.getList() != null){
//                    List<AccessCardPushRecords> accessCardPushRecordsList = accessCardPushRecordsResultBean0.getList();
//                    List<AccessFacePushRecords> accessFacePushRecordsList = accessFacePushRecordsResultBean0.getList();
//                    for (AccessCardPushRecords accessCardPushRecord : accessCardPushRecordsList){
//                        for (AccessFacePushRecords accessFacePushRecord : accessFacePushRecordsList){
//                            //如果两个表中都有同一个设备的记录，则在设备列表移除该设备。
//                            devices.removeIf(device -> device.getId().equals(accessCardPushRecord.getDeviceId()) && device.getId().equals(accessFacePushRecord.getDeviceId()));
//                        }
//                    }
//                }
//                break;
            case 1 :
                //移除不支持人脸识别的设备，保证前端特殊下发的设备是没有下发过的
                devices.removeIf(device -> device.getHaveFace() != 1);
                //根据用户ID和用户类型获取人脸识别下发记录表的记录
                ResultBean<AccessFacePushRecords> accessFacePushRecordsResultBean1 = accessFacePushRecordsFeign.getListByUserId(dto.getUserId(), dto.getUserType(), null);
                if (accessFacePushRecordsResultBean1.getList() != null){
                    List<AccessFacePushRecords> accessFacePushRecordsList = accessFacePushRecordsResultBean1.getList();
                    for (AccessFacePushRecords accessFacePushRecord : accessFacePushRecordsList){
                        //如果设备列表中有人脸识别下发记录表中设备的记录，则在设备列表移除该设备。
                        devices.removeIf(device -> device.getId().equals(accessFacePushRecord.getDeviceId()));
                    }
                }
                break;
            case 2 :
                //根据用户ID和用户类型获取卡片下发记录表的记录
                ResultBean<AccessCardPushRecords> accessCardPushRecordsResultBean2 = accessCardPushRecordsFeign.getListByUserId(dto.getUserId(), dto.getUserType(),null);
                if (accessCardPushRecordsResultBean2.getList() != null){
                    List<AccessCardPushRecords> accessCardPushRecordsList = accessCardPushRecordsResultBean2.getList();
                    for (AccessCardPushRecords accessCardPushRecord : accessCardPushRecordsList){
                        //如果设备列表中有卡片下发记录表中设备的记录，则在设备列表移除该设备。
                        devices.removeIf(device -> device.getId().equals(accessCardPushRecord.getDeviceId()));
                    }
                }
                break;
        }

        List<Long> deviceIdList = new ArrayList<>();
        devices.forEach(device -> {
            deviceIdList.add(device.getId());
        });
        dto.setDeviceIdList(deviceIdList);
        pageBean.setDto(dto);
        //  分页查询
        Page<DeviceAuthorize> page = this.deviceAuthorizeFeign.specialDevicesPagingQuery(pageBean);
        return result(page);
    }

    private ResultBean<Page> result(Page<DeviceAuthorize> page){
        if (page.getTotal() > OperationConstant.ZERO){
            //  获取设备Id列表
            List<Long> deviceIdList = page.getRecords().stream().map(DeviceAuthorize::getDeviceId).collect(Collectors.toList());
            //  获取设备设备列表
            List<Device> deviceList = this.deviceFeign.getListByIds(deviceIdList);
            //  构建返回值
            Page<Device> unitPage = new Page<>(page.getCurrent(), page.getSize());
            unitPage.setTotal(page.getTotal());
            unitPage.setRecords(deviceList);
            return new ResultBean<>(ResultEnum.SUCCESS,unitPage);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/device/authorize/region/pagingQuery")
    public ResultBean<Page> pagingQueryRegion(RegionDto dto, PageBean<Region,RegionDto> pageBean){
        dto = null == dto ? new RegionDto() : dto;
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        pageBean.setDto(dto);
        //  分页查询
        Page<Region> page = this.deviceAuthorizeFeign.pagingQueryRegion(pageBean);
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }
}
