package cn.pluss.platform.agentInfo.impl;

import cn.pluss.platform.MerchantRateRecordService;
import cn.pluss.platform.agentInfo.AgentInfoService;
import cn.pluss.platform.cash.CashService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.AgentInfoMapper;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.MD5Util;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.AgentInfo;
import cn.pluss.platform.vo.AgentStaffVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author SSS
 */
@RequiredArgsConstructor
@Service
public class AgentInfoServiceImpl implements AgentInfoService {

    @Autowired
    private UserAppService userAppService;
    @Resource
    private AgentInfoMapper agentInfoMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MerchantRateMapper merchantRateMapper;
    @Autowired
    private CashService cashService;
    @Autowired
    private MerchantRateRecordService merchantRateRecordService;

    @Override
    public Page<AgentInfo> pageData(Page<AgentInfo> page, AgentInfo agentInfo) {
        page.addOrder(OrderItem.desc("ui.createTime"));
        JSONObject pageData = (JSONObject) JSON.toJSON(page);
        List<List<?>> queryData = agentInfoMapper.selectPage(agentInfo, pageData);
        List<AgentInfo> records = (List<AgentInfo>) queryData.get(0);
        page.setRecords(records);
        long total = ((Long) queryData.get(1).get(0));
        page.setTotal(total);
        return page;
    }

    @Override
    public Page<AgentInfo> pagePermissionData(Page<AgentInfo> page, AgentInfo agentInfo) {
        page.addOrder(OrderItem.desc("ui.createTime"));
        JSONObject pageData = (JSONObject) JSON.toJSON(page);
        List<List<?>> queryData = agentInfoMapper.selectPermissionPage(agentInfo, pageData);
        List<AgentInfo> records = (List<AgentInfo>) queryData.get(0);
        page.setRecords(records);
        long total = ((Long) queryData.get(1).get(0));
        page.setTotal(total);
        return page;
    }

    @Override
    public Page<AgentInfo> pageSubData(Page<AgentInfo> page, AgentInfo agentInfo) {
        page.addOrder(OrderItem.desc("ui.createTime"));
        JSONObject pageData = (JSONObject) JSON.toJSON(page);
        List<List<?>> queryData = agentInfoMapper.selectSubAgentPage(agentInfo, pageData);
        List<AgentInfo> records = (List<AgentInfo>) queryData.get(0);
        page.setRecords(records);
        long total = ((Long) queryData.get(1).get(0));
        page.setTotal(total);

        return page;
    }

    @Override
    public AgentInfo getOne(AgentInfo agentInfo) {
        return agentInfoMapper.selectOne(agentInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(AgentInfo agentInfo) {
        if (StringUtils.isEmpty(agentInfo.getLoginName())) {
            throw new MsgException("请输入登录账号");
        }

        if (StringUtils.isEmpty(agentInfo.getPhone())) {
            throw new MsgException("请输入关联手机号");
        }

        if (agentInfo.getUserId() == null) {
            saveAgentInfo(agentInfo);
        } else {
            updateAgentInfo(agentInfo);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(AgentInfo agentInfo) {
        userInfoService.removeById(agentInfo.getUserId());
        QueryWrapper<UserApp> queryWrapperUserApp = new QueryWrapper<UserApp>().eq("userId", agentInfo.getUserId());
        userAppService.remove(queryWrapperUserApp);
        QueryWrapper<MerchantRate> queryWrapperMerchantRate = new QueryWrapper<MerchantRate>().eq("userId", agentInfo.getUserId());
        merchantRateMapper.delete(queryWrapperMerchantRate);
        Cash cash = new Cash();
        cash.setUserId(agentInfo.getUserId());
        cashService.deleteUserIdCash(cash);
    }

    @Override
    public Page<AgentStaffVO> staffPage(Page<AgentStaffVO> page, AgentStaffVO agentStaffVO, OrderItem orderItem) {
        page.getOrders().clear();
        page.addOrder(orderItem);
        page = agentInfoMapper.selectStaffPage(page, agentStaffVO);
        return page;
    }

    /**
     * 查询出相关信息并更新
     *
     * @param agentInfo 超级代理商信息
     */
    private void updateAgentInfo(AgentInfo agentInfo) {
        UserInfo userInfo = userInfoService.getById(agentInfo.getUserId());
        userInfo.setUpdateTime(new Date());
        userInfo.setLoginName(agentInfo.getLoginName());
        userInfo.setPhone(agentInfo.getPhone());

        QueryWrapper<UserApp> queryWrapperUserApp = new QueryWrapper<UserApp>()
                .eq("userId", agentInfo.getUserId());
        UserApp userApp = userAppService.getOne(queryWrapperUserApp);
        userApp.setLevel(3)
                .setIsFixedRate(agentInfo.getIsFixedRate())
                .setLoginName(agentInfo.getLoginName());

        userInfoService.updateUserInfo(userInfo);
        userAppService.updateById(userApp);

        // Cash cash = new Cash();
        // cash.setUserId(agentInfo.getUserId());
        // cash.setUpdateDt(new Date());
        // cash.setUserName(agentInfo.getUserName());
        // cash.setCashAmt(agentInfo.getCashAmt());
        // cashService.updateUserIdCash(cash);

        MerchantRate merchantRate = new MerchantRate().setUserId(agentInfo.getUserId() + "");
        merchantRate = merchantRateMapper.selectOne(new QueryWrapper<>(merchantRate));
        // 补充数据
        if (merchantRate == null) {
            merchantRate = new MerchantRate()
                    .setUserId(userInfo.getId() + "")
                    .setRate(agentInfo.getRate().intValue())
                    .setPreviousRate(agentInfo.getRate().intValue())
                    .setUpdateTime(new Date());
            merchantRateMapper.insert(merchantRate);
        } else {
            merchantRate.setRate(agentInfo.getRate().intValue()).setUpdateTime(new Date()).setPreviousRate(agentInfo.getRate().intValue());
            merchantRateMapper.updateById(merchantRate);
            // 保存修改费率记录
            MerchantRateRecord merchantRateRecord = new MerchantRateRecord();
            merchantRateRecord.setCreateTime(new Date());
            merchantRateRecord.setRate(merchantRate.getRate());
            merchantRateRecord.setUserId(merchantRate.getUserId());
            merchantRateRecordService.save(merchantRateRecord);
        }
    }


    private void saveAgentInfo(AgentInfo agentInfo) {
        Date date = new Date();
        UserInfo userInfo = new UserInfo()
                .setPassword(MD5Util.MD5Encode("123456", "UTF-8"))
                .setLoginName(agentInfo.getLoginName()).setPhone(agentInfo.getPhone())
                .setUpdateTime(date)
                .setCreateTime(date);

        AgentInfo exist = new AgentInfo().setLoginName(agentInfo.getLoginName());
        exist = agentInfoMapper.selectOne(exist);
        if (exist != null) {
            throw new MsgException("该账号已存在");
        }

        exist = new AgentInfo().setPhone(agentInfo.getPhone());
        exist = agentInfoMapper.selectOne(exist);
        if (exist != null) {
            throw new MsgException("该手机号已存在关联代理商");
        }

        userInfoService.saveUserInfo(userInfo);

        if (userInfo.getId() == null) {
            throw new MsgException("插入数据失败！");
        }

        agentInfo.setUserId(userInfo.getId());

        UserApp userApp = new UserApp();
        userApp.setUserType("agent")
                .setUserId(userInfo.getId())
                .setLoginName(agentInfo.getPhone())
                .setInviteNum(getRandomNum())
                .setLevel(3)
                .setSort(1)
                .setIsFixedRate(agentInfo.getIsFixedRate())
                // 默认身份认证状态
                .setStatus(0)
                .setCreateDt(date);
        userAppService.save(userApp);

        if (agentInfo.getCashAmt() != null && !Objects.equals(agentInfo.getCashAmt(), BigDecimal.ZERO)) {
            Cash cash = new Cash();
            cash.setUserId(userInfo.getId());
            cash.setCreateDt(new Date());
            cash.setUpdateDt(new Date());
            cash.setUserName(agentInfo.getUserName());
            cash.setCashAmt(agentInfo.getCashAmt());
            cashService.save(cash);
        }

        MerchantRate merchantRate = new MerchantRate()
                .setUserId(userInfo.getId() + "")
                .setRate(agentInfo.getRate().intValue())
                .setPreviousRate(agentInfo.getRate().intValue())
                .setUpdateTime(new Date());
        merchantRateMapper.insert(merchantRate);
    }

    private String getRandomNum() {
        String inviteNum;
        UserApp condition = new UserApp();

        do {
            inviteNum = StringUtil.genRandomNum(5);
            condition.setInviteNum(inviteNum);
            UserApp userApp = userAppService.queryUserApp(condition);
            if (userApp == null) {
                return inviteNum;
            }
        } while (true);
    }
}
