package com.zcloud.modules.custormerInfo.service.impl;

 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zcloud.common.utils.DateUtil;
 import com.zcloud.common.utils.PageUtils;
 import com.zcloud.common.utils.R;
 import com.zcloud.common.utils.Tools;
 import com.zcloud.datasource.annotation.DataSource;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerAuditRecordsDao;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerInfoDao;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerUserDao;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerinfoRequireDao;
 import com.zcloud.modules.custormerInfo.entity.BusCustomerAuditRecordsEntity;
 import com.zcloud.modules.custormerInfo.entity.BusCustomerInfoEntity;
 import com.zcloud.modules.custormerInfo.entity.BusCustomerUserEntity;
 import com.zcloud.modules.custormerInfo.entity.BusCustomerinfoRequireEntity;
 import com.zcloud.modules.custormerInfo.service.BusCustomerInfoService;
 import com.zcloud.modules.custormerInfo.vo.BusCustomerInfoVo;
 import com.zcloud.modules.sys.dao.BusImgfilesDao;
 import com.zcloud.modules.sys.dao.SysUserDao;
 import com.zcloud.modules.sys.dao.SysUserRoleDao;
 import com.zcloud.modules.sys.entity.BusImgfilesEntity;
 import com.zcloud.modules.sys.entity.SysUserEntity;
 import com.zcloud.modules.sys.entity.SysUserRoleEntity;
 import org.apache.commons.lang.StringUtils;
 import org.apache.shiro.crypto.hash.Sha256Hash;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import org.springframework.util.CollectionUtils;
 import org.springframework.util.ObjectUtils;
 import org.springframework.transaction.annotation.Transactional;

 import javax.tools.Tool;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;

/**
 * @Author makejava
 * @Desc 客户企业信息(BusCustomerInfo)表服务实现类
 * @Date 2024-03-29 15:49:53
 */
@Service("busCustomerInfoService")
public class BusCustomerInfoServiceImpl extends ServiceImpl<BusCustomerInfoDao, BusCustomerInfoEntity> implements BusCustomerInfoService {

    @Autowired
    private BusImgfilesDao busImgfilesDao;
    @Autowired
    private BusCustomerAuditRecordsDao busCustomerAuditRecordsDao;

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private BusCustomerinfoRequireDao busCustomerinfoRequireDao;
    @Autowired
    private BusCustomerUserDao busCustomerUserDao;

    @Override
    public BusCustomerInfoEntity queryByFlexibleParams(String paramName, Object paramValue) {
        QueryWrapper<BusCustomerInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(paramName, paramValue); // 根据传入的参数名和参数值动态构建查询条件
        queryWrapper.eq("is_delete", 0);
        queryWrapper.last("limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

	@Override
	public List<BusCustomerInfoEntity> queryListByFlexibleParams(String paramName, Object paramValue) {
		QueryWrapper<BusCustomerInfoEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(paramName, paramValue); // 根据传入的参数名和参数值动态构建查询条件

		return baseMapper.selectList(queryWrapper);
	}

    @Override
    @DataSource("slave1")
    public PageUtils listPage(Map<String, Object> params) {
        if (params.get("surplusSum") != null) {
            long surplusSum = Integer.valueOf(params.get("surplusSum").toString());
            surplusSum = surplusSum * 1024 * 1024 * 1024 * 1024;
            params.put("surplusSum", surplusSum);
        }
        Page<Map<String,Object>> page = new Page<>(Integer.parseInt(params.get("curPage").toString()),Integer.parseInt(params.get("limit").toString()));
        params.put("isDelete",0);
        if (params.get("status") != null){
            // 获取状态 转为数组
            String status = params.get("status").toString();
            String[] statusArr = status.split(",");
            params.put("statusArr",statusArr);
        }
        IPage<BusCustomerInfoVo> ipage = baseMapper.listPage(page,params);
        for(BusCustomerInfoVo busCustomerInfoVo:ipage.getRecords()){
            if(StringUtils.isNotEmpty(busCustomerInfoVo.getFilepathListString())){
                List<String> fileList = Arrays.asList(busCustomerInfoVo.getFilepathListString().split(","));
                busCustomerInfoVo.setFilepathList(fileList);
            }

        }



        return new PageUtils(ipage);
    }

    /**列表(全部)
     * @param pd
     * @throws Exception
     */
    public List<BusCustomerInfoEntity> listAllDoMain(BusCustomerInfoEntity pd)throws Exception{
        return baseMapper.listAllDoMain(pd);
    }


   @Override
	public void delete(String customerinfoId,String userId){
		UpdateWrapper<BusCustomerInfoEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("customerinfo_id",customerinfoId);

		BusCustomerInfoEntity busCustomerInfo = new BusCustomerInfoEntity();
		busCustomerInfo.setOperator(userId);
		busCustomerInfo.setIsDelete(1);

		this.update(busCustomerInfo, updateWrapper);
	}

    @Override
    @DataSource("slave1")
    public BusCustomerInfoVo getById(String customerinfoId) {
        BusCustomerInfoVo busCustomerInfoVo = baseMapper.getById(customerinfoId);

        List<BusCustomerinfoRequireEntity> list = busCustomerinfoRequireDao.findByInfoId(customerinfoId);
        busCustomerInfoVo.setRequireList(list);

        if(StringUtils.isNotEmpty(busCustomerInfoVo.getFilepathListString())){
            List<String> fileList = Arrays.asList(busCustomerInfoVo.getFilepathListString().split(","));
            busCustomerInfoVo.setFilepathList(fileList);
        }
        List<BusImgfilesEntity> busImgfilesEntities = busImgfilesDao.selectList(Wrappers.<BusImgfilesEntity>lambdaQuery()
                .eq(BusImgfilesEntity::getForeignKey, busCustomerInfoVo.getCustomerinfoId())
                .eq(BusImgfilesEntity::getType, 104));
        if (!CollectionUtils.isEmpty(busImgfilesEntities)) {
            busCustomerInfoVo.setIndustryQualificationList(busImgfilesEntities.stream().map(BusImgfilesEntity::getFilepath).collect(Collectors.toList()));
        }
        //获取最新的审核驳回记录
        BusCustomerAuditRecordsEntity busCustomerAuditRecordsEntity = busCustomerAuditRecordsDao.selectOne(Wrappers.<BusCustomerAuditRecordsEntity>lambdaQuery()
                .eq(BusCustomerAuditRecordsEntity::getCustomerinfoId, customerinfoId)
                .eq(BusCustomerAuditRecordsEntity::getStatus, -2)
                .orderByDesc(BusCustomerAuditRecordsEntity::getCreateTime)
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(busCustomerAuditRecordsEntity)) {
            busCustomerInfoVo.setStatusContent(busCustomerAuditRecordsEntity.getStatusContent());
        }

        if(BigDecimal.ZERO.compareTo(busCustomerInfoVo.getSurplusSum())<0){
            BigDecimal dividend = new BigDecimal("1024");
            BigDecimal result = BigDecimal.ZERO;
            for(int i = 0;i<2;i++){
                dividend = dividend.multiply(new BigDecimal(1024));
            }
            result = busCustomerInfoVo.getSurplusSum().divide(dividend,2, RoundingMode.HALF_UP);
            busCustomerInfoVo.setSurplusSum(result);
        }
        return busCustomerInfoVo;
    }

    @Override
    @DataSource("slave1")
    public PageUtils getCourseCustomerInfoListPage(Map<String, String> params) {
        Page<Map<String,Object>> page = new Page<>(Integer.parseInt(params.get("curPage")),Integer.parseInt(params.get("limit")));
//        List<String> customerIds = busOrderDao.selectOrderSalesRecordsBycurriculumId(params.get("curriculumId"));
//        if (customerIds.size() == 0) {
//            customerIds = null;
//        }
        IPage<BusCustomerInfoEntity> ipage = baseMapper.selectCustomerBycurriculumIdListPage(page, null, params.get("corpinfoName"));
        return new PageUtils(ipage);
    }

    @Override
    public int getNumber() {
        return baseMapper.getNumber();
    }



    @Override
    public PageUtils trafficListPage(Map<String, String> params) {
        Page<Map<String,Object>> page = new Page<>(Integer.parseInt(params.get("curPage")),Integer.parseInt(params.get("limit")));
        IPage<BusCustomerInfoVo> ipage = baseMapper.trafficListPage(page, params);
        return new PageUtils(ipage);
    }

    @Override
    @Transactional
    public R saveCustomerInfo(BusCustomerInfoEntity param) {
        param.setStatus(1);
        if (param.getTemporary() == 0) {
            SysUserEntity sysUserEntity = sysUserDao.queryByUserName(param.getCorpinfoName());
            if (!ObjectUtils.isEmpty(sysUserEntity)) {
                return R.error(200, "该企业已注册，请联系管理员处理");
            }
            param.setCustomerinfoId(Tools.get32UUID());
            saveRequire(param.getRequireList(), param.getCustomerinfoId(), param.getOperator());
            save(param);
            return R.ok();
        } else if (param.getTemporary() == 1){
            SysUserEntity sysUserEntity = sysUserDao.queryByUserName(param.getCorpinfoName());
            if (!ObjectUtils.isEmpty(sysUserEntity)) {
                return R.error(200, "该企业已注册，请联系管理员处理");
            }

            int number = getNumber();
            param.setSecretKey(Tools.get32UUID());
            String code = "LAZ-" + DateUtil.getDays() + "-" + number;
            param.setNumber(code);

            //保存账号
            SysUserEntity user = new SysUserEntity();
            user.setUserId(Tools.get32UUID());
            user.setPassword(new Sha256Hash("666666", param.getCorpinfoName()).toHex());
            user.setCreator(user.getUserId());
            user.setStatus(1);
            user.setIsAgent(0);
            user.setIsImprove(1);
            user.setUsername(param.getCorpinfoName());
            user.setName(param.getCorpinfoName());
            user.setType("2");
            user.setCustomerinfoId(param.getCustomerinfoId());
            sysUserDao.insert(user);

            //保存账号角色信息
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setId(Tools.get32UUID());
            sysUserRoleEntity.setUserId(user.getUserId());
            sysUserRoleEntity.setRoleId("ce844c521c253687b1d8bbff8bbf3cb7");//管理员角色

            param.setCustomerinfoId(Tools.get32UUID());
            saveRequire(param.getRequireList(), param.getCustomerinfoId(), param.getOperator());
            save(param);

            sysUserRoleDao.insert(sysUserRoleEntity);

            BusCustomerUserEntity busCustomerUser = new BusCustomerUserEntity();
            busCustomerUser.setUserId(user.getUserId());
            busCustomerUser.setCustomerinfoId(param.getCustomerinfoId());
            busCustomerUser.setIsAdmin(true);
            busCustomerUser.setIsDelete(0);
            busCustomerUser.setCreator(param.getOperator());
            busCustomerUser.setCreateTime(DateUtil.date2Str(new Date()));
            busCustomerUserDao.insert(busCustomerUser);

            return R.ok();
        } else {
            return R.error(200, "参数错误");
        }
    }

    @Override
    public R updateCustomerInfo(BusCustomerInfoEntity param) {
        param.setStatus(1);
        if (param.getTemporary() == 0) {

            BusCustomerInfoEntity busCustomerInfoEntity = baseMapper.selectById(param.getCustomerinfoId());
            if (!busCustomerInfoEntity.getCorpinfoName().equals(param.getCorpinfoName())) {
                SysUserEntity sysUserEntity = sysUserDao.queryByUserName(param.getCorpinfoName());
                if (!ObjectUtils.isEmpty(sysUserEntity)) {
                    return R.error(200, "该企业已注册，请联系管理员处理");
                }
            }

            saveRequire(param.getRequireList(), param.getCustomerinfoId(), param.getOperator());
            updateById(param);
            return R.ok();
        } else if (param.getTemporary() == 1){

            BusCustomerInfoEntity busCustomerInfoEntity = baseMapper.selectById(param.getCustomerinfoId());
            if (!busCustomerInfoEntity.getCorpinfoName().equals(param.getCorpinfoName())) {
                SysUserEntity sysUserEntity = sysUserDao.queryByUserName(param.getCorpinfoName());
                if (!ObjectUtils.isEmpty(sysUserEntity)) {
                    return R.error(200, "该企业已注册，请联系管理员处理");
                }
            }

            //保存账号
            SysUserEntity user = new SysUserEntity();
            user.setUserId(Tools.get32UUID());
            user.setPassword(new Sha256Hash("666666", param.getCorpinfoName()).toHex());
            user.setCreator(user.getUserId());
            user.setStatus(1);
            user.setIsAgent(0);
            user.setIsImprove(1);
            user.setUsername(param.getCorpinfoName());
            user.setName(param.getCorpinfoName());
            user.setType("2");
            user.setCustomerinfoId(param.getCustomerinfoId());
            sysUserDao.insert(user);

            //保存账号角色信息
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setId(Tools.get32UUID());
            sysUserRoleEntity.setUserId(user.getUserId());
            sysUserRoleEntity.setRoleId("ce844c521c253687b1d8bbff8bbf3cb7");//管理员角色

            saveRequire(param.getRequireList(), param.getCustomerinfoId(), param.getOperator());
            updateById(param);

            sysUserRoleDao.insert(sysUserRoleEntity);

            BusCustomerUserEntity busCustomerUser = new BusCustomerUserEntity();
            busCustomerUser.setUserId(user.getUserId());
            busCustomerUser.setCustomerinfoId(param.getCustomerinfoId());
            busCustomerUser.setIsAdmin(true);
            busCustomerUser.setIsDelete(0);
            busCustomerUser.setCreator(param.getOperator());
            busCustomerUser.setCreateTime(DateUtil.date2Str(new Date()));
            busCustomerUserDao.insert(busCustomerUser);

            return R.ok();
        } else {
            return R.error(200, "参数错误");
        }
    }

    @Override
    public List<BusCustomerInfoEntity> listAll(BusCustomerInfoEntity param) {
        QueryWrapper<BusCustomerInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0)
                .eq("status",1)
                .orderByAsc("corpinfo_name");
        return baseMapper.selectList(queryWrapper);
    }


    private void saveRequire(List<BusCustomerinfoRequireEntity> list, String id, String operator) {
        busCustomerinfoRequireDao.delete(new QueryWrapper<BusCustomerinfoRequireEntity>().eq("customerinfo_id", id));
        for (BusCustomerinfoRequireEntity e : list) {
            if (Tools.isEmpty(e.getRequireName()) && Tools.isEmpty(e.getRequireTime())) {
                continue;
            }
            e.setCustomerinfoId(id);
            e.setCustomerinfoRequireId(Tools.get32UUID());
            e.setCreator(operator);
            e.setCreateTime(DateUtil.date2Str(new Date()));
            e.setOperator(operator);
            e.setOperatTime(DateUtil.date2Str(new Date()));
            e.setIsDelete(0);
            busCustomerinfoRequireDao.insert(e);
        }
    }

}
