package com.hys.app.controller.erp.use;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hys.app.framework.exception.ServiceException;

import com.hys.app.framework.util.BeanUtil;
import com.hys.app.framework.util.DateUtil;
import com.hys.app.framework.util.StringUtil;
import com.hys.app.mapper.system.AdminUserMapper;
import com.hys.app.model.erp.dos.OrderDO;

import com.hys.app.model.erp.entity.Company;
import com.hys.app.model.system.dos.AdminUser;
import com.hys.app.pay.ali.AliPayService;
import com.hys.app.pay.ali.PayOrder;
import com.hys.app.pay.ali.PayTypeUrl;
import com.hys.app.pay.ali.WxService;

import com.hys.app.service.erp.CompanyManager;
import com.hys.app.service.erp.OrderManager;
import com.hys.app.util.AliSmsUtil;
import com.hys.app.util.MailSmtpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/admin/erp/pay")
@Api(tags = "订单支付")
@Validated
@AllArgsConstructor
public class PayController {
    private CompanyManager companyManager;
    private AliPayService aliPayService;
    private WxService wxService;
    private AdminUserMapper adminUserMapper;


    @ApiOperation(value = "扫描完获取拉起支付的url")
    @PostMapping("/getCompanyPayUrl")
    public Object getListByScan(@RequestBody @Validated PayTypeUrl payTypeUrl) {
        Company company = companyManager.getById(payTypeUrl.getId());
        if (ObjectUtil.isNull(company)) {
            throw new ServiceException("未查询到公司信息");
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setTraceNo(company.getId().toString());
        payOrder.setSubject("购买公司使用权账号");
        payOrder.setTimeExpire(LocalDateTime.now().plusMinutes(30));
        payOrder.setTotalAmount(company.getThisMoney().doubleValue());
        payOrder.setOrderPayType("company");
        switch (payTypeUrl.getPayType()) {
            case "ali":
                return aliPayService.pay(payOrder);
            case "wx":
                return "暂未开通";
            default:
                return "不支持的支付方式";
        }
    }

    @PostMapping("/aliReturnCall")
    @Transactional(rollbackFor = Exception.class)
    public String aliReturnCall(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        if (aliPayService.checkReturnParam(params)) {
            String passbackParams = URLDecoder.decode(params.get("passback_params"), "UTF-8");
            if ("company".equals(passbackParams)){
                Company company = companyManager.getById(params.get("out_trade_no"));
                company.setEndUseTime(company.getEndUseTime().plusDays(company.getThisDay()));
                company.setThisDay(null);
                company.setThisMoney(null);
                companyManager.updateById(company);
                //给公司创建初始账号
                String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                StringBuilder sb = new StringBuilder();
                Random random = new Random();
                for (int i = 0; i < 6; i++) {
                    int index = random.nextInt(characters.length());
                    sb.append(characters.charAt(index));
                }
                String password = sb.toString();

                //管理员信息入库
                AdminUser adminUser = new AdminUser();
                adminUser.setCompanyId(company.getId());
                adminUser.setUsername("admin");
                adminUser.setRoleId(company.getRoleId());
                adminUser.setFounder(0);
                adminUser.setNickname(company.getName()+"管理员");
                adminUser.setPassword(StringUtil.md5(password + adminUser.getUsername().toLowerCase()));
                adminUser.setDateLine(DateUtil.getDateline());
                adminUser.setUserState(0);
                adminUserMapper.insert(adminUser);
                //todo  用短信和邮件把账号密码发给用户
            }
        }
        return "success";
    }
    @PostMapping("/sendmail")
    public void sendmail(@RequestBody  Map<String,Object> map )  {
        MailSmtpUtil.sendEmail(map.get("toMail").toString(),map.get("subject").toString(),map.get("content").toString());
    }

    @PostMapping("/senSms")
    public void senSms(@RequestBody  Map<String,Object> map ) throws Exception {
        AliSmsUtil.sendSms(map.get("rePhone").toString(),map.get("templateCode").toString(),(Map<String, String>) map.get("map"));
    }
}
