package com.zcloud.modules.custormerInfo.service.impl;
 import cn.hutool.core.bean.BeanUtil;
 import com.alibaba.fastjson.JSONObject;
 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.exception.ZException;
 import com.zcloud.common.middleware.MiddlewareBean;
 import com.zcloud.common.utils.*;
 import com.zcloud.datasource.annotation.DataSource;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerAuditRecordsDao;
 import com.zcloud.modules.custormerInfo.dao.BusCustomerUserDao;
 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.service.BusCustomerAuditRecordsService;
 import com.zcloud.modules.custormerInfo.service.BusCustomerInfoService;
 import com.zcloud.modules.sys.dao.SysUserDao;
 import com.zcloud.modules.sys.dao.SysUserRoleDao;
 import com.zcloud.modules.sys.entity.SysUserEntity;
 import com.zcloud.modules.sys.entity.SysUserRoleEntity;
 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.transaction.annotation.Transactional;
 import org.springframework.util.ObjectUtils;

 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;

/**
 * @Author makejava
 * @Desc 客户企业审核记录表(BusCustomerAuditRecords)表服务实现类
 * @Date 2024-03-29 19:30:07
 */
@Service("busCustomerAuditRecordsService")
public class BusCustomerAuditRecordsServiceImpl extends ServiceImpl<BusCustomerAuditRecordsDao, BusCustomerAuditRecordsEntity> implements BusCustomerAuditRecordsService {

    @Autowired
    private BusCustomerInfoService busCustomerInfoService;

    @Autowired
    private MiddlewareBean middlewareBean;

    @Autowired
    private BusCustomerUserDao busCustomerUserDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private RedisUtils redisUtils;

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

		return baseMapper.selectOne(queryWrapper);
	}

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

		return baseMapper.selectList(queryWrapper);
	}

    @Override
    @DataSource("slave1")
    public PageUtils listPage(Map<String, Object> params) {
        Page<Map<String,Object>> page = new Page<>(Integer.parseInt(params.get("curPage").toString()),Integer.parseInt(params.get("limit").toString()));
        params.put("isDelete",0);
        IPage<BusCustomerAuditRecordsEntity> ipage = baseMapper.listPage(page,params);
        return new PageUtils(ipage);
    }


   @Override
	public void delete(String customerAuditRecordsId,String userId){
		UpdateWrapper<BusCustomerAuditRecordsEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("customer_audit_records_id",customerAuditRecordsId);

		BusCustomerAuditRecordsEntity busCustomerAuditRecords = new BusCustomerAuditRecordsEntity();
		busCustomerAuditRecords.setOperator(userId);
		busCustomerAuditRecords.setIsDelete(1);

		this.update(busCustomerAuditRecords, updateWrapper);
	}

    @Override
    @DataSource("master")
    @Transactional(rollbackFor = Exception.class)
    public void addAndUpdateInfo(BusCustomerAuditRecordsEntity param,String userId) throws Exception {
        BusCustomerInfoService busCustomerInfoService =  ((BusCustomerInfoService) SpringContextUtils.getBean("busCustomerInfoService"));

        BusCustomerInfoEntity oldInfo = busCustomerInfoService.getById(param.getCustomerinfoId());
        BusCustomerInfoEntity busCustomerInfo = new BusCustomerInfoEntity();
        BeanUtil.copyProperties(param,busCustomerInfo);

        if (param.getStatus() == 1 && !ObjectUtils.isEmpty(oldInfo) && ObjectUtils.isEmpty(oldInfo.getNumber()) && ObjectUtils.isEmpty(oldInfo.getSecretKey())) {// 初次审核通过给这两个字段赋值
            int number = busCustomerInfoService.getNumber();
            busCustomerInfo.setSecretKey(this.get32UUID());
            String code = "LAZ-" + DateUtil.getDays() + "-" + number;
            busCustomerInfo.setNumber(code);
        }

        // 意向客户审核通过 修改类型
        if (!ObjectUtils.isEmpty(param.getType()) && param.getType() == 2 && param.getStatus() == 1) {
            busCustomerInfo.setType(1);
        }

        // 更新主表信息
        busCustomerInfoService.updateById(busCustomerInfo);
        BusCustomerInfoEntity byId = busCustomerInfoService.getById(busCustomerInfo.getCustomerinfoId());

        if (param.getStatus() == 1) {// 如果审核通过，建立企业和用户绑定关系
            //判断该企业是否已经生成账号
            SysUserEntity compUser = sysUserDao.selectOne(Wrappers.<SysUserEntity>lambdaQuery()
                    .eq(SysUserEntity::getCustomerinfoId, byId.getCustomerinfoId())
                    .eq(SysUserEntity::getIsDelete, 0)
                    .last("limit 1"));

            if (ObjectUtils.isEmpty(compUser)) { //审核通过后，创建以企业名称为用户名的账号
                SysUserEntity user = new SysUserEntity();
                user.setUserId(Tools.get32UUID());
                user.setPassword(new Sha256Hash("Aa@123456", byId.getCorpinfoName()).toHex());
                user.setCreator(userId);
                user.setStatus(1);
                user.setEmail(byId.getCustomerinfoEmail());
                user.setIsImprove(1);
                user.setCustomerinfoId(byId.getCustomerinfoId());
                user.setUsername(byId.getCorpinfoName());
                user.setName(byId.getCorpinfoName());
                user.setType("2");

                //保存账号角色信息
                SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                sysUserRoleEntity.setId(Tools.get32UUID());
                sysUserRoleEntity.setUserId(user.getUserId());
                sysUserRoleEntity.setRoleId("ce844c521c253687b1d8bbff8bbf3cb7");//企业角色
                if (2 == byId.getCustomerinfoType()) {
                    sysUserRoleEntity.setRoleId("e783225c5132e1c6adc738a72a2b5d7f"); //代理角色
                }

                sysUserDao.insert(user);
                sysUserRoleDao.insert(sysUserRoleEntity);

                //缓存redis
                redisUtils.set("user_" + user.getUserId(), user.getName(), -1L);
            } else {
                compUser.setUsername(byId.getCorpinfoName());
                compUser.setName(byId.getCorpinfoName());
                compUser.setEmail(byId.getCustomerinfoEmail());
                sysUserDao.updateById(compUser);

                //缓存redis
                redisUtils.set("user_" + compUser.getUserId(), compUser.getName(), -1L);
            }

            //缓存redis
            redisUtils.set("corp_" + byId.getCustomerinfoId(), byId.getCorpinfoName(), -1L);

            //获取用户是否绑定企业
            BusCustomerUserEntity busCustomerUserEntity = busCustomerUserDao.selectOne(Wrappers.<BusCustomerUserEntity>lambdaQuery()
                    .eq(BusCustomerUserEntity::getCustomerinfoId, param.getCustomerinfoId())
                    .eq(BusCustomerUserEntity::getUserId, byId.getCreator())
                    .eq(BusCustomerUserEntity::getIsDelete, 0));

            if (ObjectUtils.isEmpty(busCustomerUserEntity)) {
                BusCustomerUserEntity busCustomerUser = new BusCustomerUserEntity();
                busCustomerUser.setUserId(byId.getCreator());
                busCustomerUser.setCustomerinfoId(param.getCustomerinfoId());
                busCustomerUser.setIsAdmin(true);
                busCustomerUser.setIsDelete(0);
                busCustomerUser.setCreator(param.getOperator());
                busCustomerUser.setCreateTime(DateUtil.date2Str(new Date()));
                busCustomerUserDao.insert(busCustomerUser);

                //赋予企业角色
                SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                sysUserRoleEntity.setUserId(byId.getCreator());
                sysUserRoleEntity.setCustomerinfoId(param.getCustomerinfoId());
                sysUserRoleEntity.setRoleId("ce844c521c253687b1d8bbff8bbf3cb7"); // 企业管理员角色

                //如果是机构 赋予代理角色
                if (byId.getCustomerinfoType() == 2) {
                    sysUserRoleEntity.setRoleId("e783225c5132e1c6adc738a72a2b5d7f"); // 代理角色
                }
                sysUserRoleDao.insert(sysUserRoleEntity);
            }
        }

        String result = HttpRequestUtil.doPost(middlewareBean.getUrl() + "/busCustomerInfo/updateInfo", JSONObject.toJSONString(byId));
        if (result == null) {
            throw new ZException("数据同步错误");
        }

        param.setCustomerAuditRecordsId(Tools.get32UUID());
        param.setCreator(userId);
        // 保存记录表信息
        this.save(param);
    }

    private String get32UUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }
}
