package com.sptg.gateway.controller;

import cn.hutool.core.date.DateUtil;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.dto.FaceChargeProjectResidentialUserDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.gateway.util.DataCheck;
import com.sptg.pay.api.dto.UserOrderDto;
import com.sptg.pay.api.entity.UserOrder;
import com.sptg.pay.api.feigns.UserOrderFeign;
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.apache.commons.lang3.time.DateUtils;
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 javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * title: UserFaceChargeController
 * package: com.sptg.estate.biz.security
 * description: 住户人脸激活控制器
 *
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/userFace")
public class UserFaceChargeController {

    private final OrgFeign orgFeign;
    private final MemberAndUserFeign memberAndUserFeign;
    private final UserFeign userFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;
    private final FaceChargeProjectFeign faceChargeProjectFeign;
    private final FaceChargeProjectResidentialUserFeign faceChargeProjectResidentialUserFeign;
    private final ResidentialFeign residentialFeign;
    private final UserOrderFeign userOrderFeign;

    /**
     * 功能描述: 通过会员id获取用户密码授权的开门记录
     * @param map {
     *             member_id     :   会员id,
     *             residential_id : 小区id
     *             org_id        :   机构授权org_id，机构id
     *             token         :   对接令牌
     *            }
     * @return  返回结果
     *
     *
     */
    @PostMapping(value = "/getFaceChargeListByResidentialId")
    public Map<String,Object> getListByResidentialId(@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 residential_id = map.get("residential_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            String user_id = map.get("user_id");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if(StringUtils.isBlank(user_id)){
                hashMap.put("result_msg", "用户id不能为空");
                return hashMap;
            } else {
                User user = null;
                user = this.userFeign.findUserById(Long.parseLong(user_id));
                if(user==null){
                    hashMap.put("result_msg", "住户不存在");
                    return hashMap;
                }else{
                    if(null != user.getFaceEndDate()){
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dateString = formatter.format(user.getFaceEndDate());
                        hashMap.put("faceEndDate",dateString);
                    }
                }
            }
            if (residential_id == null){
                return hashMap;
            }
            Long residentialId = Long.valueOf(residential_id);
            //判断小区是否存在或者是否被删除
            Residential residential = residentialFeign.findResidentialById(residentialId);
            if (residential ==null){
                hashMap.put("result_msg", "您的小区不存在");
                return hashMap;
            }
            //查询人脸收费项目
            List<FaceChargeProject> faceChargeProjectList = faceChargeProjectFeign.getListByResidentialIdAndDate(residentialId);
            hashMap.put("result_code", 1);
            hashMap.put("list",faceChargeProjectList);

            if(faceChargeProjectList.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 {
     *            token                 :   对接令牌
     *            org_id                 :   机构授权org_id，机构id
     *            user_id               :   修改的住户id
     *            face_charge_id        :   人脸套餐id,
     *            residential_id        :   小区id
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/activeFace")
    public Map<String,Object> activeFace(@RequestBody Map<String,String> map, HttpServletRequest request){
        Map<String,Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "人脸激活失败");
        String org_id = map.get("org_id");
        String token = map.get("token");
        String user_id = map.get("user_id");
        String face_charge_id = map.get("face_charge_id");
        String residential_id = map.get("residential_id");
        String room_id = map.get("room_id");
        String order_type = map.get("order_type");
        String description = map.get("description");
        FaceChargeProject faceCharge = null;
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            if(residential_id == null){
                hashMap.put("result_msg", "小区id不能为空");
                return hashMap;
            }
            if(room_id == null){
                hashMap.put("result_msg", "房间id不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(face_charge_id)){
                hashMap.put("result_msg", "人脸套餐id不能为空");
                return hashMap;
            }else{
                faceCharge = faceChargeProjectFeign.getFaceChargeProjectById(Long.valueOf(face_charge_id));
                if(faceCharge == null){
                    hashMap.put("result_msg", "人脸套餐不存在");
                    return hashMap;
                }
            }
            if(StringUtils.isBlank(user_id)){
                hashMap.put("result_msg", "用户id不能为空");
                return hashMap;
            } else {
                User user = null;
                user = this.userFeign.findUserById(Long.parseLong(user_id));
                if(user.getCheckState().toString().equals("1")){

                }else{
                    hashMap.put("result_msg", "请先上传人脸图片");
                    return hashMap;
                }
                if(StringUtils.isBlank(user.getImageUri())){
                    hashMap.put("result_msg", "请先上传人脸图片");
                    return hashMap;
                }
                if(user==null){
                    hashMap.put("result_msg", "激活人脸的住户不存在");
                    return hashMap;
                }else{
                    //1、创建订单
                    UserOrderDto userOrderDto = new UserOrderDto();
                    userOrderDto.setUserId(user.getId());
                    userOrderDto.setGoodsId(faceCharge.getId());
                    userOrderDto.setOrderType(order_type);
                    userOrderDto.setDescription(description);
                    FaceChargeProject faceChargeProject = this.faceChargeProjectFeign.getFaceChargeProjectById(userOrderDto.getGoodsId());
                    if(faceChargeProject.getType().equals(OperationConstant.ONE)){ //免费
                        userOrderDto.setShouldPayAmount(new BigDecimal(0));
                        userOrderDto.setActualPayAmount(new BigDecimal(0));
                        userOrderDto.setOffsetAmount(new BigDecimal(0));
                        userOrderDto.setIsCharge(OperationConstant.ONE);
                    }else{ //付费
                        BigDecimal shouldPayAmount = faceCharge.getAmount();
                        //实际付款金额
                        BigDecimal actualPayAmount = new BigDecimal(faceChargeProject.getDiscount() / 100).multiply(shouldPayAmount);
                        userOrderDto.setShouldPayAmount(shouldPayAmount);
                        userOrderDto.setOffsetAmount(shouldPayAmount.subtract(actualPayAmount));
                        userOrderDto.setActualPayAmount(actualPayAmount);
                        userOrderDto.setIsCharge(OperationConstant.TWO);
                    }
                    ResultBean<UserOrder> resultBean = userOrderFeign.addUserOrder(userOrderDto);
                    if(resultBean.getCode().equals("200") && resultBean.getData()!= null){
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "人脸订单创建成功");
                        //免费套餐直接下发人脸
                        if (faceChargeProject.getType().equals(OperationConstant.ONE)){
                            Date faceEndDate = user.getFaceEndDate();
                            Date today = new Date();
                            if(faceEndDate != null){
                                //延长激活日期
                                int compare = DateUtil.compare(faceEndDate, today);
                                if(compare >= 0){
                                    user.setFaceEndDate(DateUtils.addDays(user.getFaceEndDate(), faceChargeProject.getDays()));
                                }else{
                                    user.setFaceEndDate(DateUtils.addDays(today, faceChargeProject.getDays()));
                                }
                            }else{
                                user.setFaceBeginDate(today);
                                user.setFaceEndDate(DateUtils.addDays(today, faceChargeProject.getDays()));
                            }
                            user.setFaceEnable(OperationConstant.ONE);
                            if (this.userFeign.faceEnable(user)){
                                //下发成功后新增绑定记录
                                FaceChargeProjectResidentialUserDto dto = new FaceChargeProjectResidentialUserDto();
                                dto.setResidentialId(Long.parseLong(residential_id));
                                dto.setFaceChargeId(faceChargeProject.getId());
                                dto.setTypeItem(faceChargeProject.getTypeItem());
                                dto.setUserId(user.getId());
                                dto.setCreateDate(new Date());
                                this.faceChargeProjectResidentialUserFeign.addFaceChargeProjectResidentialUser(dto);
                            }
                        }
                        List<UserOrder> orderList = new ArrayList<>();
                        orderList.add(resultBean.getData());
                        hashMap.put("list", orderList);
                    }else{
                        hashMap.put("result_code", 0);
                        hashMap.put("result_msg", "人脸订单创建失败");
                    }

                    /*Date today = new Date();
                    Date faceBeginDate = user.getFaceBeginDate();
                    if(faceBeginDate == null){
                        user.setFaceEndDate(DateUtils.addDays(today, faceCharge.getDays()));
                        Boolean b = userFeign.updateEntity(user);
                        if(b){

                        }else{
                            hashMap.put("result_msg", "人脸有效期更新失败");
                        }
                    }else{
                        if(today.after(user.getFaceEndDate())){
                            user.setFaceEndDate(DateUtils.addDays(today, faceCharge.getDays()));
                        }else{
                            user.setFaceEndDate(DateUtils.addDays(user.getFaceEndDate(), faceCharge.getDays()));
                        }

                        Boolean b = userFeign.updateEntity(user);
                        if(b){

                        }else{
                            hashMap.put("result_msg", "人脸有效期更新失败");
                        }
                    }
                    FaceChargeProjectResidentialUser faceUser = new FaceChargeProjectResidentialUser();
                    faceUser.setCreateDate(today);
                    faceUser.setFaceChargeId(Long.parseLong(face_charge_id));
                    faceUser.setResidentialId(Long.parseLong(residential_id));
                    faceUser.setUserId(user.getId());
                    DevicesAccessPushVO devicesAccessPushVO = new DevicesAccessPushVO();
                    devicesAccessPushVO.setUserId(user.getId());
                    devicesAccessPushVO.setOperType(OperationConstant.THREE); //人脸门禁启用
                    ResultBean<Boolean> resultBean = userFeign.accessDevicesManualPush(devicesAccessPushVO);
                    if(resultBean.getData()){
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "人脸激活成功");
                    }*/
                }
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }
}
