package com.supplier.service.impl;

import com.supplier.mapper.PersonalMapper;
import com.supplier.mapper.WxPayMapper;
import com.supplier.model.*;
import com.supplier.service.PersonalServce;
import com.supplier.util.DesDecry;
import com.supplier.util.SnowflakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PersonalServiceImpl implements PersonalServce {
    //雪花算法
    private SnowflakeUtil snowflakeUtil = new SnowflakeUtil(1, 1, 1);

    @Autowired
    private PersonalMapper personalMapper;

    @Autowired
    private WxPayMapper wxPayMapper;

    @Override
    public Supplier getPresonalMessage(String code) {
        return personalMapper.getPresonalMessage(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePhone(Supplier supplier) {
        personalMapper.updatePhone(supplier);
    }

    @Override
    public int checkCaptcha(Supplier supplier) {
        return personalMapper.checkCaptcha(supplier);
    }

    @Override
    public List<User> seleceWxUserCount(User user) {
        return personalMapper.seleceWxUserCount(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWXUser(User user) {
        personalMapper.addWXUser(user);
    }

    @Override
    public int geThisUserID(String wxid) {
        return personalMapper.geThisUserID(wxid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserWx(User user) {
        personalMapper.updateUserWx(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOffNum(SupplierRelease supplierRelease) {
        supplierRelease.setCode(getSuppileUtil(supplierRelease.getCode()));
        personalMapper.updateOffNum(supplierRelease);
        personalMapper.addOfferNumChild("0", supplierRelease.getCode());//子账户同步
    }

    @Override
    public Map<String, Object> getByNumber() {
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("data", personalMapper.getByNumber());
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> payBlance(String offerNum, String code) {
        Map<String, Object> map = new HashMap<>();
        try{
            Map<String, Object> map1 = personalMapper.getByNumber();
            Supplier supplier = personalMapper.getPresonalMessage(code);
            //判断当前账号是否是主账号 如果不是主账号则将编号改成主账号操作
            String codeMaster = code;
            if(!supplier.getAccountAssociated().equals("0")){
                codeMaster = supplier.getAccountAssociated();
                supplier.setBalanceOf(personalMapper.getPresonalMessage(supplier.getAccountAssociated()).getBalanceOf());
            }
            Double offerVal = (Integer.parseInt(offerNum) * Double.parseDouble(String.valueOf(map1.get("power_unit"))));
            if(Double.parseDouble(supplier.getBalanceOf()) < offerVal){
                map.put("msg", "500");
                map.put("errMsg", "主账号余额不足请充值");
                return map;
            }
            //购买信息
            BuyOfferNum buyOfferNum = new BuyOfferNum()
                    .setOfferNum(offerNum)
                    .setCode(code)
                    .setPayAmount(offerVal.toString())
                    .setUuid(snowflakeUtil.nextId() + "")
                    .setPayType("余额购买");
            personalMapper.addBuyOfferNum(buyOfferNum); //购买次数记录
            personalMapper.minusBalanceOf(offerVal.toString(), codeMaster);//修改金额
            personalMapper.addOfferNum(offerNum, codeMaster);//增加次数
            wxPayMapper.updateBalanceChild(Double.parseDouble("0"), codeMaster);//子账号同步金额
            personalMapper.addOfferNumChild("0", codeMaster);//子账号次数同步
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBuyOfferNum(BuyOfferNum buyOfferNum) {
        personalMapper.addBuyOfferNum(buyOfferNum); //购买次数记录
    }

    @Override
    public Map<String, Object> balanceOfPayments(String code) {
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("data", personalMapper.balanceOfPayments(code));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> topUpNum(String code) {
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("data", personalMapper.topUpNum(code));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> getEmployees(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        try{
            supplier.setPage((supplier.getPage() - 1) * supplier.getLimit());
            List<Supplier> list = new ArrayList<>();
            for(Supplier supplier1 : personalMapper.getEmployees(supplier)){
                supplier1.setPhone(DesDecry.decrypt(supplier1.getPhone()));
                list.add(supplier1);
            }
            map.put("data", list);
            map.put("count", personalMapper.getEmployeesCount(supplier));
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> editorEmployees(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        try{
            int count = personalMapper.checkCaptchaPhone(supplier);//校验验证码是否正确
            if(count > 0) {
                Supplier supplier1 = personalMapper.checkUser(supplier);//验证是否第一次登录
                if(supplier.getCode().equals(supplier1.getCode())){
                    map.put("errMsg", "操作无效不能将管理员账号设置成子账号！");
                    map.put("msg", "300");
                    return map;
                }
                if(supplier1.getCode() == null){//如果为空的话增加
                    supplier.setHeadpir("https://lidaotech.oss-cn-beijing.aliyuncs.com/test/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220622112747.png")
                            .setCaptcha("null")
                            .setName("TUYAGYS_" + supplier1.getId())
                            .setCode(SerialNumber("SUP", supplier1.getId() + ""));
                } else {
                    supplier.setCaptcha("null");
                }
                Supplier supplier2 = personalMapper.getPresonalMessage(supplier.getCode()); //查询主账号各项信息
                supplier.setOfferNum(supplier2.getOfferNum())
                        .setBalanceOf(supplier2.getBalanceOf())
                        .setCompany(supplier2.getCompany())
                        .setRepresentative(supplier2.getRepresentative())
                        .setDocumentType(supplier2.getDocumentType())
                        .setIdNumber(supplier2.getIdNumber())
                        .setRegisteredCapital(supplier2.getRegisteredCapital())
                        .setSetUpTheDate(supplier2.getSetUpTheDate())
                        .setResidence(supplier2.getResidence())
                        .setBusinessLicense(supplier2.getBusinessLicense())
                        .setIdCardJust(supplier2.getIdCardJust())
                        .setIdCardReverse(supplier2.getIdCardReverse())
                        .setAccountAssociated(supplier.getCode())
                        .setPermissionsType("1")
                        .setCode(null);
                personalMapper.editorEmployees(supplier);
                map.put("msg", "200");
            } else {
                map.put("errMsg", "手机号或验证码不正确");
                map.put("msg", "300");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> delChild(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        try{
            personalMapper.delChild(supplier);
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    @Override
    public Map<String, Object> editorModify(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        try{
            personalMapper.editorModify(supplier);
            map.put("msg", "200");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    /**
     * 用户编号
     * @param id
     * @return
     */
    public static String SerialNumber(String letter, String id){
        for(int i = 0; i < 8 - id.length(); i++){
            letter = letter + "0";
        }
        return letter + id;
    }

    public String getSuppileUtil(String code){
        String result = "";
        Supplier supplier = personalMapper.getPresonalMessage(code);//查询供应商信息
        //如果操作人不是父级账号 则查询父级账号的信息 将父级余额放入对象中
        if(!supplier.getAccountAssociated().equals("0")){
            result = supplier.getAccountAssociated();
        } else {
            result = code;
        }
        return result;
    }
}
