package com.supplier.service.impl;

import com.supplier.controller.WxRefundContoller;
import com.supplier.mapper.PersonalMapper;
import com.supplier.mapper.SupplierReleaseMapper;
import com.supplier.mapper.WxPayMapper;
import com.supplier.model.*;
import com.supplier.service.WxPayService;
import com.supplier.util.AmountUtil;
import com.supplier.util.DesDecry;
import com.supplier.util.DesEncry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxPayServiceImpl implements WxPayService {
    @Autowired
    private WxPayMapper wxPayMapper;
    @Autowired
    private PersonalMapper personalMapper;
    @Autowired
    private SupplierReleaseMapper supplierReleaseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pay(WxPay wxPay) {
        wxPayMapper.deletePay(wxPay);
        wxPayMapper.pay(wxPay);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payUpdate(WxPay wxPay) {
        wxPayMapper.payUpdate(wxPay);
    }

    @Override
    public int getPolling(String releUuid) {
        return wxPayMapper.getPolling(releUuid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void wxCash(WxWithdrawal wxWithdrawal) {
        wxPayMapper.wxCash(wxWithdrawal);
    }

    @Override
    public WxPay getRefundVal(String releUuid) {
        return wxPayMapper.getRefundVal(releUuid);
    }

    @Override
    public Map<String, Object> getUserRefund(WxRefund wxRefund) {
        Map<String, Object> map = new HashMap<>();
        try{
            wxRefund.setPage((wxRefund.getPage() - 1) * wxRefund.getLimit());
            List<WxRefund> list = wxPayMapper.getUserRefund(wxRefund);
            List<WxRefund> list1 = new ArrayList<>();
            for(WxRefund wxRefund1 : list){
                wxRefund1.setReleaseUuid(DesEncry.encrypt(DesEncry.encrypt(wxRefund1.getReleaseUuid())));
                list1.add(wxRefund1);
            }
            map.put("data", list1);
            map.put("count", wxPayMapper.getUserRefundCount(wxRefund));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRefundType(String releUuid, String refundState) {
        wxPayMapper.updateRefundType(releUuid, refundState);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> refusedRefund(WxRefund wxRefund) {
        Map<String, Object> map = new HashMap<>();
        try{
            wxRefund.setReleaseUuid(DesDecry.decrypt(DesDecry.decrypt(wxRefund.getReleaseUuid())));
            WxRefund refund = wxPayMapper.getRefund(wxRefund);
            if(refund.getRefundState().equals("1")){
                map.put("msg", "500");
                map.put("errMsg", "该退款申请已同意，操作无效");
                return map;
            }
            //如果是全额退款 则改变定制单状态为全额退款状态
            if(refund.getRefundType().equals("2")){
                SupplierRelease supplierRelease = new SupplierRelease().setUuid(DesDecry.decrypt(DesDecry.decrypt(wxRefund.getReleaseUuid())));
                List<SupplierRelease> list = supplierReleaseMapper.getSupplierRelease(supplierRelease);
                SupplierRelease supplierRelease1 = new SupplierRelease()
                        .setCode(list.get(0).getCode())
                        .setOrderType("14")
                        .setDemandUuid(list.get(0).getDemandUuid());
                supplierReleaseMapper.updatePrivateType(supplierRelease1);
            }
            if(wxRefund.getRefundState().equals("1")){
                WxPay wxPay = wxPayMapper.getRefundVal(wxRefund.getReleaseUuid());//获取付该报价单付款的信息
                Supplier supplier = personalMapper.getPresonalMessage(wxPay.getCode());//查询供应商信息
                //如果操作人不是父级账号 则查询父级账号的信息 将父级余额放入对象中
                if(!supplier.getAccountAssociated().equals("0")){
                    Supplier supplier1 = personalMapper.getPresonalMessage(supplier.getAccountAssociated());//查询父级信息
                    wxPay.setBalanceOf(supplier1.getBalanceOf());
                    wxPay.setCode(supplier1.getCode());
                }
                if(null == wxPay){
                    map.put("msg", "500");
                    map.put("errMsg", "未查询到该报价单的支付信息");
                    return map;
                }
                if(Double.parseDouble(refund.getRefundFee()) > Double.parseDouble(wxPay.getTotalFee())){
                    map.put("msg", "500");
                    map.put("errMsg", "退款金额大于支付金额");
                    return map;
                }
                if(Double.parseDouble(refund.getRefundFee()) > Double.parseDouble(wxPay.getBalanceOf())){
                    map.put("msg", "500");
                    map.put("errMsg", "主账号余额不足，请先充值");
                    return map;
                }
                Map<String, Object> map1 = WxRefundContoller.refund(refund.getRefundFee(), wxPay);
                if(map1.get("msg").equals("200")){
                    String bigDecimal2 = AmountUtil.moneySub(wxPay.getBalanceOf(), refund.getRefundFee());//退款后的账户余额
                    wxPayMapper.subtractBalance(bigDecimal2, wxPay.getCode());//供应商余额变更
                    wxPayMapper.updateBalanceChild(Double.parseDouble(bigDecimal2), wxPay.getCode());//子账号余同步
                    wxPayMapper.updateRefundType(wxRefund.getReleaseUuid(), wxRefund.getRefundState());//退款状态改变
                    return map1;
                } else {
                    return map1;
                }
            } else {
                wxPayMapper.updateRefundType(wxRefund.getReleaseUuid(), wxRefund.getRefundState());
            }
            map.put("msg", "200");
            map.put("data", "操作成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buySupplierBalance(WxPay wxPay) {
        try{
            wxPayMapper.buySupplierBalance(wxPay);//充值记录
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBuySupplier(WxPay buySupplier) {
        try{
            buySupplier.setCode(getSuppileUtil(buySupplier.getCode()));
            wxPayMapper.updateBuySupplier(buySupplier); //完善充值记录
            //供应商余额增加
            wxPayMapper.updateBalance(Double.parseDouble(buySupplier.getTotalFee()), buySupplier.getCode());//金额充值
            wxPayMapper.updateBalanceChild(Double.parseDouble(buySupplier.getTotalFee()), buySupplier.getCode());//子账户余额同步
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public int getTopUp(WxPay wxPay) {
        return wxPayMapper.getTopUp(wxPay);
    }

    @Override
    public void getTopUpTimeOut() {
        try{
            //充值记录
            List<WxPay> list = wxPayMapper.getTopUpTimeOut();
            for(WxPay wxPay : list){
                wxPayMapper.delTopOut(wxPay);
            }
            //购买次数记录
            List<BuyOfferNum> list1 = wxPayMapper.getOfferNumTimeOut();
            for(BuyOfferNum buyOfferNum : list1){
                wxPayMapper.delOfferNum(buyOfferNum);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBuyOfferNum(BuyOfferNum buyOfferNum) {
        try{
            buyOfferNum.setCode(getSuppileUtil(buyOfferNum.getCode()));
            wxPayMapper.updateBuyOfferNum(buyOfferNum);//完善购买记录
            //供应商报价单次数增加
            personalMapper.addOfferNum(buyOfferNum.getOfferNum(), buyOfferNum.getCode());//增加次数
            personalMapper.addOfferNumChild(buyOfferNum.getOfferNum(), buyOfferNum.getCode());//子账号次数同步
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> getOfferNum(BuyOfferNum buyOfferNum) {
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("data", wxPayMapper.getOfferNum(buyOfferNum));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> getAuditRefund(WxRefund wxRefund) {
        Map<String, Object> map = new HashMap<>();
        try{
            wxRefund.setPage((wxRefund.getPage() - 1) * wxRefund.getLimit());
            List<WxRefund> list = wxPayMapper.getAuditRefund(wxRefund);
            List<WxRefund> list1 = new ArrayList<>();
            for(WxRefund wxRefund1 : list){
                wxRefund1.setReleaseUuid(DesEncry.encrypt(DesEncry.encrypt(wxRefund1.getReleaseUuid())));
                list1.add(wxRefund1);
            }
            map.put("data", list1);
            map.put("count", wxPayMapper.getAuditRefundCount(wxRefund));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSupplierBalanceOf(Supplier supplier) {
        supplier.setCode(getSuppileUtil(supplier.getCode()));
        wxPayMapper.addSupplierBalanceOf(supplier);
        wxPayMapper.addSupplierBalanceOfChild(supplier);//子账号同步
    }

    @Override
    public Map<String, Object> getTopUpRecord(TopUpRecord topUpRecord) {
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("msg", "200");
            map.put("data", wxPayMapper.getTopUpRecord(topUpRecord));
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    /**
     * 判断当前账号是否是主账号 如果不是主账号则将编号改成主账号操作
     * @param code 参数
     * @return 返回结果
     */
    public String getSuppileUtil(String code){
        String result = "";
        Supplier supplier = personalMapper.getPresonalMessage(code);//查询供应商信息
        //如果操作人不是父级账号 则查询父级账号的信息 将父级余额放入对象中
        if(!supplier.getAccountAssociated().equals("0")){
            result = supplier.getAccountAssociated();
        } else {
            result = code;
        }
        return result;
    }
}
