package com.ics.controller.mobile.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.baomidou.mybatisplus.core.metadata.IPage;
import com.ics.admin.domain.Customer;
import com.ics.admin.domain.Policy;
import com.ics.admin.domain.ServiceBanner;
import com.ics.admin.domain.meeting.*;
import com.ics.admin.domain.meeting.vo.VisitorPersonVo;
import com.ics.admin.mapper.meeting.RoomContentMapper;
import com.ics.admin.service.*;
import com.ics.admin.service.meeting.*;
import com.ics.common.core.controller.BaseController;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.core.domain.R;
import com.ics.common.core.domain.dto.DevicePersonDto;
import com.ics.common.core.domain.dto.FacesDto;
import com.ics.common.core.page.PageDomain;
import com.ics.common.core.page.TableSupport;
import com.ics.common.utils.DeviceUtils;
import com.ics.common.utils.RandomUtil;
import com.ics.common.utils.UrlToBase64Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.RequiresPermissions;

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


/**
 * 访客管理模块
 */
@RestController
@Slf4j
@RequestMapping("/api/visitor")
public class ApiVisitorController extends BaseController {

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


    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IIcsCustomerStaffService customerStaffService;

    @Autowired
    private IVisitorPersonService visitorPersonService;

    @Autowired
    private IReservationPersonService reservationPersonService;

    @Autowired
    private RoomContentMapper roomContentMapper;


    @Autowired
    private IRoomService roomService;

    @Autowired
    private IBuildingDetailService buildingDetailService;

    @Autowired
    private IServiceBannerService bannerService;

    @Autowired
    private IPolicyService policyService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IEquipmentService equipmentService;

    @Autowired
    private IDetailEquipmentService detailEquipmentService;

    @Autowired
    private IUserEquipmentService userEquipmentService;

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

    /**
     * 获取所有的企业
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("list")
    public R list(Customer customer) {
        List<Customer> customers = customerService.selectCustomerList(customer);
        return result(customers);
    }

    /**
     * 获取企业下的所有用户
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("selectUserByCustomer/{customerId}")
    public R selectUserByCustomer(@PathVariable("customerId") Long customerId) {
        List<IcsCustomerStaff> customers = customerStaffService.selectUserByCustomer(customerId);
        return result(customers);
    }

    /**
     * 被访客记录
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/selectVisitorRecordByUserId")
    public R selectVisitorPerson(@RequestBody VisitorPerson visitorPerson1) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        IPage<VisitorPerson> visitorPersons = visitorPersonService.selectVisitorRecord(visitorPerson1.getUserId(), pageNum, pageSize);
        for (VisitorPerson visitorPerson : visitorPersons.getRecords()) {
            if (visitorPerson.getStatus() == 0) {
                visitorPerson.setStatusName("待审核");
            } else if (visitorPerson.getStatus() == 1) {
                visitorPerson.setStatusName("审核通过");
            } else if (visitorPerson.getStatus() == 2) {
                visitorPerson.setStatusName("审核拒绝");
            }

            Long userId = visitorPerson1.getUserId();
            IcsCustomerStaff icsCustomerStaff = customerStaffService.selectIcsCustomerStaffById(userId);
            visitorPerson.setUserName(icsCustomerStaff.getUsername());
            visitorPerson.setMobile(icsCustomerStaff.getMobile());
            Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
            visitorPerson.setCustomerName(customer.getName());
        }
        return R.ok().put("data", visitorPersons);

    }

    /**
     * 访客记录
     *
     * @return
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("selectVisitorRecordByIntervieweeId")
    public R selectVisitorRecordByIntervieweeId(@RequestBody VisitorPerson visitorPerson1) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        IPage<VisitorPerson> visitorPersons = visitorPersonService.selectVisitorRecordByIntervieweeId(visitorPerson1.getIntervieweeId(),visitorPerson1.getParkId(), pageNum, pageSize);
        for (VisitorPerson visitorPerson : visitorPersons.getRecords()) {
            if (visitorPerson.getStatus() == 0) {
                visitorPerson.setStatusName("待审核");
            } else if (visitorPerson.getStatus() == 1) {
                visitorPerson.setStatusName("审核通过");
            } else if (visitorPerson.getStatus() == 2) {
                visitorPerson.setStatusName("审核拒绝");
            }


            Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
            if(customer != null) {
                visitorPerson.setCustomerName(customer.getName());
            }
        }
        return R.ok().put("data", visitorPersons);
    }

    /**
     * 获取访客记录的详情
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("selectVisitorRecordById/{id}")
    public R selectVisitorRecordById(@PathVariable("id") Long id) {
        VisitorPerson visitorPerson = visitorPersonService.selectReservationPersonById(id);

        if (visitorPerson.getStatus() == 0) {
            visitorPerson.setStatusName("待审核");
        } else if (visitorPerson.getStatus() == 1) {
            visitorPerson.setStatusName("审核通过");
        } else if (visitorPerson.getStatus() == 2) {
            visitorPerson.setStatusName("审核拒绝");
        }

        Customer customer = customerService.selectCustomerById(visitorPerson.getCustomerId());
        visitorPerson.setCustomerName(customer.getName());

        VisitorPersonVo visitorPersonVO = new VisitorPersonVo();
        BeanUtils.copyProperties(visitorPerson, visitorPersonVO);

        return R.ok().put("data", visitorPersonVO);
    }


    /**
     * 被访人审核功能
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("updateVisitorPersonStatus")
    public R updateVisitorPersonStatus(@RequestBody VisitorPerson person) {
        VisitorPerson visitorPerson = visitorPersonService.selectReservationPersonById(person.getId());
        Assert.isTrue(visitorPerson.getStatus() == 0, "该访客已审核");


        person.setReviewers(person.getUserId());
        person.setReviewersTime(new Date());
        int update = visitorPersonService.updateVisitorPersonStatus(person);
        if (update > 0) {


            ArrayList<Long> ids = new ArrayList<>();

            Customer customer = customerService.selectCustomerById(Long.valueOf(visitorPerson.getCustomerId()));
            if (null != customer) {
                String roomId = customer.getRoomId();
                List<String> roomIds = StrUtil.split(roomId, ',');
                List<Long> collect = roomIds.stream().map(Long::valueOf).collect(Collectors.toList());
                //获取了房间集合，循环对应集合，
                for (Long id : collect) {
                    List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                    if (CollUtil.isNotEmpty(roomEquipment)) {
                        for (RoomEquipment equipment : roomEquipment) {
                            ids.add(equipment.getEquipmentId());
                        }
                    }
                    List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(id);
                    if (CollUtil.isNotEmpty(detailEquipments)) {
                        for (DetailEquipment detailEquipment : detailEquipments) {
                            ids.add(detailEquipment.getEquipmentId());
                        }
                    }
                }
                if (CollUtil.isNotEmpty(ids)) {
                    for (Long id : ids) {
                        UserEquipment userEquipment = new UserEquipment();
                        userEquipment.setEquipmentId(id);
                        userEquipment.setUserId(visitorPerson.getIntervieweeId());
                        userEquipment.setStartTime(customer.getStartDate());
                        userEquipment.setEndDate(customer.getEndDate());
                        userEquipmentService.insertUserEquipment(userEquipment);
                    }
                }
            }
            String roomId = customer.getRoomId();
            List<String> roomIds = StrUtil.split(roomId, ',');
            List<Long> collect = roomIds.stream().map(Long::valueOf).collect(Collectors.toList());
            //获取了房间集合，循环对应集合，
            for (Long aLong : collect) {
                //根据房间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(person.getIntervieweeId()));
                        JSONObject jsonObject = JSONUtil.parseObj(s);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount > 0) {
                            //todo 需要修改  到底是按照访客时间。
                            return toAjax(1);
                        }
                        DevicePersonDto devicePersonDto = new DevicePersonDto();
                        ArrayList<FacesDto> facesDtos = new ArrayList<>();
                        devicePersonDto.setPersonId(String.valueOf(visitorPerson.getIntervieweeId()));
                        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);
                        String s1 = DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                        log.info("添加人员返回结果：" + s1);

                    }
                }
            }

        }
        return toAjax(update);
    }

    /**
     * 会议邀请记录
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("selectVisitorInvitationRecord/{userId}")
    public R selectVisitorInvitationRecord(@PathVariable("userId") Long userId,Long parkId) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        System.out.println(parkId);
        IPage<Reservation> list = reservationPersonService.selectListByParticipantId(userId,parkId, pageNum, pageSize);
        return R.ok().put("page", list);
    }


    /**
     * 添加访客预约
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("visitorPerson")
    public R visitorPerson(@RequestBody VisitorPerson person) {
        person.setStatus(0);
        Assert.isTrue(IdcardUtil.isValidCard(person.getCardNo()), "身份证格式不正确");
        Assert.isTrue(Validator.isMobile(person.getPhone()), "手机号格式不正确");
        person.setUserId(Long.valueOf(RandomUtil.randomInt(10)));
        int i = visitorPersonService.insertReservationPerson(person);
        Assert.isTrue(i > 0, "添加访客预约失败");
        //添加成功后，需要 往设备中添加一条数据

        return toAjax(i);
    }

    /**
     * 轮播图
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/carousel")
    public R carousel() {

        return R.data(bannerService.selectServiceBannerList(new ServiceBanner()));
    }

    /**
     * 展示政策
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/policy")
    public R policy() {
        return R.data(policyService.selectPolicyById(11L));
    }

    @RequiresPermissions("member:center:view")
    @GetMapping("/policyById/{id}")
    public R policyById(@PathVariable Long id) {
        return R.data(policyService.selectPolicyById(id));
    }

}
