package com.ym.mec.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.entity.HfMember;
import com.ym.mec.biz.dal.page.HfMemberQueryInfo;
import com.ym.mec.biz.service.HfMemberService;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.thirdparty.adapay.ConfigInit;
import com.ym.mec.thirdparty.adapay.CorpMember;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.thirdparty.adapay.Payment;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

@RequestMapping("adapay")
@Api(tags = "汇付服务")
@RestController
public class AdapayController extends BaseController {

    @Autowired
    private HfMemberService hfMemberService;
    @Autowired
    private SysConfigDao sysConfigDao;

    @Value("${spring.profiles.active:dev}")
    private String profiles;

    @ApiOperation(value = "企业用户列表")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('adapay/queryPage')")
    public HttpResponseResult<PageInfo<HfMember>> queryPage(HfMemberQueryInfo queryInfo) {
        return succeed(hfMemberService.queryPage(queryInfo));
    }

    @ApiOperation("新建企业用户")
    @PostMapping(value = "createMember")
    @PreAuthorize("@pcs.hasPermissions('adapay/createMember')")
    public HttpResponseResult<Map<String, Object>> createMember(HfMember member) throws Exception {
        if (!profiles.equals("prod")) {
            return failed("仅生产环境可用");
        }
        if (member.getMultipartFile().isEmpty()) {
            return failed("证件压缩文件必传");
        }
        File file = new File("/var/tmp/" + member.getMultipartFile().getOriginalFilename());
        InputStream inputStream = member.getMultipartFile().getInputStream();

        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            IOUtils.copy(inputStream, fos);
            return succeed(hfMemberService.createMember(member, file));
        } catch (Exception e) {
            return failed(e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            boolean delete = file.delete();
        }
    }

    @ApiOperation("修改企业用户(状态是failed才能修改)")
    @PostMapping(value = "updateMember")
    @PreAuthorize("@pcs.hasPermissions('adapay/updateMember')")
    public HttpResponseResult<Map<String, Object>> updateMember(HfMember member) throws Exception {
        if (!profiles.equals("prod")) {
            return failed("仅生产环境可用");
        }
        if (member.getMultipartFile().isEmpty()) {
            return failed("证件压缩文件必传");
        }
        File file = new File("/var/tmp/" + member.getMultipartFile().getOriginalFilename());
        InputStream inputStream = member.getMultipartFile().getInputStream();

        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            IOUtils.copy(inputStream, fos);
            return succeed(hfMemberService.updateMember(member, file));
        } catch (Exception e) {
            return failed(e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            boolean delete = file.delete();
        }
    }


    @ApiOperation("绑定结算账户（succeeded 状态才能使用）")
    @PostMapping(value = "createSettleAccount")
    @PreAuthorize("@pcs.hasPermissions('adapay/createSettleAccount')")
    public HttpResponseResult<Map<String, Object>> createSettleAccount(String memberId, String cardNo, String bankCode) throws Exception {
        if (!profiles.equals("prod")) {
            return failed("仅生产环境可用");
        }
        try {
            return succeed(hfMemberService.createSettleAccount(memberId, cardNo, bankCode));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }

    @ApiOperation("查询企业用户信息")
    @GetMapping(value = "getMemberInfo")
    @PreAuthorize("@pcs.hasPermissions('adapay/getMemberInfo')")
    public HttpResponseResult<Map<String, Object>> getMemberInfo(String memberId) throws Exception {
        return succeed(CorpMember.executeQueryMember(memberId));
    }


    @ApiOperation("导出对账单")
    @GetMapping(value = "exportBill")
    @PreAuthorize("@pcs.hasPermissions('adapay/exportBill')")
    public void exportBill(Date startTime, Date endTime, HttpServletResponse response) throws Exception {
        long createdGte = startTime.getTime();
        long createdLte = DateUtil.getLastSecondWithDay(endTime).getTime();
        int pageIndex = 1;
        List<Map<String, Object>> data = new ArrayList<>();
        while (profiles.equals("prod")) {
            Map<String, Object> paymentList = Payment.queryList(pageIndex, createdGte, createdLte);
            JSONArray payments = (JSONArray) paymentList.get("payments");
            if (!paymentList.get("status").equals("succeeded")) {
                throw new BizException("查询失败，请重试");
            }

            if (payments != null && payments.size() > 0) {
                for (Object payment : payments) {
                    Map<String, Object> paymentMap = (Map<String, Object>) payment;
                    if (!paymentMap.get("status").equals("succeeded")) {
                        continue;
                    }
                    paymentMap.put("created_time", DateUtil.timeStamp2Date(paymentMap.get("created_time").toString(), null));
                    if (paymentMap.get("pay_channel").equals("alipay_qr")) {
                        paymentMap.put("pay_channel", "支付宝正扫");
                    } else if (paymentMap.get("pay_channel").equals("alipay_wap")) {
                        paymentMap.put("pay_channel", "支付宝H5支付");
                    } else {
                        paymentMap.put("pay_channel", "微信公众号支付");
                    }

                    if (paymentMap.get("status").equals("pending")) {
                        paymentMap.put("status", "交易处理中");
                    } else if (paymentMap.get("status").equals("succeeded")) {
                        paymentMap.put("status", "交易成功");
                    } else {
                        paymentMap.put("status", "交易失败");
                    }
                    if (paymentMap.get("pay_mode").equals("delay")) {
                        if (!paymentMap.containsKey("payment_confirms")) {
                            Map<String, Object> confirmMap = Payment.queryConfirmList(paymentMap.get("id").toString());
                            if (confirmMap.containsKey("payment_confirms")) {
                                paymentMap.put("payment_confirms", confirmMap.get("payment_confirms"));
                            }
                        }
                        if (!paymentMap.containsKey("payment_confirms")) {
                            paymentMap.put("memo", "没有提交分账信息，请联系技术核查");
                            data.add(paymentMap);
                            continue;
                        }
                        JSONArray confirms = (JSONArray) paymentMap.get("payment_confirms");
                        for (Object confirm : confirms) {
                            Map<String, Object> divMemberMap = (Map<String, Object>) confirm;
                            paymentMap.put("fee_amt", divMemberMap.get("fee_amt"));
                            divMemberMap.putAll(paymentMap);

                            JSONArray divMembers = (JSONArray) divMemberMap.get("div_members");
                            Map<String, Object> divMember = (Map<String, Object>) divMembers.get(0);
                            divMemberMap.putAll(divMember);
                            if (divMemberMap.get("member_id").equals("0")) {
                                divMemberMap.put("member_id", ConfigInit.merNo);
                            }
                            data.add(divMemberMap);
                        }
                    } else {
                        JSONArray divMembers = (JSONArray) paymentMap.get("div_members");
                        for (Object divMember : divMembers) {
                            Map<String, Object> divMemberMap = (Map<String, Object>) divMember;
                            divMemberMap.putAll(paymentMap);
                            if (divMemberMap.get("member_id").equals("0")) {
                                divMemberMap.put("member_id", ConfigInit.merNo);
                            }
                            if (divMemberMap.get("fee_flag").equals("N")) {
                                divMemberMap.put("fee_amt", "0.00");
                            }
                            data.add(divMemberMap);
                        }
                    }
                }
            }
            if (paymentList.get("has_more").equals(false)) {
                break;
            }
            pageIndex++;
        }

        OutputStream outputStream = response.getOutputStream();
        try {
            String[] header = {"支付流水号", "订单号", "支付渠道", "交易金额", "商户号", "分润金额", "是否承担手续费", "手续费", "第三方订单号", "支付宝/微信订单号", "交易时间", "交易状态", "备注"};
            String[] body = {"id", "order_no", "pay_channel", "pay_amt", "member_id", "amount", "fee_flag", "fee_amt", "party_order_id", "out_trans_id", "created_time", "status", ""};

            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, data);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=bill-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation("修改每月最大收款金额（succeeded 状态才能使用）")
    @PostMapping(value = "updateMonthMaxReceipt")
    @PreAuthorize("@pcs.hasPermissions('adapay/updateMonthMaxReceipt')")
    public HttpResponseResult<HfMember> updateMonthMaxReceipt(Integer id, BigDecimal monthMaxReceipt, String routeMemberId,Integer organId) throws Exception {
        HfMember hfMember = hfMemberService.get(id);
        if (hfMember == null) {
            return failed("您修改的数据不存在");
        }
        hfMember.setMonthMaxReceipt(monthMaxReceipt);
        hfMember.setRouteMemberId(routeMemberId);
        hfMember.setRouteOrganId(organId);
        hfMember.setUpdateTime(new Date());
        if (hfMemberService.update(hfMember) <= 0) {
            return failed("修改失败，请重试");
        }
        return succeed(hfMember);
    }
}
