package com.gic.haoban.manage.web.controller.licence;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.licence.LicenceOrderDTO;
import com.gic.haoban.manage.api.dto.licence.LicenceOrderPageDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.LicenceOrderPageQDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.LicenceOrderQDTO;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.api.service.licence.LicenceOrderApiService;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.qo.licence.LicenceOrderPageQO;
import com.gic.haoban.manage.web.qo.licence.LicenceOrderQO;
import com.gic.haoban.manage.web.vo.licence.LicenceOrderPageVO;
import com.gic.haoban.manage.web.vo.licence.LicenceOrderVO;
import com.gic.log.record.anno.GicLogRecord;
import com.gic.log.record.util.GicLogRecordCategoryEnum;
import com.gic.log.record.util.GicLogRecordEvaluationContext;
import com.gic.log.record.util.GicLogRecordOptTypeEnum;
import com.gic.thirdparty.api.dto.ScanPayReqDataDTO;
import com.gic.thirdparty.api.dto.ScanPayResDataDTO;
import com.gic.thirdparty.api.service.Pay4WXService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 企业微信许可账号购买
 *
 * @author jx
 * @since 2023-03-09
 */
@RestController
@RequestMapping("/licence-order")
public class LicenceOrderController {

    private static Logger logger = LogManager.getLogger(LicenceOrderController.class);

    @Autowired
    private LicenceOrderApiService licenceOrderApiService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private Pay4WXService pay4WXService;
    @Autowired
    private Config config;

    /**
     * 查询订单详情
     */
    @RequestMapping("licence-order-detail")
    public RestResponse<LicenceOrderVO> getLicenceOrderDetail(@RequestParam Long orderId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<LicenceOrderDTO> licenceOrderDetail = licenceOrderApiService.getLicenceOrderDetail(orderId, 1);
        LicenceOrderVO licenceOrderVO = JSONObject.parseObject(JSONObject.toJSONString(licenceOrderDetail.getResult()), LicenceOrderVO.class);
        return RestResponse.successResult(licenceOrderVO);
    }

//    /**
//     * 删除订单
//     */
//    @RequestMapping("licence-order-delete")
//    public RestResponse<Boolean> deleteLicenceOrder(@RequestParam Long orderId) {
//        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
//        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
//            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
//        }
//        ServiceResponse<Boolean> booleanServiceResponse = licenceOrderApiService.deleteLicenceOrder(orderId);
//        return RestResponse.successResult(booleanServiceResponse.getResult());
//    }

    /**
     * 新增或者修改订单
     */
    @RequestMapping("licence-order-saveOrUpdate")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_LICENCE_ORDER,
            optType = GicLogRecordOptTypeEnum.HB_1004_01, userFunc = LogRecordUserServiceImpl.class, optPage = "购买企业微信许可账号")
    public RestResponse<String> saveOrUpdateLicenceOrder(@RequestBody LicenceOrderQO licenceOrderQO) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        //金额校验
        Integer integer = licenceOrderQO.checkPrice();
        if (integer == -1) {
            return RestResponse.failure("-9999", "许可账号数量有误！");
        } else if (integer == 0) {
            return RestResponse.failure("-9999", "购买金额计算有误！");
        }
        LicenceOrderQDTO licenceOrderQDTO = JSONObject.parseObject(JSONObject.toJSONString(licenceOrderQO), LicenceOrderQDTO.class);
        licenceOrderQDTO.setEnterpriseId(loginUser.getEnterpriseId());
        licenceOrderQDTO.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        licenceOrderQDTO.setCreatorId(loginUser.getClerkId());
        licenceOrderQDTO.setCreatorName(loginUser.getClerkName());
        String result = licenceOrderApiService.saveOrUpdateLicenceOrder(licenceOrderQDTO).getResult();
        String time = "";
        if (licenceOrderQO.getTimeType() == 1) {
            time = licenceOrderQO.getTimeValue() + "个月";
        } else {
            time = licenceOrderQO.getTimeValue() + "天";
        }
        String logValue = "【购买企微许可账号】：订单编号ZH" + result + ",企业员工账号" + licenceOrderQO.getExternalContactCount() + "个，时长" + time;
        GicLogRecordEvaluationContext.putAttribute("logValue", logValue);
        return RestResponse.successResult(result);
    }

    /**
     * 分页查询订单列表
     */
    @RequestMapping("licence-order-page")
    public RestResponse<Page<LicenceOrderPageVO>> getLicenceOrderPage(@RequestBody LicenceOrderPageQO licenceOrderPageQO) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        String enterpriseId = loginUser.getEnterpriseId();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String clerkName = loginUser.getClerkName();
        LicenceOrderPageQDTO qdto = JSONObject.parseObject(JSONObject.toJSONString(licenceOrderPageQO), LicenceOrderPageQDTO.class);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setCreatorName(clerkName);
        qdto.setType(1);
        ServiceResponse<Page<LicenceOrderPageDTO>> licenceOrderPage = licenceOrderApiService.getLicenceOrderPage(qdto);
        Page<LicenceOrderPageVO> result = PageHelperUtils.changePageToCurrentPage(licenceOrderPage.getResult(), LicenceOrderPageVO.class);
        return RestResponse.successResult(result);
    }

    /**
     * 取消订单/订单已经过期
     */
    @RequestMapping("licence-order-cancel")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_LICENCE_ORDER,
            optType = GicLogRecordOptTypeEnum.HB_1004_02, userFunc = LogRecordUserServiceImpl.class, optPage = "取消订单")
    public RestResponse<Boolean> cancelLicenceOrder(@RequestParam Long orderId, Integer type) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<LicenceOrderDTO> licenceOrderDetail = licenceOrderApiService.getLicenceOrderDetail(orderId, null);
        LicenceOrderDTO dto = licenceOrderDetail.getResult();
        if (null == dto) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_5.getCode()), HaoBanErrCode.ERR_5.getMsg());
        }
        String enterpriseId = loginUser.getEnterpriseId();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String clerkName = loginUser.getClerkName();
        Boolean result = licenceOrderApiService.updateLicenceOrderType(orderId, type, enterpriseId, wxEnterpriseId, clerkName, 1).getResult();
        String logValue = "【取消购买企微许可账号订单】：订单编号" + dto.getOrderNumber() + "，取消时间" + DateUtil.dateToStr(new Date(), DateUtil.FORMAT_DATETIME_19);
        GicLogRecordEvaluationContext.putAttribute("logValue", logValue);
        return RestResponse.successResult(result);
    }

    /**
     * 订单凭证上传
     */
    @RequestMapping("licence-order-voucher-upload")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_LICENCE_ORDER,
            optType = GicLogRecordOptTypeEnum.HB_1004_03, userFunc = LogRecordUserServiceImpl.class, optPage = "上传凭证")
    public RestResponse<Boolean> uploadLicenceOrderVoucher(@RequestParam Long orderId, String voucher) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<LicenceOrderDTO> licenceOrderDetail = licenceOrderApiService.getLicenceOrderDetail(orderId, null);
        LicenceOrderDTO dto = licenceOrderDetail.getResult();
        if (null == dto) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_5.getCode()), HaoBanErrCode.ERR_5.getMsg());
        }
        String enterpriseId = loginUser.getEnterpriseId();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String clerkName = loginUser.getClerkName();
        Boolean result = licenceOrderApiService.uploadLicenceOrderVoucher(orderId, voucher, enterpriseId, wxEnterpriseId, clerkName).getResult();
        String logValue = "【上传购买企微许可账号支付凭证】：订单编号" + dto.getOrderNumber() + "，上传时间" + DateUtil.dateToStr(new Date(), DateUtil.FORMAT_DATETIME_19);
        GicLogRecordEvaluationContext.putAttribute("logValue", logValue);
        return RestResponse.successResult(result);
    }

    /**
     * 支付订单
     */
    @RequestMapping("licence-order-pay-1")
    public RestResponse<Map<String, Object>> payLicenceOrder(@RequestParam Long orderId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        LicenceOrderDTO result = licenceOrderApiService.getLicenceOrderDetail(orderId, 1).getResult();
        if (result == null) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_5.getCode()), HaoBanErrCode.ERR_5.getMsg());
        }
        //判断url是否存在，存在直接返回
        if (null != result.getWxUrl()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("transactionCode", result.getOrderNumber());
            map.put("url", result.getWxUrl());
            map.put("money", result.getPrice());
            return RestResponse.successResult(map);
        }
        Integer money = result.getPrice();
        if (null != loginUser.getPhoneNumber() && Arrays.asList("13456789987", "13429152802","13383841777","13576223447").contains(loginUser.getPhoneNumber())) {
            //测试账号付款一分
            money = 1;
        }
        // 交易订单号
        String transactionCode = result.getOrderNumber();
        ScanPayReqDataDTO scanPayReqData = new ScanPayReqDataDTO("好办平台企业微信许可账号购买", loginUser.getEnterpriseId(),
                transactionCode, money, DateUtil.dateToStr(new Date(), DateUtil.FORMAT_DATETIME_14), "",
                "NATIVE");
        //二维码
        //通知回调的url
        String host = config.getHost();
        // 最后一个分隔符位置
        int lastIndex = host.lastIndexOf("/");
        // 倒数第二个分隔符位置
        int secondLastIndex = host.lastIndexOf("/", lastIndex - 1);
        String subHost = host.substring(0, secondLastIndex + 1);
        String url = subHost + "gic-thirdparty/weixin_payment_result_notice_qywx";
        scanPayReqData.setNotify_url(url);
        ScanPayResDataDTO prePaymentOrderForQYWX = pay4WXService.createPrePaymentOrderForQYWX(scanPayReqData);
        logger.info("微信预支付返回信息：{}", JSON.toJSONString(prePaymentOrderForQYWX));
        if (prePaymentOrderForQYWX == null) {
            logger.info("微信预支付订单二维码生成失败！！");
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_100034.getCode()), HaoBanErrCode.ERR_100034.getMsg());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("transactionCode", transactionCode);
        map.put("url", prePaymentOrderForQYWX.getCode_url());
        map.put("money", money);
        //记录订单号transactionCode和预支付交易会话标识
        licenceOrderApiService.saveTransactionCode(orderId, transactionCode, prePaymentOrderForQYWX.getPrepay_id(), null, null, prePaymentOrderForQYWX.getCode_url());
        return RestResponse.successResult(map);
    }

    /**
     * 支付订单-判断是否支付成功
     */
    @RequestMapping("licence-order-pay-2")
    public RestResponse<Boolean> payLicenceOrder2(@RequestParam Long orderId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        LicenceOrderDTO result = licenceOrderApiService.getLicenceOrderDetail(orderId, 1).getResult();
        if (result == null) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_5.getCode()), HaoBanErrCode.ERR_5.getMsg());
        }
        if (result.getOrderStatus() == 1) {
            return RestResponse.successResult(true);
        }
        return RestResponse.successResult(false);
    }

    /**
     * 查询企业品牌名称
     */
    @RequestMapping("get-enterprise-name")
    public RestResponse<HashMap<String, String>> getEnterpriseName() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        HashMap<String, String> result = new HashMap<>(8);
        //查询gic品牌名称
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(loginUser.getEnterpriseId());
        if (ObjectUtil.isNotNull(enterpriseDTO)) {
            logger.info("gic企业查询返回实体：{}", JSON.toJSONString(enterpriseDTO));
            result.put("enterpriseName", enterpriseDTO.getEnterpriseName());
        }
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(loginUser.getWxEnterpriseId());
        if (ObjectUtil.isNotNull(wxEnterpriseDTO)) {
            logger.info("企业微信查询返回实体：{}", JSON.toJSONString(wxEnterpriseDTO));
            result.put("wxEnterpriseName", wxEnterpriseDTO.getCorpName());
        }
        return RestResponse.successResult(result);
    }

    /**
     * 查询企业是否存在未支付订单
     */
    @RequestMapping("licence-order-isPay")
    public RestResponse<String> isPayLicenceOrder() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<String> payLicenceOrder = licenceOrderApiService.isPayLicenceOrder(loginUser.getWxEnterpriseId());
        return RestResponse.successResult(payLicenceOrder.getResult());
    }

    /**
     * 查询开户信息
     */
    @RequestMapping("get-account-info")
    public RestResponse<HashMap<String, String>> getAccountInfo() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        HashMap<String, String> result = new HashMap<>(8);
        result.put("accountName", config.getAccountName());
        result.put("accountNumber", config.getAccountNumber());
        result.put("bankName", config.getBankName());
        return RestResponse.successResult(result);
    }

    /**
     * 订单编号和企业微信订单编号模糊搜索
     *
     * @param param 模糊查询
     * @param type  0 微信订单编号 1 企业微信订单编号
     * @return
     */
    @RequestMapping("get-order-id-list")
    public RestResponse<List<String>> getOrderIdList(String param, Integer type) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<List<String>> orderIdList = licenceOrderApiService.getOrderIdList(param, type, loginUser.getWxEnterpriseId());
        return RestResponse.successResult(orderIdList.getResult());
    }

    /**
     * 是否显示弹窗  hasPopup 0不弹出  1弹出
     * count 关联数量
     */
    @RequestMapping("licence-order-hasPopup")
    public RestResponse<HashMap<String, Integer>> hasPopup() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        ServiceResponse<HashMap<String, Integer>> response = licenceOrderApiService.hasPopup(loginUser.getWxEnterpriseId());
        return RestResponse.successResult(response.getResult());
    }


}
