package com.fs.store.controller;

import java.util.Date;
import java.util.List;

import com.fs.common.core.domain.R;
import com.fs.common.utils.IPUtils;
import com.fs.store.domain.FsUser;
import com.fs.store.enums.BillDetailEnum;
import com.fs.store.param.FsUseExtractQueryParam;
import com.fs.store.service.IFsUserBillService;
import com.fs.store.service.IFsUserService;
import com.fs.store.vo.FsUserExtractVO;
import com.fs.wx.pay.config.WxPayProperties;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.store.domain.FsUserExtract;
import com.fs.store.service.IFsUserExtractService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户提现Controller
 * 
 * @author fs
 * @date 2022-03-15
 */
@RestController
@RequestMapping("/store/userExtract")
public class FsUserExtractController extends BaseController
{
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IFsUserExtractService fsUserExtractService;
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private IFsUserBillService billService;
    /**
     * 查询用户提现列表
     */
    @PreAuthorize("@ss.hasPermi('store:userExtract:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUseExtractQueryParam param)
    {
        startPage();
        List<FsUserExtractVO> list = fsUserExtractService.selectFsUserExtractListVOQuery(param);
        return getDataTable(list);
    }

    /**
     * 导出用户提现列表
     */
    @PreAuthorize("@ss.hasPermi('store:userExtract:export')")
    @Log(title = "用户提现", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsUserExtract fsUserExtract)
    {
        List<FsUserExtract> list = fsUserExtractService.selectFsUserExtractList(fsUserExtract);
        ExcelUtil<FsUserExtract> util = new ExcelUtil<FsUserExtract>(FsUserExtract.class);
        return util.exportExcel(list, "userExtract");
    }

    /**
     * 获取用户提现详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:userExtract:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(fsUserExtractService.selectFsUserExtractById(id));
    }


    @PreAuthorize("@ss.hasPermi('store:userExtract:audit')")
    @PostMapping("/audit")
    @Transactional
    public R audit(@RequestBody FsUserExtract fsUserExtract, HttpServletRequest servletRequest)
    {
        FsUserExtract extract=fsUserExtractService.selectFsUserExtractById(fsUserExtract.getId());
        if(extract.getStatus().equals(0)){
            FsUser user=fsUserService.selectFsUserById(extract.getUserId());
            if(fsUserExtract.getStatus()==1){
                WxPayConfig payConfig = new WxPayConfig();
                payConfig.setAppId(wxPayProperties.getAppId());
                payConfig.setMchId(wxPayProperties.getMchId());
                payConfig.setMchKey(wxPayProperties.getMchKey());
                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setKeyPath(null);
                payConfig.setNotifyUrl(wxPayProperties.getNotifyUrl());
                wxPayService.setConfig(payConfig);
                EntPayService entPayService=wxPayService.getEntPayService();
                EntPayRequest request=new EntPayRequest();
                request.setAppid(wxPayProperties.getAppId());
                request.setMchId(wxPayProperties.getMchId());
                request.setOpenid(user.getMaOpenId());
                request.setCheckName("NO_CHECK");
                request.setSpbillCreateIp(IPUtils.getIpAddr(servletRequest));
                request.setReUserName(user.getRealName());
                request.setPartnerTradeNo(extract.getId().toString());
                request.setDescription("会员提现");
                request.setAmount(WxPayUnifiedOrderRequest.yuanToFen(extract.getExtractPrice().toString()));
                try {
                    EntPayResult result=entPayService.entPay(request);
                    if(result.getResultCode().equals(0)){
                        extract.setStatus(1);
                        fsUserExtractService.updateFsUserExtract(extract);
                    }
                    return R.ok();
                } catch (WxPayException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    e.printStackTrace();
                    return R.error(e.getMessage());
                }

            }
            else if(fsUserExtract.getStatus()==-1){
                extract.setStatus(-1);
                extract.setFailMsg(fsUserExtract.getFailMsg());
                fsUserExtractService.updateFsUserExtract(extract);
                user.setNowMoney(user.getNowMoney().add(extract.getExtractPrice()));
                fsUserService.updateFsUser(user);
                //插入流水
                billService.addBill(user.getUserId(), BillDetailEnum.CATEGORY_1.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),extract.getExtractPrice().doubleValue(),user.getNowMoney().doubleValue(),"提现申请驳回",extract.getId().toString(),0l);
                return R.ok();
            }
            else{
                return R.error("非法操作");
            }
        }
        else{
            return R.error("非法操作");
        }

    }


}
