package com.sptg.gateway.controller;

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.core.constant.UserFlagConstant;
import com.sptg.common.core.entity.DispatchTask;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.entity.GuestAuthorize;
import com.sptg.estate.api.entity.MemberAndUser;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.GuestAuthorizeFeign;
import com.sptg.estate.api.feigns.MemberAndUserFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.gateway.entity.GuestAuthorizeApi;
import com.sptg.gateway.util.DataCheck;
import com.sptg.gateway.util.PojoToApi;
import com.sptg.permissions.api.feigns.ApiDockingConfFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * title: GuestAuthorizeController
 * package: com.sptg.estate.biz.security
 * description: 访客授权管理控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/guestAuthorize")
public class GuestAuthorizeController {

    private final OrgFeign orgFeign;
    private final GuestAuthorizeFeign guestAuthorizeFeign;
    private final MemberAndUserFeign memberAndUserFeign;
    private final UserFeign userFeign;
    private final DeviceFeign deviceFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;


    /**
     * 功能描述: 通过id获取访客授权详情
     *
     * @param
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getById/{id}")
    public Map<String, Object> getById(@PathVariable("id") Long id) {
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询数据失败");
        try {
            GuestAuthorize guestAuthorize = this.guestAuthorizeFeign.findGuestAuthorizeById(id);
            if(null != guestAuthorize){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "查询数据成功");
                hashMap.put("guestAuthorize",guestAuthorize);
            }else{
                hashMap.put("result_code", 0);
                hashMap.put("result_msg", "授权记录不存在");

            }

        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 通过会员id获取访客授权密码列表
     *
     * @param map {
     *            member_id     :   会员id,
     *            org_id        :   机构授权org_id，机构id
     *            token         :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getListByMemberId")
    public Map<String, Object> getListByMemberId(@RequestBody Map<String, String> map) {
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询数据失败");
        try {
            String member_id = map.get("member_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
            } else {
                List<Long> userIds = new ArrayList<>();
                for (MemberAndUser mau : list) {
                    userIds.add(mau.getUserId());
                }
                ResultBean<GuestAuthorize> resultBean = this.guestAuthorizeFeign.getListByUserId(userIds);
                if (resultBean.getCode().equals("200")) {
                    hashMap.put("result_code", 1);
                    List<GuestAuthorize> guestAuthorizes = resultBean.getList();
                    List<GuestAuthorizeApi> gs = new ArrayList<>();
                    for (GuestAuthorize g : guestAuthorizes) {
                        gs.add(PojoToApi.guestAuthorizeToApi(g));
                    }
                    hashMap.put("list", gs);
                    if (gs.size() == 0) {
                        hashMap.put("result_msg", "没有查询到相关数据");
                    } else {
                        hashMap.put("result_msg", "获取相关数据成功");
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 获取授权密码
     *
     * @param map {
     *            room_id       :   授权的房间id
     *            guest_type    :   访客类型：0-朋友  1-外卖 2-快递 3-其他
     *            begin_date    :   密码有效开始时间  --时间戳
     *            end_date      :   密码有效结束时间  --时间戳
     *            valid_count   :   密码有效次数
     *            org_id        :   机构授权org_id，机构id
     *            member_id     :   会员id,
     *            token         :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getGuestAuthorize")
    public Map<String, Object> getGuestAuthorize(@RequestBody Map<String, String> map) {
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取密码失败");
        try {
            String room_id = map.get("room_id");
            String guest_type = map.get("guest_type");
            String begin_date = map.get("begin_date");
            String end_date = map.get("end_date");
            String valid_count = map.get("valid_count");
            String member_id = map.get("member_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(room_id)) {
                hashMap.put("result_msg", "授权的房间（room_id）不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(guest_type)) {
                hashMap.put("result_msg", "授权的访客类型（guest_type）不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(begin_date)) {
                hashMap.put("result_msg", "授权的密码有效开始时间(begin_date)不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(end_date)) {
                hashMap.put("result_msg", "授权的密码有效结束时间(end_date)不能为空");
                return hashMap;
            }
//            if(StringUtils.isBlank(valid_count)){
//                hashMap.put("result_msg", "授权的密码有效次数(valid_count)不能为空");
//                return hashMap;
//            }
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                //会员在授权的房间下的userId
                Long userId = null;
                for (MemberAndUser mau : list) {
                    if (mau.getRoomId().equals(Long.valueOf(room_id))) {
                        userId = mau.getUserId();
                    }
                }
                if (userId == null) {
                    hashMap.put("result_msg", "会员没有该授权房间的权限");
                    return hashMap;
                } else {
                    User user = this.userFeign.findUserById(userId);
                    if (user == null) {
                        hashMap.put("result_msg", "会员授权的房间下对应的住户不存在");
                        return hashMap;
                    } else {
                        GuestAuthorize ga = new GuestAuthorize();
                        ga.setGuestType(Integer.valueOf(guest_type));
                        ga.setRoomId(user.getRoomId());
                        ga.setRoomName(user.getRoomName());
                        ga.setUnitId(user.getUnitId());
                        ga.setUnitName(user.getUnitName());
                        ga.setBuildingId(user.getBuildingId());
                        ga.setBuildingName(user.getBuildingName());
                        ga.setUserId(user.getId().toString());
                        ga.setUserName(user.getName());
//                        ga.setValidCount(Integer.valueOf(valid_count));
                        ga.setResidentialId(user.getResidentialId());
                        ga.setResidentialName(user.getResidentialName());
                        ga.setEnableType(OperationConstant.ZERO);
                        ga.setOrgPosition(user.getOrgPosition());
                        ga.setEstatePosition(user.getEstatePosition());
                        ga.setRootOrgId(user.getRootOrgId());
                        ga.setBeginDate(new Date(Long.valueOf(begin_date)));
                        ga.setEndDate(new Date(Long.valueOf(end_date)));
                        ga.setCreateDate(new Date());
                        //获取授权密码
                        ResultBean<GuestAuthorize> resultBean = this.guestAuthorizeFeign.addGuestAuthorize(ga);
                        if (ResultEnum.SUCCESS.getCode().equals(resultBean.getCode())) {
                            GuestAuthorize authorize = resultBean.getData();
                            //密码下发
                            DispatchTask dispatchTask = new DispatchTask();
                            dispatchTask.setXqId(authorize.getResidentialId());
                            dispatchTask.setUnitId(authorize.getUnitId());
                            dispatchTask.setData(authorize);
                            Map<String, String> logMap = new HashMap<>();
                            //小区
                            if (!StringUtils.isEmpty(authorize.getResidentialName())) {
                                logMap.put("xqName", authorize.getResidentialName());
                            } else {
                                logMap.put("xqName", null);
                            }
                            //单元
                            if (!StringUtils.isEmpty(authorize.getUnitName())) {
                                logMap.put("unitName", authorize.getUnitName());
                            } else {
                                logMap.put("unitName", null);
                            }
                            //房间
                            if (!StringUtils.isEmpty(authorize.getRoomName())) {
                                logMap.put("roomName", authorize.getRoomName());
                            } else {
                                logMap.put("roomName", null);
                            }
                            //用户名
                            if (!StringUtils.isEmpty(authorize.getUserName())) {
                                logMap.put("userName", authorize.getUserName());
                            } else {
                                logMap.put("userName", null);
                            }
                            //密码
                            if (null != authorize.getPassword()) {
                                logMap.put("password", authorize.getPassword().toString());
                            } else {
                                logMap.put("password", null);
                            }
                            //有效期开始时间
                            SimpleDateFormat format = new SimpleDateFormat();
                            if (null != authorize.getBeginDate()) {
                                logMap.put("beginTime", format.format(authorize.getBeginDate()));
                            } else {
                                logMap.put("beginTime", null);
                            }
                            //有效期结束时间
                            if (null != authorize.getEndDate()) {
                                logMap.put("endTime", format.format(authorize.getEndDate()));
                            } else {
                                logMap.put("endTime", null);
                            }
                            ResultBean<Boolean> result = this.deviceFeign.pushOpenDoorPwd(dispatchTask, logMap);
                            if (result.getData()) {
                                hashMap.put("result_code", 1);
                                hashMap.put("result_msg", "密码下发成功");
                            } else {
                                hashMap.put("result_msg", "密码下发失败");
                            }
                            hashMap.put("guestAuthorize", PojoToApi.guestAuthorizeToApi(authorize));
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 撤销密码
     *
     * @param map {
     *            guest_authorize_id       :   要撤销的密码id
     *            org_id                   :   机构授权org_id，机构id
     *            member_id                :   会员id,
     *            token                     :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/cancel")
    public Map<String, Object> cancel(@RequestBody Map<String, String> map) {
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "密码撤销失败");
        String guest_authorize_id = map.get("guest_authorize_id");
        String org_id = map.get("org_id");
        String member_id = map.get("member_id");
        String token = map.get("token");
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(guest_authorize_id)) {
                hashMap.put("result_msg", "要撤销的密码（guest_authorize_id）不能为空");
                return hashMap;
            }
            GuestAuthorize guestAuthorize = this.guestAuthorizeFeign.findGuestAuthorizeById(Long.valueOf(guest_authorize_id));
            if (guestAuthorize == null) {
                hashMap.put("result_msg", "要撤销的密码不存在");
                return hashMap;
            }
            if (guestAuthorize.getEnableType() != 0) {
                hashMap.put("result_msg", "要撤销的密码状态不正常" + guestAuthorize.getEnableType());
                return hashMap;
            }
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                //权限校验，校验会员关联的住户是否是创建该密码的住户
                boolean check = false;
                for (MemberAndUser mua : list) {
                    if (guestAuthorize.getUserId().equals(mua.getUserId().toString())) {
                        check = true;
                        break;
                    }
                }
                if (!check) {
                    hashMap.put("result_msg", "会员没有删除该密码的权限");
                    return hashMap;
                } else {
                    GuestAuthorize g = new GuestAuthorize();
                    g.setId(guestAuthorize.getId());
                    g.setEnableType(OperationConstant.ONE);
                    ResultBean<Boolean> resultBean = this.guestAuthorizeFeign.updateGuestAuthorizeEnableType(g);
                    if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode()) && resultBean.getData()) {
                        guestAuthorize.setUserId(UserFlagConstant.USER_FLAG + guestAuthorize.getUserId());
                        //密码删除动作
                        DispatchTask dispatchTask = new DispatchTask();
                        dispatchTask.setXqId(guestAuthorize.getResidentialId());
                        dispatchTask.setUnitId(guestAuthorize.getUnitId());
                        dispatchTask.setData(guestAuthorize);
                        Map<String, String> logMap = new HashMap<>();
                        //小区
                        if (!StringUtils.isEmpty(guestAuthorize.getResidentialName())) {
                            logMap.put("xqName", guestAuthorize.getResidentialName());
                        } else {
                            logMap.put("xqName", null);
                        }
                        //单元
                        if (!StringUtils.isEmpty(guestAuthorize.getUnitName())) {
                            logMap.put("unitName", guestAuthorize.getUnitName());
                        } else {
                            logMap.put("unitName", null);
                        }
                        //房间
                        if (!StringUtils.isEmpty(guestAuthorize.getRoomName())) {
                            logMap.put("roomName", guestAuthorize.getRoomName());
                        } else {
                            logMap.put("roomName", null);
                        }
                        //用户名
                        if (!StringUtils.isEmpty(guestAuthorize.getUserName())) {
                            logMap.put("userName", guestAuthorize.getUserName());
                        } else {
                            logMap.put("userName", null);
                        }
                        //密码
                        if (null != guestAuthorize.getPassword()) {
                            logMap.put("password", guestAuthorize.getPassword().toString());
                        } else {
                            logMap.put("password", null);
                        }
                        //有效期开始时间
                        SimpleDateFormat format = new SimpleDateFormat();
                        if (null != guestAuthorize.getBeginDate()) {
                            logMap.put("beginTime", format.format(guestAuthorize.getBeginDate()));
                        } else {
                            logMap.put("beginTime", null);
                        }
                        //有效期结束时间
                        if (null != guestAuthorize.getEndDate()) {
                            logMap.put("endTime", format.format(guestAuthorize.getEndDate()));
                        } else {
                            logMap.put("endTime", null);
                        }
                        this.deviceFeign.removeOpenDoorPwd(dispatchTask, logMap);
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "密码撤销成功");
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }
}
