package com.ics.controller.mobile.member;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import com.ics.admin.domain.Customer;
import com.ics.admin.domain.meeting.Equipment;
import com.ics.admin.domain.meeting.RoomEquipment;
import com.ics.admin.service.ICustomerService;
import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.admin.service.meeting.IEquipmentService;
import com.ics.admin.service.meeting.IRoomEquipmentService;
import com.ics.common.annotation.LoginStaff;
import com.ics.common.annotation.LoginUser;
import com.ics.common.constant.Constants;
import com.ics.common.constant.UserConstants;
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.utils.DeviceUtils;
import com.ics.common.utils.UrlToBase64Util;
import com.ics.common.utils.bean.BeanUtils;
import com.ics.system.service.IConfigService;
import com.ics.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;
import org.wf.jwtp.util.SubjectUtil;

import javax.security.auth.Subject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 个人资料
 *
 * @author jack
 */
@Slf4j
@RestController
@RequestMapping("/user/profile")
public class ProfileAPIController extends BaseController {


    @Autowired
    private IUserService userService;
    @Autowired
    private IIcsCustomerStaffService icsCustomerStaffService;

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IConfigService configService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IEquipmentService equipmentService;


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


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


    /**
     * 当前用户信息
     */
    @Ignore
    @GetMapping
    public R index( IcsCustomerStaff icsCustomerStaff) {
        String jsonConfig = configService.selectConfigByKey("sys.setting.siteUrl");
        JSONObject jsonObject = JSON.parseObject(jsonConfig);
        String siteUrl = jsonObject.getString("siteUrl");
        Map<String, Object> map = Maps.newHashMap();
        icsCustomerStaff = icsCustomerStaffService.selectIcsCustomerStaffById(icsCustomerStaff.getId());
        if (icsCustomerStaff !=null ){
            Customer customer = customerService.selectCustomerById(icsCustomerStaff.getIcsCustomerId());
            if (null != customer){
                icsCustomerStaff.setCustomerName(customer.getName());
            }
        }

        return R.data(icsCustomerStaff);
    }

    /**
     * 更新当前用户
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/update")
    public R update(@RequestBody IcsCustomerStaff icsCustomerStaff) {
        long userId = this.getCurrentUserId();

        icsCustomerStaff.setId(userId);

        if(StrUtil.isNotBlank(icsCustomerStaff.getPhoto())) {
            Long icsCustomerId = icsCustomerStaff.getIcsCustomerId();
            Customer customer = customerService.selectCustomerById(icsCustomerId);
            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 persons = DeviceUtils.queryPersons(equipment.getIp(),String.valueOf(icsCustomerStaff.getId()));
                        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(persons);
                        Integer amount = (Integer) jsonObject.get("amount");
                        if (amount <= 0) {
                            DevicePersonDto devicePersonDto = new DevicePersonDto();
                            ArrayList<FacesDto> facesDtos = new ArrayList<>();
                            devicePersonDto.setPersonId(String.valueOf(icsCustomerStaff.getId()));
                            devicePersonDto.setName(icsCustomerStaff.getName());
                            devicePersonDto.setPhone(String.valueOf(icsCustomerStaff.getMobile()));
                            devicePersonDto.setCertificateType("111");
                            devicePersonDto.setCertificateNumber(icsCustomerStaff.getCardNo());
                            //添加人员类型
                            devicePersonDto.setPersonType("whitelist");
                            //添加访客时间
                            FacesDto facesDto = new FacesDto();
                            facesDto.setFaceId(String.valueOf(icsCustomerStaff.getId()));
                            String photoUrl = url + icsCustomerStaff.getPhoto();
                            String faceData = BASE64_PREFIX + UrlToBase64Util.imageUrlToBase64(photoUrl);
                            facesDto.setData(faceData);
                            facesDtos.add(facesDto);
                            devicePersonDto.setFaces(facesDtos);
                            String s = DeviceUtils.addPersons(equipment.getIp(), devicePersonDto);
                            log.info("添加人员返回结果：" + s);
                        }
                    }

                }
            }
        }


        return toAjax(icsCustomerStaffService.updateIcsCustomerStaff(icsCustomerStaff));
    }
}
