package com.usky.meeting.controller.web;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.meeting.annotation.FaceLog;
import com.usky.meeting.domain.MeetingFace;
import com.usky.meeting.domain.SysDept;
import com.usky.meeting.mapper.MeetingFaceMapper;
import com.usky.meeting.mapper.SysDeptMapper;
import com.usky.meeting.repository.MeetingInfoRepository;
import com.usky.meeting.service.MeetingFaceService;
import com.usky.meeting.service.vo.DmpDeviceInfoVO;
import com.usky.meeting.service.vo.FaceResultVO;
import com.usky.meeting.service.vo.MeetingFaceRequestVO;
import com.usky.meeting.service.vo.MeetingFaceVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyj
 * @since 2024-03-08
 */
@RestController
@RequestMapping("/meetingFace")
@Api("人脸验证接口")
@Slf4j
public class MeetingFaceController {
    @Autowired
    MeetingFaceService faceService;
    @Autowired
    MeetingInfoRepository meetingInfoRepository;
    @Autowired
    private MeetingFaceMapper meetingFaceMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @PostMapping("/vef")
    @ApiOperation(value="人脸验证", notes="根据传入的base64编码和数据的base64编码进行对比")
    @FaceLog
    public MeetingFaceVO faceVef(@RequestBody MeetingFaceRequestVO requestVO){
        return faceService.vef(requestVO);
    }

    @GetMapping("/faceList")
    @ApiOperation(value = "人脸列表",notes = "查询所有的人脸信息")
    public ApiResult<CommonPage<MeetingFace>> faceList(
            @RequestParam Integer current,
            @RequestParam Integer size,
            @RequestParam(required = false) String faceName,
            @RequestParam(required = false) String faceStatus,
            @RequestParam(required = false) Integer fid,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer deptId
    ){
        IPage<MeetingFace> page = faceService.page(new Page(current, size), new QueryWrapper<MeetingFace>()
                .like(StrUtil.isNotBlank(faceName),"face_name",faceName)
                .like(StrUtil.isNotBlank(faceStatus),"face_status",faceStatus)
                .eq(fid != null,"fid",fid)
                .eq(userId != null,"user_id",userId)
                .eq(deptId != null,"dept_id",deptId)
                .eq("tenant_id", SecurityUtils.getTenantId()));
        if(page.getRecords().size() > 0){
//            for (int i = 0; i < page.getRecords().size(); i++) {
//                if(Objects.nonNull(page.getRecords().get(i).getBindDevice()) || StringUtils.isNotBlank(page.getRecords().get(i).getBindDevice())){
//                    String[] deviceIdStr = page.getRecords().get(i).getBindDevice().split(",");
//                    Integer[] deviceIds = Arrays.stream(deviceIdStr).map(Integer::parseInt).toArray(Integer[]::new);
//                    List<DmpDeviceInfoVO> list = meetingFaceMapper.getDeviceInfo(Arrays.asList(deviceIds));
//                    page.getRecords().get(i).setDeviceInfos(list);
//
//                }
//            }

            QueryWrapper<SysDept> queryWrapper = Wrappers.query();
            queryWrapper.eq("del_flag",0).eq("tenant_id",SecurityUtils.getTenantId());
            List<SysDept> sysDeptList = sysDeptMapper.selectList(queryWrapper);
            if(sysDeptList.size() > 0){
                for (int i = 0; i < page.getRecords().size(); i++) {
                    Integer deptId1 = page.getRecords().get(i).getDeptId();
                    for (int j = 0; j < sysDeptList.size(); j++) {
                        if(deptId1.equals(Integer.valueOf(sysDeptList.get(j).getDeptId().toString()))){
                            page.getRecords().get(i).setSysDept(sysDeptList.get(j));
                            break;
                        }
                    }

                }
            }

        }
        return ApiResult.success(new CommonPage<>(page.getRecords(),page.getTotal(),size,current));
    }


    @GetMapping("/faceDelete/{fid}")
    @ApiOperation(value = "删除人脸",notes = "根据id进行删除")
    public FaceResultVO faceDelete(@PathVariable Integer fid){
        faceService.removeById(fid);
        meetingInfoRepository.delMeetingFaceDevice(fid);
        return FaceResultVO.success("删除成功");
    }

    @GetMapping("/info/{fid}")
    @ApiOperation(value = "查询方法",notes = "根据id查询人脸信息")
    public FaceResultVO info(@PathVariable Integer fid){
        return FaceResultVO.success(faceService.getById(fid));
    }

    @PostMapping("/save")
    @ApiOperation(value = "添加")
    public FaceResultVO save(@RequestBody MeetingFace face){
        Long userId = face.getUserId();
        LambdaQueryWrapper<MeetingFace> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MeetingFace::getUserId,userId);
        List<MeetingFace> list = faceService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            throw new BusinessException("人员已绑定，请检查");
        }

        face.setVefNum(0);
        face.setCreateTime(LocalDateTime.now());
        face.setTenantId(SecurityUtils.getTenantId());
        String[] devicefids = new String[0];
        if(Objects.nonNull(face.getBindDevice()) || StringUtils.isNotBlank(face.getBindDevice())){
            devicefids = face.getBindDevice().split(",");
        }
        faceService.save(face);
        if(devicefids.length > 0){
            for (int i = 0; i < devicefids.length; i++) {
                meetingInfoRepository.insertMeetingFaceDevice(face.getFid(),Integer.parseInt(devicefids[i]));
            }
        }
        return FaceResultVO.success("添加成功");
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public FaceResultVO update(@RequestBody MeetingFace face){
        faceService.updateById(face);
        meetingInfoRepository.delMeetingFaceDevice(face.getFid());
        String[] devicefids = new String[0];
        if(Objects.nonNull(face.getBindDevice()) || StringUtils.isNotBlank(face.getBindDevice())){
            devicefids = face.getBindDevice().split(",");
        }
        if(devicefids.length > 0){
            for (int i = 0; i < devicefids.length; i++) {
                meetingInfoRepository.insertMeetingFaceDevice(face.getFid(),Integer.parseInt(devicefids[i]));
            }
        }
        return FaceResultVO.success("修改成功");
    }
}

