package com.ruoyi.buyerapi.service.impl;

import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.buyerapi.domain.BuyerFileInfo;
import com.ruoyi.buyerapi.domain.BuyerUserRole;
import com.ruoyi.buyerapi.mapper.*;
import com.ruoyi.buyerapi.service.IBuyerDeptService;
import com.ruoyi.buyerapi.service.IBuyerRoleService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.commonapi.service.impl.SmsUtilAliImplService;
import com.ruoyi.system.domain.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.buyerapi.domain.BuyerCompanyInfo;
import com.ruoyi.buyerapi.service.IBuyerCompanyInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员企业信息Service业务层处理
 *
 * @author zq
 * @date 2022-09-20
 */
@Service
public class BuyerCompanyInfoServiceImpl implements IBuyerCompanyInfoService {
    @Autowired
    private BuyerCompanyInfoMapper buyerCompanyInfoMapper;

    @Autowired
    private BuyerUserMapper buyerUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SmsUtilAliImplService smsUtilAliImplService;

    @Autowired
    private IBuyerDeptService buyerDeptService;

    @Autowired
    private IBuyerRoleService buyerRoleService;

    @Autowired
    private BuyerUserRoleMapper buyerUserRoleMapper;

    @Autowired
    private BuyerFileInfoMapper buyerFileInfoMapper;

    /**
     * 查询会员企业信息
     *
     * @param id 会员企业信息主键
     * @return 会员企业信息
     */
    @Transactional
    @Override
    public BuyerCompanyInfo selectBuyerCompanyInfoById(String id) {
        BuyerCompanyInfo buyerCompanyInfo = buyerCompanyInfoMapper.selectBuyerCompanyInfoById(id);
        // 查询关联文件信息
        List<BuyerFileInfo> buyerFileInfos = buyerFileInfoMapper.selectBuyerFileInfoByLinkId(id);
        if (buyerCompanyInfo != null) {
            buyerCompanyInfo.setBuyerFileInfos(buyerFileInfos);
            Date expireTimeDate = buyerCompanyInfo.getExpireTime();
            Date nowDate = DateUtils.getNowDate();
            int compare = DateUtil.compare(expireTimeDate, nowDate);
            // 计算到期时间
            String endLength = "";
            long day = 0;
            long hour = 0;
            long minute = 0;
            if (compare > 0) {
                day = DateUtil.between(expireTimeDate, nowDate, DateUnit.DAY);
                hour = DateUtil.between(expireTimeDate, nowDate, DateUnit.HOUR) % 24;
                minute = DateUtil.between(expireTimeDate, nowDate, DateUnit.MINUTE) % 60;
            }
            endLength = day + "天" + hour + "小时" + minute + "分";
            buyerCompanyInfo.setEndLength(endLength);
            return buyerCompanyInfo;
        } else {
            return null;
        }
    }

    /**
     * 查询会员企业信息
     *
     * @param userId 用户id
     * @return 会员企业信息
     */
    @Override
    public BuyerCompanyInfo selectBuyerCompanyInfoByUserId(long userId) {
        BuyerCompanyInfo buyerCompanyInfo = buyerCompanyInfoMapper.selectBuyerCompanyInfoByUserId(userId);
        if (buyerCompanyInfo != null) {
            Date expireTimeDate = buyerCompanyInfo.getExpireTime();
            Date nowDate = DateUtils.getNowDate();
            int compare = DateUtil.compare(expireTimeDate, nowDate);
            // 计算到期时间
            String endLength = "";
            long day = 0;
            if (compare > 0) {
                day = DateUtil.between(expireTimeDate, nowDate, DateUnit.DAY);
            }
            endLength = day + "天";
            buyerCompanyInfo.setEndLength(endLength);
        }
        return buyerCompanyInfo;
    }

    /**
     * 查询会员企业信息列表
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 会员企业信息
     */
    @Transactional
    @Override
    public List<BuyerCompanyInfo> selectBuyerCompanyInfoList(BuyerCompanyInfo buyerCompanyInfo) {
        List<BuyerCompanyInfo> companyInfos = buyerCompanyInfoMapper.selectBuyerCompanyInfoList(buyerCompanyInfo);
        for (BuyerCompanyInfo companyInfo : companyInfos) {
            // 查询关联文件信息
            List<BuyerFileInfo> buyerFileInfos = buyerFileInfoMapper.selectBuyerFileInfoByLinkId(companyInfo.getId());
            companyInfo.setBuyerFileInfos(buyerFileInfos);
            Date expireTimeDate = companyInfo.getExpireTime();
            Date nowDate = DateUtils.getNowDate();
            int compare = DateUtil.compare(expireTimeDate, nowDate);
            // 计算到期时间
            String endLength = "";
            long day = 0;
            long hour = 0;
            long minute = 0;
            if (compare > 0) {
                day = DateUtil.between(expireTimeDate, nowDate, DateUnit.DAY);
                hour = DateUtil.between(expireTimeDate, nowDate, DateUnit.HOUR) % 24;
                minute = DateUtil.between(expireTimeDate, nowDate, DateUnit.MINUTE) % 60;
            }
            endLength = day + "天" + hour + "小时" + minute + "分";
            companyInfo.setEndLength(endLength);
        }
        return companyInfos;
    }

    /**
     * 会员趋势统计
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 会员趋势
     */
    @Override
    public int selectTrendBuyerCompanyInfo(BuyerCompanyInfo buyerCompanyInfo) {
        return buyerCompanyInfoMapper.selectTrendBuyerCompanyInfo(buyerCompanyInfo);
    }

    /**
     * 查询会员量
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 会员量
     */
    @Override
    public int selectCountBuyerCompanyInfo(BuyerCompanyInfo buyerCompanyInfo) {
        return buyerCompanyInfoMapper.selectCountBuyerCompanyInfo(buyerCompanyInfo);
    }

    /**
     * 新增会员企业信息
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBuyerCompanyInfo(BuyerCompanyInfo buyerCompanyInfo) {
        buyerCompanyInfo.setCreateTime(DateUtils.getNowDate());
        SysUser sysUser = buyerUserMapper.selectUserByUserName(buyerCompanyInfo.getUserName());
        // 后台端新增会员
        if (sysUser == null) {
            // 新增用户信息
            sysUser = new SysUser();
            sysUser.setCompanyId(buyerCompanyInfo.getId());
            sysUser.setUserName(buyerCompanyInfo.getUserName());
            sysUser.setNickName(buyerCompanyInfo.getUserName());
            sysUser.setPhonenumber(buyerCompanyInfo.getPhoneNumber());
            sysUser.setPassword(SecurityUtils.encryptPassword(buyerCompanyInfo.getPassword()));
            buyerUserMapper.insertUser(sysUser);

            // 新增关联文件
            List<BuyerFileInfo> buyerFileInfos = buyerCompanyInfo.getBuyerFileInfos();
            if (buyerFileInfos != null && buyerFileInfos.size() > 0) {
                for (BuyerFileInfo buyerFileInfo : buyerFileInfos) {
                    buyerFileInfo.setId(IdUtil.simpleUUID());
                    buyerFileInfo.setCreateTime(DateUtils.getNowDate());
                    buyerFileInfo.setCreateBy(SecurityUtils.getUsername());
                    buyerFileInfo.setLinkId(buyerCompanyInfo.getId());
                }
                buyerFileInfoMapper.batchInsertBuyerFileInfo(buyerFileInfos);
            }

            // 新增企业信息
            buyerCompanyInfo.setUserId(sysUser.getUserId());
            return buyerCompanyInfoMapper.insertBuyerCompanyInfo(buyerCompanyInfo);
        }
        // 平台端提交企业认证
        else {
            // 修改关联文件
            List<BuyerFileInfo> buyerFileInfos = buyerCompanyInfo.getBuyerFileInfos();
            if (buyerFileInfos != null && buyerFileInfos.size() > 0) {
                for (BuyerFileInfo buyerFileInfo : buyerFileInfos) {
                    buyerFileInfo.setId(IdUtil.simpleUUID());
                    buyerFileInfo.setUpdateTime(DateUtils.getNowDate());
                    buyerFileInfo.setUpdateBy(SecurityUtils.getUsername());
                    buyerFileInfo.setLinkId(buyerCompanyInfo.getId());
                }
                buyerFileInfoMapper.deleteBuyerFileInfoByLinkId(buyerCompanyInfo.getId());
                buyerFileInfoMapper.batchInsertBuyerFileInfo(buyerFileInfos);
            } else if (buyerFileInfos != null && buyerFileInfos.size() == 0) {
                buyerFileInfoMapper.deleteBuyerFileInfoByLinkId(buyerCompanyInfo.getId());
            }
            // 新增企业信息
            buyerCompanyInfo.setUserId(sysUser.getUserId());
            buyerCompanyInfoMapper.insertBuyerCompanyInfo(buyerCompanyInfo);
            sysUser.setCompanyId(buyerCompanyInfo.getId());
            // 更新用户信息
            return buyerUserMapper.updateUser(sysUser);
        }
    }

    /**
     * 修改会员企业信息
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBuyerCompanyInfo(BuyerCompanyInfo buyerCompanyInfo) {
        buyerCompanyInfo.setUpdateTime(DateUtils.getNowDate());
        buyerCompanyInfo.setAuthTime(DateUtils.getNowDate());
        buyerCompanyInfo.setReviewerId(SecurityUtils.getUserId());
        // 审核通过
        if (buyerCompanyInfo.getAuthStatus() != null && buyerCompanyInfo.getAuthStatus().equals("1")) {
            // 新增默认部门
            SysDept sysDept = new SysDept();
            sysDept.setAncestors("0");
            sysDept.setDeptName(buyerCompanyInfo.getName());
            sysDept.setLeader(buyerCompanyInfo.getNickName());
            sysDept.setPhone(buyerCompanyInfo.getPhoneNumber());
            sysDept.setCompanyId(buyerCompanyInfo.getId());
            buyerDeptService.insertRootDept(sysDept);

            // 新增默认角色（超级管理员）
            SysRole role = new SysRole();
            role.setRoleName("超级管理员");
            role.setRoleKey("admin");
            role.setRoleSort("1");
            role.setMenuCheckStrictly(true);
            role.setDeptCheckStrictly(true);
            role.setStatus("0");
            role.setRemark("超级管理员");
            role.setCompanyId(buyerCompanyInfo.getId());
            buyerRoleService.insertRootRole(role);

            // 新增用户默认角色
            BuyerUserRole buyerUserRole = new BuyerUserRole();
            buyerUserRole.setUserId(buyerCompanyInfo.getUserId());
            buyerUserRole.setRoleId(role.getRoleId());
            List<BuyerUserRole> buyerUserRoles = new ArrayList<>();
            buyerUserRoles.add(buyerUserRole);
            buyerUserRoleMapper.batchUserRole(buyerUserRoles);

            // 更新企业会员信息
            return buyerCompanyInfoMapper.updateBuyerCompanyInfo(buyerCompanyInfo);
        } else {
            // 更新企业会员信息
            String unit = buyerCompanyInfo.getUnit();
            Date expireTime = buyerCompanyInfo.getExpireTime();
            Date nowDate = DateUtils.getNowDate();
            // 过期时间和当日时间比较
            int compare = DateUtil.compare(expireTime, nowDate);
            expireTime = compare > 0 ? expireTime : nowDate;
            // 重新设置会员企业到期时间
            if (unit != null) {
                switch (unit) {
                    case "year":
                        expireTime = DateUtil.offset(expireTime, DateField.YEAR, buyerCompanyInfo.getDuration());
                        break;
                    case "month":
                        expireTime = DateUtil.offset(expireTime, DateField.MONTH, buyerCompanyInfo.getDuration());
                        break;
                    case "day":
                        expireTime = DateUtil.offset(expireTime, DateField.DAY_OF_MONTH, buyerCompanyInfo.getDuration());
                        break;
                    case "hour":
                        expireTime = DateUtil.offset(expireTime, DateField.HOUR, buyerCompanyInfo.getDuration());
                        break;
                }
            }
            buyerCompanyInfo.setExpireTime(expireTime);
            buyerCompanyInfo.setUpdateTime(DateUtils.getNowDate());
            if (buyerCompanyInfo.getId() == null) {
                buyerCompanyInfo.setId(SecurityUtils.getCompanyId());
            }
            return buyerCompanyInfoMapper.updateBuyerCompanyInfo(buyerCompanyInfo);
        }
    }

    /**
     * 充值会员企业信息
     *
     * @param buyerCompanyInfo 会员企业信息
     * @return 结果
     */
    @Override
    public int RechargeBuyerCompanyInfo(BuyerCompanyInfo buyerCompanyInfo) {
        String unit = buyerCompanyInfo.getUnit();
        Date expireTime = buyerCompanyInfo.getExpireTime();
        Date nowDate = DateUtils.getNowDate();
        // 过期时间和当日时间比较
        int compare = DateUtil.compare(expireTime, nowDate);
        expireTime = compare > 0 ? expireTime : nowDate;
        // 重新设置会员企业到期时间
        switch (unit) {
            case "year":
                expireTime = DateUtil.offset(expireTime, DateField.YEAR, buyerCompanyInfo.getDuration());
                break;
            case "month":
                expireTime = DateUtil.offset(expireTime, DateField.MONTH, buyerCompanyInfo.getDuration());
                break;
            case "day":
                expireTime = DateUtil.offset(expireTime, DateField.DAY_OF_MONTH, buyerCompanyInfo.getDuration());
                break;
            case "hour":
                expireTime = DateUtil.offset(expireTime, DateField.HOUR, buyerCompanyInfo.getDuration());
                break;
        }
        buyerCompanyInfo.setExpireTime(expireTime);
        buyerCompanyInfo.setIsExpire("0");
        buyerCompanyInfo.setUpdateTime(DateUtils.getNowDate());
        return buyerCompanyInfoMapper.updateBuyerCompanyInfo(buyerCompanyInfo);
    }

    /**
     * 批量删除会员企业信息
     *
     * @param ids 需要删除的会员企业信息主键
     * @return 结果
     */
    @Override
    public int deleteBuyerCompanyInfoByIds(String[] ids) {
        return buyerCompanyInfoMapper.deleteBuyerCompanyInfoByIds(ids);
    }

    /**
     * 删除会员企业信息信息
     *
     * @param id 会员企业信息主键
     * @return 结果
     */
    @Override
    public int deleteBuyerCompanyInfoById(String id) {
        return buyerCompanyInfoMapper.deleteBuyerCompanyInfoById(id);
    }
}
