package com.fs.his.controller;

import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.IPUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.core.config.WxPayProperties;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.FsUserExtract;
import com.fs.his.param.FsUserExtractParam;
import com.fs.his.service.IFsUserBillService;
import com.fs.his.service.IFsUserExtractService;
import com.fs.his.service.IFsUserService;
import com.fs.his.vo.FsUserExtractVO;
import com.fs.hisStore.enums.BillDetailEnum;
import com.fs.hisStore.service.IFsUserBillScrmService;
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.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户提现管理Controller
 *
 * @author fs
 * @date 2023-06-25
 */
@RestController
@RequestMapping("/his/userExtract")
public class FsUserExtractController extends BaseController
{
    @Autowired
    private IFsUserExtractService fsUserExtractService;

    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private IFsUserBillScrmService billService;

    /**
     * 查询用户提现管理列表
     */
    @PreAuthorize("@ss.hasPermi('his:userExtract:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserExtractParam fsUserExtract)
    {
        startPage();
        List<FsUserExtractVO> list = fsUserExtractService.selectFsUserExtractListVO(fsUserExtract);
        return getDataTable(list);
    }

    /**
     * 导出用户提现管理列表
     */
    @PreAuthorize("@ss.hasPermi('his: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, "用户提现管理数据");
    }

    /**
     * 获取用户提现管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('his:userExtract:query')")
    @GetMapping(value = "/{extractId}")
    public AjaxResult getInfo(@PathVariable("extractId") String extractId)
    {
        return AjaxResult.success(fsUserExtractService.selectFsUserExtractByExtractId(extractId));
    }

    /**
     * 新增用户提现管理
     */
    @PreAuthorize("@ss.hasPermi('his:userExtract:add')")
    @Log(title = "用户提现管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsUserExtract fsUserExtract)
    {
        return toAjax(fsUserExtractService.insertFsUserExtract(fsUserExtract));
    }

    /**
     * 审核
     */
    @PreAuthorize("@ss.hasPermi('his:userExtract:edit')")
    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUserExtract fsUserExtract)
    {
        return toAjax(fsUserExtractService.updateFsUserExtract(fsUserExtract));
    }

    /**
     * 删除用户提现管理
     */
    @PreAuthorize("@ss.hasPermi('his:userExtract:remove')")
    @Log(title = "用户提现管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{extractIds}")
    public AjaxResult remove(@PathVariable String[] extractIds)
    {
        return toAjax(fsUserExtractService.deleteFsUserExtractByExtractIds(extractIds));
    }



    @PreAuthorize("@ss.hasPermi('his:userExtract:audit')")
    @PostMapping("/audit")
    @Transactional
    public R audit(@RequestBody FsUserExtract fsUserExtract, HttpServletRequest servletRequest)
    {
        FsUserExtract extract=fsUserExtractService.selectFsUserExtractByExtractId(fsUserExtract.getExtractId());
        if(extract.getStatus().equals(0)){
            FsUser user=fsUserService.selectFsUserById(Long.valueOf(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.getExtractId().toString());
                request.setDescription("会员提现");
                request.setAmount(WxPayUnifiedOrderRequest.yuanToFen(extract.getExtractPrice().toString()));
                try {
                    EntPayResult result=entPayService.entPay(request);
                    if(result.getResultCode().equals(0)){
                        extract.setStatus(1L);
                        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(-1L);
                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(),user.getNowMoney(),"提现申请驳回",extract.getExtractId().toString(),0l);
                return R.ok();
            }
            else{
                return R.error("非法操作");
            }
        }
        else{
            return R.error("非法操作");
        }

    }
}
