package com.ics.admin.controller.meeting;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ics.admin.domain.Customer;
import com.ics.admin.domain.Park;
import com.ics.admin.domain.Room;
import com.ics.admin.domain.meeting.*;
import com.ics.admin.service.ICustomerService;
import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.admin.service.IParkService;
import com.ics.admin.service.meeting.*;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.core.domain.dto.DevicePersonDto;
import com.ics.common.core.domain.dto.FacesDto;
import com.ics.common.utils.DateUtils;
import com.ics.common.utils.DeviceUtils;
import com.ics.common.utils.RandomUtil;
import com.ics.common.utils.UrlToBase64Util;
import com.ics.system.domain.Tenant;
import com.ics.system.domain.User;
import com.ics.system.service.ICurrentUserService;
import com.ics.system.service.ITenantService;
import com.ics.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ics.common.core.domain.R;
import com.ics.common.core.controller.BaseController;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;
import org.wf.jwtp.util.SubjectUtil;

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

import static java.util.stream.Collectors.toList;

/**
 * 访客预约表 提供者
 *
 * @author chen
 * @date 2024-02-25
 */
@RestController
@RequestMapping("/meeting/visitorPerson")
public class VisitorPersonController extends BaseController {

    @Autowired
    private IVisitorPersonService visitorPersonService;

    @Autowired
    private IIcsCustomerStaffService staffService;

    @Autowired
    private ICustomerService customerService;



    @Autowired
    private ICurrentUserService currentUserService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IEquipmentService equipmentService;

    @Autowired
    private IParkService parkService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IUserEquipmentService userEquipmentService;

    @Autowired
    private IDetailEquipmentService detailEquipmentService;

    @Value("${dfs.domain}")
    private String url;

    private static final String BASE64_PREFIX = "data:image/png;base64,";



    /**
     * 查询预约参观人员
     */
    @Ignore
    @GetMapping("get/{id}")
    public VisitorPerson get(@PathVariable("id") Long id) {
        VisitorPerson visitorPerson = visitorPersonService.selectReservationPersonById(id);
        IcsCustomerStaff customerStaff = staffService.selectIcsCustomerStaffById(visitorPerson.getIntervieweeId());
        if (null != customerStaff) {
            visitorPerson.setIntervieweeName(customerStaff.getUsername());
        }
        IcsCustomerStaff customerStaff1 = staffService.selectIcsCustomerStaffById(visitorPerson.getUserId());

        Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
        if (null != customer) {
            visitorPerson.setCustomerName(customer.getName());
        }

        Park park = parkService.selectParkById(visitorPerson.getParkId());
        if (park !=null ){
            visitorPerson.setParkName(park.getName());
        }

        Tenant tenant = tenantService.selectTenantById(visitorPerson.getTenantId());
        if (tenant !=null ){
            visitorPerson.setTenantName(tenant.getName());
        }
        return visitorPerson;
    }

    /**
     * 查询预约参观人员列表
     */
    @RequiresPermissions("meeting:visitorPerson:list")
    @GetMapping("list")
    public R list(VisitorPerson visitorPerson) {
        startPage();
        boolean isAdmin = SubjectUtil.hasRole(getRequest(),"manager");
        if (isAdmin){
            Long parkId = currentUserService.getParkId();
            Long tenantId = currentUserService.getTenantId();
            visitorPerson.setParkId(parkId);
//            visitorPerson.setTenantId(tenantId);
        }
        boolean b = SubjectUtil.hasRole(getRequest(),"admin");
        if (b){
            User user = userService.selectUserById(getCurrentUserId());
            if (null != user.getCustomerId()){
                Customer customer = customerService.selectCustomerById(user.getCustomerId());
                if (null != customer){
                    List<IcsCustomerStaff> icsCustomerStaffs = staffService.selectUserByCustomer(customer.getId());
                    List<Long> ids = icsCustomerStaffs.stream().map(item -> {
                        return item.getId();
                    }).collect(Collectors.toList());
                    visitorPerson.setStaffIds(ids);
                }
            }
        }
        return result(visitorPersonService.selectReservationPersonList(visitorPerson));
    }


    /**
     * 新增保存预约参观人员
     */
    @RequiresPermissions("meeting:visitorPerson:add")
    @PostMapping("save")
    public R addSave(@RequestBody VisitorPerson visitorPerson) {


        Assert.isTrue(IdcardUtil.isValidCard(visitorPerson.getCardNo()), "身份证格式不正确");
        Assert.isTrue(Validator.isMobile(visitorPerson.getPhone()), "手机号格式不正确");

        IcsCustomerStaff customerStaff = staffService.selectUserByMobile(visitorPerson.getPhone());
        System.out.println("用户信息为+++++++++++++++++++++++"+customerStaff.getId());
        visitorPerson.setIntervieweeId(customerStaff.getId());
        visitorPerson.setUserId(visitorPerson.getUserId());
        long currentUserId = this.getCurrentUserId();

        visitorPerson.setStatus(1);
        visitorPerson.setCreateTime(DateUtils.getNowDate());
        System.out.println("当前登录人的信息为+++++++++++++++++++++++");
        visitorPerson.setCreateBy(getLoginName());
        visitorPerson.setUpdateTime(DateUtils.getNowDate());
        visitorPerson.setUpdateBy(getLoginName());

        visitorPerson.setUserId(Long.valueOf(RandomUtil.randomInt(10)));
        int i = visitorPersonService.insertReservationPerson(visitorPerson);
        if (i > 0) {
            Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
            String roomId = customer.getRoomId();
            String buildId = customer.getBuildId();
            List<Long> result = new ArrayList<>();

            List<String> roomIds = StrUtil.split(roomId, ',');
            List<String> buildIds = StrUtil.split(buildId, ',');

            System.out.println("楼层id为-------------"+buildIds);
            List<Long> collect = roomIds.stream().map(Long::valueOf).collect(Collectors.toList());
            List<Long> buildCollect = buildIds.stream().map(Long::valueOf).collect(toList());
            result.addAll(buildCollect);
            result.addAll(collect);
            System.out.println("所有设备id-------------"+result);

            //获取了房间集合，循环对应集合，
            for (Long aLong : result) {
                //根据楼层获取设备id
                List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(aLong);
                for (DetailEquipment detailEquipment : detailEquipments) {
                    //根据设备id获取设备
                    Equipment equipment = equipmentService.selectEquipmentById(detailEquipment.getEquipmentId());
                    if (equipment != null) {
                        String persons = DeviceUtils.queryPersons(equipment.getIp(), String.valueOf(visitorPerson.getIntervieweeId()));
                        JSONObject jsonObject = JSONUtil.parseObj(persons);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount <= 0) {
                            //添加 用户和对应的设备
                            UserEquipment userEquipment = new UserEquipment();
                            userEquipment.setEquipmentId(equipment.getId());
                            userEquipment.setUserId(visitorPerson.getIntervieweeId());
                            userEquipment.setStartTime(customer.getStartDate());
                            userEquipment.setEndDate(customer.getEndDate());
                            userEquipmentService.insertUserEquipment(userEquipment);


                            DevicePersonDto devicePersonDto = new DevicePersonDto();
                            ArrayList<FacesDto> facesDtos = new ArrayList<>();
                            devicePersonDto.setPersonId(String.valueOf(visitorPerson.getUserId()));
                            devicePersonDto.setName(visitorPerson.getName());
                            devicePersonDto.setPhone(String.valueOf(visitorPerson.getPhone()));
                            devicePersonDto.setCertificateType("111");
                            devicePersonDto.setCertificateNumber(visitorPerson.getCardNo());
                            //添加人员类型
                            devicePersonDto.setPersonType("whitelist");
                            //添加访客时间
                            FacesDto facesDto = new FacesDto();
                            facesDto.setFaceId(String.valueOf(visitorPerson.getUserId()));
                            String photoUrl = url + visitorPerson.getPhoto();
                            String faceData = BASE64_PREFIX + UrlToBase64Util.imageUrlToBase64(photoUrl);

                            facesDto.setData(faceData);
                            facesDtos.add(facesDto);
                            devicePersonDto.setFaces(facesDtos);
                            String s = DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                            System.out.println("新增楼层人员结果：" + s);
                        }
                    }
                }


                //根据房间id获取设备id
                List<RoomEquipment> roomEquipments = roomEquipmentService.selectListByRoomId(aLong);
                for (RoomEquipment roomEquipment : roomEquipments) {
                    //根据设备id获取设备
                    Equipment equipment = equipmentService.selectEquipmentById(roomEquipment.getEquipmentId());
                    if (equipment != null) {
                        String s = DeviceUtils.queryPersons(equipment.getIp(), String.valueOf(visitorPerson.getIntervieweeId()));
                        JSONObject jsonObject = JSONUtil.parseObj(s);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount > 0) {
                            //todo 需要修改  到底是按照访客时间。
                            return toAjax(1);
                        }
                        //添加 用户和对应的设备
                        UserEquipment userEquipment = new UserEquipment();
                        userEquipment.setEquipmentId(equipment.getId());
                        userEquipment.setUserId(visitorPerson.getIntervieweeId());
                        userEquipment.setStartTime(customer.getStartDate());
                        userEquipment.setEndDate(customer.getEndDate());
                        userEquipmentService.insertUserEquipment(userEquipment);

                        //往设备添加对应的人脸数据
                        DevicePersonDto devicePersonDto = new DevicePersonDto();
                        ArrayList<FacesDto> facesDtos = new ArrayList<>();
                        devicePersonDto.setPersonId(String.valueOf(visitorPerson.getUserId()));
                        devicePersonDto.setName(visitorPerson.getName());
                        devicePersonDto.setPhone(String.valueOf(visitorPerson.getPhone()));
                        devicePersonDto.setCertificateType("111");
                        devicePersonDto.setCertificateNumber(visitorPerson.getCardNo());
                        //添加人员类型
                        devicePersonDto.setPersonType("visitor");
                        //添加访客时间
                        devicePersonDto.setVisitorValidStartTime(DateUtil.format(visitorPerson.getVisitTime(), "yyyy-MM-dd'T'HH:mm:ss"));
                        devicePersonDto.setVisitorValidEndTime(DateUtil.format(visitorPerson.getLeaveTime(), "yyyy-MM-dd'T'HH:mm:ss"));
                        FacesDto facesDto = new FacesDto();
                        facesDto.setFaceId(String.valueOf(visitorPerson.getUserId()));
                        String photoUrl = url + visitorPerson.getPhoto();
                        String faceData = BASE64_PREFIX + UrlToBase64Util.imageUrlToBase64(photoUrl);
                        facesDto.setData(faceData);
                        facesDtos.add(facesDto);
                        devicePersonDto.setFaces(facesDtos);
                        DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                    }
                }
            }
        }

        return toAjax(i);
    }

    /**
     * 修改保存预约参观人员
     */
    @RequiresPermissions("meeting:visitorPerson:edit")
    @PostMapping("update")
    public R editSave(@RequestBody VisitorPerson visitorPerson) {

//        if (null != visitorPerson.getStatus()) {
//            Long loginCustomerId = this.getLoginCustomerId();
//
//            if (loginCustomerId != null) {
//                visitorPerson.setReviewersTime(new Date());
//            }
//        }

        if (visitorPerson.getStatus() == 1){
            Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
            String roomId = customer.getRoomId();
            String buildId = customer.getBuildId();
            List<Long> result = new ArrayList<>();

            List<String> roomIds = StrUtil.split(roomId, ',');
            List<String> buildIds = StrUtil.split(buildId, ',');

            System.out.println("楼层id为-------------"+buildIds);
            List<Long> collect = roomIds.stream().map(Long::valueOf).collect(Collectors.toList());
            List<Long> buildCollect = buildIds.stream().map(Long::valueOf).collect(toList());
            result.addAll(buildCollect);
            result.addAll(collect);
            System.out.println("所有设备id-------------"+result);

            //获取了房间集合，循环对应集合，
            for (Long aLong : result) {
                //根据楼层获取设备id
                List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(aLong);
                for (DetailEquipment detailEquipment : detailEquipments) {
                    //根据设备id获取设备
                    Equipment equipment = equipmentService.selectEquipmentById(detailEquipment.getEquipmentId());
                    if (equipment != null) {
                        String persons = DeviceUtils.queryPersons(equipment.getIp(), String.valueOf(visitorPerson.getIntervieweeId()));
                        JSONObject jsonObject = JSONUtil.parseObj(persons);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount <= 0) {
                            //添加 用户和对应的设备
                            UserEquipment userEquipment = new UserEquipment();
                            userEquipment.setEquipmentId(equipment.getId());
                            userEquipment.setUserId(visitorPerson.getIntervieweeId());
                            userEquipment.setStartTime(customer.getStartDate());
                            userEquipment.setEndDate(customer.getEndDate());
                            userEquipmentService.insertUserEquipment(userEquipment);


                            DevicePersonDto devicePersonDto = new DevicePersonDto();
                            ArrayList<FacesDto> facesDtos = new ArrayList<>();
                            devicePersonDto.setPersonId(String.valueOf(visitorPerson.getUserId()));
                            devicePersonDto.setName(visitorPerson.getName());
                            devicePersonDto.setPhone(String.valueOf(visitorPerson.getPhone()));
                            devicePersonDto.setCertificateType("111");
                            devicePersonDto.setCertificateNumber(visitorPerson.getCardNo());
                            //添加人员类型
                            devicePersonDto.setPersonType("whitelist");
                            //添加访客时间
                            FacesDto facesDto = new FacesDto();
                            facesDto.setFaceId(String.valueOf(visitorPerson.getUserId()));
                            String photoUrl = url + visitorPerson.getPhoto();
                            String faceData = BASE64_PREFIX + UrlToBase64Util.imageUrlToBase64(photoUrl);

                            facesDto.setData(faceData);
                            facesDtos.add(facesDto);
                            devicePersonDto.setFaces(facesDtos);
                            String s = DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                            System.out.println("新增楼层人员结果：" + s);
                        }
                    }
                }


                //根据房间id获取设备id
                List<RoomEquipment> roomEquipments = roomEquipmentService.selectListByRoomId(aLong);
                for (RoomEquipment roomEquipment : roomEquipments) {
                    //根据设备id获取设备
                    Equipment equipment = equipmentService.selectEquipmentById(roomEquipment.getEquipmentId());
                    if (equipment != null) {
                        String s = DeviceUtils.queryPersons(equipment.getIp(), String.valueOf(visitorPerson.getIntervieweeId()));
                        JSONObject jsonObject = JSONUtil.parseObj(s);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount > 0) {
                            //todo 需要修改  到底是按照访客时间。
                            return toAjax(1);
                        }
                        //添加 用户和对应的设备
                        UserEquipment userEquipment = new UserEquipment();
                        userEquipment.setEquipmentId(equipment.getId());
                        userEquipment.setUserId(visitorPerson.getIntervieweeId());
                        userEquipment.setStartTime(customer.getStartDate());
                        userEquipment.setEndDate(customer.getEndDate());
                        userEquipmentService.insertUserEquipment(userEquipment);

                        //往设备添加对应的人脸数据
                        DevicePersonDto devicePersonDto = new DevicePersonDto();
                        ArrayList<FacesDto> facesDtos = new ArrayList<>();
                        devicePersonDto.setPersonId(String.valueOf(visitorPerson.getUserId()));
                        devicePersonDto.setName(visitorPerson.getName());
                        devicePersonDto.setPhone(String.valueOf(visitorPerson.getPhone()));
                        devicePersonDto.setCertificateType("111");
                        devicePersonDto.setCertificateNumber(visitorPerson.getCardNo());
                        //添加人员类型
                        devicePersonDto.setPersonType("visitor");
                        //添加访客时间
                        devicePersonDto.setVisitorValidStartTime(DateUtil.format(visitorPerson.getVisitTime(), "yyyy-MM-dd'T'HH:mm:ss"));
                        devicePersonDto.setVisitorValidEndTime(DateUtil.format(visitorPerson.getLeaveTime(), "yyyy-MM-dd'T'HH:mm:ss"));
                        FacesDto facesDto = new FacesDto();
                        facesDto.setFaceId(String.valueOf(visitorPerson.getUserId()));
                        String photoUrl = url+visitorPerson.getPhoto();
                        String faceData = BASE64_PREFIX + UrlToBase64Util.imageUrlToBase64(photoUrl);
                        facesDto.setData(faceData);
                        facesDtos.add(facesDto);
                        devicePersonDto.setFaces(facesDtos);
                        DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                    }
                }
            }
        }else if (visitorPerson.getStatus() == 2){
            //如果状态为2
            //则删除设备中的人员信息
        }

        visitorPerson.setUpdateBy(getLoginName());
        visitorPerson.setUpdateTime(DateUtils.getNowDate());

        return toAjax(visitorPersonService.updateReservationPerson(visitorPerson));
    }

    /**
     * 删除预约参观人员
     */
    @RequiresPermissions("meeting:visitorPerson:remove")
    @PostMapping("remove")
    public R remove(String ids) {
        return toAjax(visitorPersonService.deleteReservationPersonByIds(ids));
    }


    /**
     * 根据预约记录查询当前人的进出记录
     */
    @Ignore
    @GetMapping("getRecordByReservationId/{id}")
    public R getRecordByReservationId(@PathVariable("id") Long id) {
        List<RoomRecord> list = visitorPersonService.getRecordByReservationId(id);
        for (RoomRecord record : list) {
            IcsCustomerStaff customerStaff1 = staffService.selectIcsCustomerStaffById(record.getUserId());
            if (null != customerStaff1) {
                record.setUserName(customerStaff1.getUsername());
                record.setUserPhone(customerStaff1.getMobile());
            }
        }
        return R.data(list);
    }

    /**
     * 根据企业id查询出所有的用户
     */
    @Ignore
    @GetMapping("selectUserByCustomer/{customerId}")
    public R selectUserByCustomer(@PathVariable("customerId") Long customerId) {
        List<IcsCustomerStaff> customers = staffService.selectUserByCustomer(customerId);
        return R.data(customers);
    }

    /**
     * 根据企业id查询出所有的用户
     */
    @Ignore
    @GetMapping("selectCustomer")
    public R selectCustomer(Long parkId) {
        Customer customer = new Customer();
        customer.setParkId(parkId);
        List<Customer> customers = customerService.selectCustomerList(customer);
        return R.data(customers);
    }


    public void addPersonDeviceByCustomer(Room room, Long deviceId) {
        if (room != null) {
            List<Customer> customers = customerService.selectByRoomId(room.getId(),room.getParkId());
            if ( CollUtil.isNotEmpty(customers)) {
                for (Customer customer : customers) {
                    List<IcsCustomerStaff> icsCustomerStaffs = staffService.selectUserByCustomer(customer.getId());
                    if (CollUtil.isNotEmpty(icsCustomerStaffs)) {
                        List<Long> ids = icsCustomerStaffs.stream().map(item -> {
                            return item.getId();
                        }).collect(Collectors.toList());
                        for (Long id : ids) {
                            UserEquipment userEquipment = new UserEquipment();
                            userEquipment.setEquipmentId(deviceId);
                            userEquipment.setUserId(id);
                            userEquipment.setStartTime(customer.getStartDate());
                            userEquipment.setEndDate(customer.getEndDate());
                            userEquipmentService.insertUserEquipment(userEquipment);
                        }
                    }
                }

            }
        }
    }
}

