package com.yeejoin.amos.boot.module.tcm.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.tcm.api.dto.AccountDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.BasePersonRegisterDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzsBaseIndividualityDto;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzsBaseIndividuality;
import com.yeejoin.amos.boot.module.tcm.api.enums.EnterpriseEnums;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsBaseIndividualityMapper;
import com.yeejoin.amos.boot.module.tcm.api.service.ITzsBaseIndividualityService;
import com.yeejoin.amos.boot.module.tcm.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.tcm.flc.biz.service.impl.RegUnitInfoServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-08-31
 */
@Slf4j
@Service
public class TzsBaseIndividualityServiceImpl extends BaseService<TzsBaseIndividualityDto, TzsBaseIndividuality, TzsBaseIndividualityMapper> implements ITzsBaseIndividualityService {

    @Autowired
    RegUnitInfoServiceImpl regUnitInfoService;

    @Autowired
    StartPlatformTokenService startPlatformTokenService;

    /**
     * 分页查询
     */
    public Page<TzsBaseIndividualityDto> queryForTzsBaseIndividualityPage(Page<TzsBaseIndividualityDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<TzsBaseIndividualityDto> queryForTzsBaseIndividualityList() {
        return this.queryForList("", false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void personRegister(BasePersonRegisterDto dto) {
        startPlatformTokenService.setRequestContext();
        dto.setName(dto.getRealName());
        dto.setUnitCode(dto.getCredentialsType() + "_" + dto.getCredentialsNum());
        String unitType = StringUtils.join(dto.getUnitTypeList(), ",");
        String unitTypeCode = StringUtils.join(dto.getUnitTypeCodeList(), ",");
        CompanyModel companyInfo = new CompanyModel();
        companyInfo.setAgencyCode("tzs");
        companyInfo.setParentId(Long.parseLong(dto.getManagementUnitId()));
        companyInfo.setLevel("company");
        companyInfo.setCompanyName(dto.getCredentialsNum() + "_" + dto.getRealName());
        companyInfo.setCompanyCode(dto.getUnitCode());
        companyInfo.setCompanyType(unitType);
        try {
            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.create(companyInfo);
            if (companyResult == null || companyResult.getResult() == null) {
                throw new BadRequest("平台单位注册失败");
            }
            CompanyModel company = companyResult.getResult();
            dto.setAmosCompanySeq(company.getSequenceNbr().toString());
            AccountDto accountDto = new AccountDto();
            accountDto.setCompanyId(company.getSequenceNbr());
            accountDto.setUnitTypeCode(unitTypeCode);
            accountDto.setAdminTel(dto.getAdminTel());
            accountDto.setPwd(dto.getAdminLoginPwd());
            accountDto.setLoginName(dto.getAdminLoginName());
            accountDto.setAdminUserName(dto.getRealName());
            AgencyUserModel user = regUnitInfoService.createUser(accountDto, EnterpriseEnums.GR_ZT.getType());
            dto.setAdminUserId(user.getUserId());
            RegUnitInfoDto regUnitInfoDto = new RegUnitInfoDto();
            BeanUtils.copyProperties(dto, regUnitInfoDto);
            TzBaseEnterpriseInfo baseEnterpriseInfo = regUnitInfoService.createBaseEnterpriseInfo(regUnitInfoDto, EnterpriseEnums.GR_ZT.getType());
            TzsBaseIndividuality tzsBaseIndividuality = new TzsBaseIndividuality();
            BeanUtils.copyProperties(dto, tzsBaseIndividuality);
            tzsBaseIndividuality.setEnterpriseId(baseEnterpriseInfo.getSequenceNbr());
            this.save(tzsBaseIndividuality);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            try {
                // 失败后回滚：删除已经创建的企业信息
                if (StringUtils.isNotEmpty(dto.getAmosCompanySeq())) {
                    FeignClientResult<CompanyModel> feignClientResult = Privilege.companyClient.seleteOne(Long.parseLong(dto.getAmosCompanySeq()));
                    if (feignClientResult != null && feignClientResult.getResult() != null) {
                        Privilege.companyClient.deleteCompany(dto.getAmosCompanySeq());
                    }
                }
                // 失败后回滚：删除已经创建的管理员账号
                if (StringUtils.isNotEmpty(dto.getAdminUserId())) {
                    FeignClientResult<AgencyUserModel> feignClientResult = Privilege.agencyUserClient.queryByUserId(dto.getAdminUserId());
                    if (feignClientResult != null && feignClientResult.getResult() != null) {
                        Privilege.agencyUserClient.multDeleteUser(dto.getAdminUserId());
                    }
                }
            } catch (Exception rollbackException) {
                log.error("回滚操作发生异常: {}", rollbackException.getMessage(), rollbackException);
            }
            throw new RuntimeException("个体单位注册失败: " + e.getMessage() + "  请联系管理员！");
        }
    }

    public RegUnitInfoDto adminInfo(String unitCode) {
        // 管理员信息
        TzsBaseIndividuality individuality = this.getOne(
                new LambdaQueryWrapper<TzsBaseIndividuality>().eq(TzsBaseIndividuality::getCredentialsNum, unitCode));
        RegUnitInfoDto regUnitInfoDto = new RegUnitInfoDto();
        if (individuality != null) {
            regUnitInfoDto.setAdminIdNumber(individuality.getCredentialsNum());
            regUnitInfoDto.setAdminName(individuality.getRealName());
        }
        regUnitInfoDto.setAdminIdCardPhoto(ObjectUtils.isEmpty(individuality.getIdentificationPhoto()) ? new ArrayList() : JSON.parseArray(individuality.getIdentificationPhoto()));
        return regUnitInfoDto;
    }
}