package com.sptg.gateway.controller;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.dto.ApplyPayRefundDto;
import com.sptg.estate.api.entity.FaceChargeProject;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.ApplyPayRefundFeign;
import com.sptg.estate.api.feigns.FaceChargeProjectFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.gateway.entity.PayCertificateApi;
import com.sptg.gateway.util.DataCheck;
import com.sptg.gateway.util.PojoToApi;
import com.sptg.pay.api.dto.PayCertificateDto;
import com.sptg.pay.api.entity.PayCertificate;
import com.sptg.pay.api.entity.UserOrder;
import com.sptg.pay.api.feigns.PayCertificateFeign;
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.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 用户订单控制器
 * @author xuanyan
 * @date 2020/6/24 17:24
 */

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/user/order")
public class UserOrderController {

    private final PayCertificateFeign payCertificateFeign;
    private final ApplyPayRefundFeign applyPayRefundFeign;
    private final OrgFeign orgFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;
    private final UserOrderFeign userOrderFeign;
    private final FaceChargeProjectFeign faceChargeProjectFeign;
    private final UserFeign userFeign;

    /**
     *  根据userId查询支付凭证
     * @param map{
     *           user_id  用户id
     *           order_id 订单id
     *           }
     * @return Map<String,Object>返回结果
     */
    @PostMapping("/getPayCertificate")
    public Map<String,Object> findPayCertificateListByConditionByUserId(@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 userId = map.get("user_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(userId)){
                hashMap.put("result_msg", "用户id不能为空");
                return hashMap;
            }
            PayCertificateDto payCertificateDto = new PayCertificateDto();
            payCertificateDto.setUserId(Long.valueOf(userId));
            payCertificateDto.setPayStatus(OperationConstant.TWO);
            List<PayCertificate> payCertificateList = payCertificateFeign.findPayCertificateListByCondition(payCertificateDto);
            if(payCertificateList != null && payCertificateList.size() > 0){
                List<PayCertificateApi> list = new ArrayList<>();
                payCertificateList.forEach(payCertificate -> {
                    list.add(PojoToApi.payCertificateToApi(payCertificate));
                });
                hashMap.put("result_code", 1);
                hashMap.put("list", list);
                hashMap.put("result_msg", "查询数据成功");
            }else {
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "没有查询到该用户的支付凭证");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     *  添加退款申请记录
     * @param map{
     *           pay_certificate_id     支付凭证ID
     *           user_id                用户id
     *           pay_type               支付类型：wxPay，aliPay
     *           actual_pay_fee         实际付款金额
     *           refund_fee             申请退款金额
     *           check_status           审核状态：0：申请待审核，1：申请审核通过，2：申请审核拒绝
     *           refund_status          退款状态，WAIT：退款中，SUCCESS：退款成功，REFUNDCLOSE：退款关闭，CHANGE：退款异常
     *           name                   申请人姓名
     *           phone                  申请手机号
     *           residential_name       所在小区名
     *           unit_name              所在单元名
     *           room_name              所在房间名
     *           }
     * @return Map<String,Object>返回结果
     */
    @PostMapping("/addApplyPayRefund")
    public Map<String,Object> addApplyPayRefund(@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 {
            //支付凭证ID
            String payCertificateId = map.get("pay_certificate_id");
            //申请退款金额
            String refundFee = map.get("refund_fee");
            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(payCertificateId)){
                hashMap.put("result_msg", "支付凭证id不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(refundFee)){
                hashMap.put("result_msg", "退款金额不能为空");
                return hashMap;
            }
            //根据payCertificateId查询applyPayRefundDto
//            PayCertificateDto payCertificateDto = new PayCertificateDto();
//            payCertificateDto.setId(Long.valueOf(payCertificateId));
            PayCertificate payCertificate = payCertificateFeign.findPayCertificateById(Long.valueOf(payCertificateId));

            //添加判断是否可以退款
            Long orderId = payCertificate.getOrderId();
            UserOrder userOrder = userOrderFeign.findUserOrderById(orderId);
            String orderType = userOrder.getOrderType();
            if (!orderType.equals("FACE_ENABLE")){
                hashMap.put("result_msg","该订单类型不支持退款");
                return hashMap;
            }
            Long goodsId = userOrder.getGoodsId();
            FaceChargeProject faceChargeProject = faceChargeProjectFeign.getFaceChargeProjectById(goodsId);
            if(faceChargeProject == null){
                hashMap.put("result_msg","支付凭证查询为空，不能申请退款");
                return hashMap;
            }
            Integer typeItem = faceChargeProject.getTypeItem();
            if (typeItem != 21){
                hashMap.put("result_msg","该订单类型不支持退款");
                return hashMap;
            }

            User user = userFeign.findUserById(payCertificate.getUserId());
            ApplyPayRefundDto applyPayRefundDto = new ApplyPayRefundDto();
            applyPayRefundDto.setPayCertificateId(Long.valueOf(payCertificateId));
            applyPayRefundDto.setUserId(payCertificate.getUserId());
            applyPayRefundDto.setPayType(payCertificate.getChannelCode());
            applyPayRefundDto.setActualPayFee(payCertificate.getPayment());
            applyPayRefundDto.setRefundFee(new BigDecimal(refundFee));
            applyPayRefundDto.setCheckStatus(0);
            applyPayRefundDto.setName(user.getName());
            applyPayRefundDto.setPhone(user.getTel());
            applyPayRefundDto.setResidentialId(user.getResidentialId());
            applyPayRefundDto.setResidentialName(user.getResidentialName());
            applyPayRefundDto.setUnitName(user.getUnitName());
            applyPayRefundDto.setRoomName(user.getRoomName());
            applyPayRefundDto.setRefundNo(genReturnOrderNo());
            applyPayRefundDto.setOrderId(orderId);
            applyPayRefundDto.setOrderNo(userOrder.getBizOrderNo());
            ResultBean<Boolean> bean = applyPayRefundFeign.addApplyPayRefund(applyPayRefundDto);
            if(bean.getMsg().equals("success")){
                payCertificate.setApplyRefund(OperationConstant.ONE); //设置为已发起退款申请
                ResultBean<Boolean> resultBean = this.payCertificateFeign.updatePayCertificate(payCertificate);
                if(resultBean.getData()){
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg","添加申请记录成功");
                }
            }else {
                hashMap.put("result_msg","添加申请记录失败");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 生成退款申请单号
     * @return
     */
    protected String genReturnOrderNo() {

        int hashCode = UUID.randomUUID().toString().hashCode();

        if (hashCode < 0) {//有可能是负数
            hashCode = -hashCode;
        }

//        String bizOrderNo = String.valueOf(hashCode);
//        bizOrderNo = String.format("%010d", hashCode);
        String returnOrderNo = "R"+String.format("%010d", hashCode);
        return returnOrderNo;
    }

}
