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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.PersonnelBusiness;
import com.yeejoin.amos.boot.module.hygf.api.entity.RegionalCompanies;
import com.yeejoin.amos.boot.module.hygf.api.entity.UnitInfo;
import com.yeejoin.amos.boot.module.hygf.api.entity.UserMessage;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UnitInfoMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IPersonnelBusinessService;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
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 com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.boot.module.hygf.api.util.DesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * 人员业务信息表服务实现类
 *
 * @author system_generator
 * @date 2023-09-01
 */
@Service
public class PersonnelBusinessServiceImpl extends BaseService<PersonnelBusinessDto,PersonnelBusiness,PersonnelBusinessMapper> implements IPersonnelBusinessService {
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    UnitInfoMapper unitInfoMapper;

    @Autowired
    UserMessageMapper userMessageMapper;
    @Value("${dealer.appcode}")
    private String appCodes;
    @Value("${amos.secret.key}")
    String secretKey;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Value("${hygf.user.group.id}")
    private long userGroupId;
    /**
     * 分页查询
     */
    public Page<PersonnelBusinessDto> queryForPersonnelBusinessPage(Page<PersonnelBusinessDto> page)   {
        return this.queryForPage(page, null, false);
    }

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

    @Override
    public IPage<CompanyDtoUserDto> getCompanyDtoUserDto(CompanyDtoUserDto dto) {

        Map<String,String> map= personnelBusinessMapper.getorgcode(dto.getAmosUnitId());
        dto.setAmosUnitOrgCode(map.get("orgCode"));
        IPage<CompanyDtoUserDto> pag = personnelBusinessMapper.getCompanyDtoUserDtopage(dto);

        return pag;
    }

    @Transactional
    public void  savePersonnelBusiness(UserDataDto model){
        UserDataZHDto userDataZHDto= model.getUserDataZHDto();
        UserDataJBDto userDataJBDto= model.getUserDataJBDto();
        FeignClientResult<AgencyUserModel> userResult =null;
       //新增平台用户
        try {
            // 1 创建平台用户
            List<RoleModel> userRoleList = new ArrayList<>();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(userDataZHDto.getUserName());
            agencyUserModel.setRealName(userDataJBDto.getRealName());
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            agencyUserModel.setRePassword(DesUtil.encode(userDataZHDto.getRePassword(), secretKey));
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(userDataJBDto.getEmergencyTelephone());
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userDataZHDto.getRole());
            orgRoles.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userRoleList);
           // agencyUserModel.setAppCodes(split);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            // 将创建用户加入用户组
             userResult = Privilege.agencyUserClient.create(agencyUserModel);
            if (userResult == null || userResult.getStatus()!=200) {
                throw new BadRequest("新增人员失败！"+userResult.getDevMessage());
            }
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            for (Long aLong : userDataZHDto.getRole()) {
                Privilege.groupUserClient.create(aLong, userId);
            }


            //新增人员基础信息表
            PublicAgencyUser publicAgencyUser=new PublicAgencyUser();
            publicAgencyUser.setRealName(userDataJBDto.getRealName());
            publicAgencyUser.setGender(userDataJBDto.getGender());
            publicAgencyUser.setJobNumber(userDataJBDto.getJobNumber());
            publicAgencyUser.setIdType(userDataJBDto.getIdType());
            publicAgencyUser.setIdNumber(userDataJBDto.getIdNumber());
            publicAgencyUser.setAmosId(userDataJBDto.getAmosUnitId());

            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.seleteOne(userDataJBDto.getAmosUnitId());
            if (companyResult == null || companyResult.getStatus()!=200) {
                throw new BadRequest("新增人员失败！"+companyResult.getDevMessage());
            }
            publicAgencyUser.setAmosOrgCode(companyResult.getResult().getOrgCode());
            publicAgencyUser.setAmosUserId(userResult.getResult().getUserId());
            publicAgencyUser.setAmosUserName(userDataZHDto.getUserName());
            publicAgencyUser.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            publicAgencyUser.setRole(JSON.toJSONString( userDataZHDto.getRole()));
            publicAgencyUser.setLockStatus("UNLOCK");
            publicAgencyUser.setLockTime(new Date());
            publicAgencyUser.setHeight(userDataJBDto.getHeight());
            publicAgencyUser.setWeight(userDataJBDto.getWeight());
            publicAgencyUser.setEmergencyTelephone(userDataJBDto.getEmergencyTelephone());
            publicAgencyUser.setDomicileAddress(userDataJBDto.getDomicileAddress());
            publicAgencyUser.setPosition(userDataJBDto.getPosition()!=null?JSON.toJSONString(userDataJBDto.getPosition()):null);
            publicAgencyUser.setNowAddress(userDataJBDto.getNowAddress());
            publicAgencyUser.setNativePlace(userDataJBDto.getNativePlace());
            publicAgencyUser.setPoliticalOutlook(userDataJBDto.getPoliticalOutlook());
            publicAgencyUserMapper.insert(publicAgencyUser);

            PersonnelBusiness re=new PersonnelBusiness();
            FeignClientResult<CompanyModel> companyResult1 = Privilege.companyClient.seleteOne(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            if (companyResult1 == null || companyResult1.getStatus()!=200) {
                throw new BadRequest("新增人员失败！"+companyResult1.getDevMessage());
            }
            re.setRegionalCompaniesSeq(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            re.setRegionalCompaniesName(companyResult1.getResult().getCompanyName());
            re.setRegionalCompaniesCode(companyResult1.getResult().getOrgCode());
            re.setCertificate(model.getUserDataZZDto()!=null?JSON.toJSONString(model.getUserDataZZDto().getCertificate()):null);
            re.setAmosUnitId(companyResult.getResult().getSequenceNbr());
            re.setAmosUnitName(companyResult.getResult().getCompanyName());
            re.setAmosUnitOrgCode(companyResult.getResult().getOrgCode());
            re.setFoundationId(publicAgencyUser.getSequenceNbr());
            re.setAmosDealerId(model.getAmosDealerId());
            personnelBusinessMapper.insert(re);

        }catch (Exception e){
            if (userResult != null && userResult.getResult() != null
                    && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
            }
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }

    }


    @Transactional
    public void  updatePersonnelBusiness( UserDataDto model ,long id){

        PublicAgencyUser publicAgencyUser= publicAgencyUserMapper.selectById(id);


        UserDataZHDto userDataZHDto= model.getUserDataZHDto();
        UserDataJBDto userDataJBDto= model.getUserDataJBDto();
        FeignClientResult<AgencyUserModel> userResult =null;

        try {
            // 1 修改平台用户
            List<RoleModel> userRoleList = new ArrayList<>();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(userDataZHDto.getUserName());
            agencyUserModel.setRealName(userDataJBDto.getRealName());
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            agencyUserModel.setRePassword(DesUtil.encode(userDataZHDto.getRePassword(), secretKey));
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(userDataJBDto.getEmergencyTelephone());
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userDataZHDto.getRole());
            orgRoles.put(Long.valueOf(userDataJBDto.getAmosUnitId()), userRoleList);
            //agencyUserModel.setAppCodes(split);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            // 将创建用户加入用户组
            userResult = Privilege.agencyUserClient.update(agencyUserModel,publicAgencyUser.getAmosUserId());
            if (userResult == null || userResult.getStatus()!=200) {
                throw new BadRequest("修改人员失败！"+userResult.getDevMessage());
            }
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            for (Long aLong : userDataZHDto.getRole()) {
                Privilege.groupUserClient.create(aLong, userId);
            }


            //修改人员基础信息表
            publicAgencyUser.setRealName(userDataJBDto.getRealName());
            publicAgencyUser.setGender(userDataJBDto.getGender());
            publicAgencyUser.setJobNumber(userDataJBDto.getJobNumber());
            publicAgencyUser.setIdType(userDataJBDto.getIdType());
            publicAgencyUser.setIdNumber(userDataJBDto.getIdNumber());
            publicAgencyUser.setAmosId(userDataJBDto.getAmosUnitId());

            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.seleteOne(userDataJBDto.getAmosUnitId());
            if (companyResult == null || companyResult.getStatus()!=200) {
                throw new BadRequest("修改人员失败！"+companyResult.getDevMessage());
            }
            publicAgencyUser.setAmosOrgCode(companyResult.getResult().getOrgCode());
            publicAgencyUser.setAmosUserName(userDataZHDto.getUserName());
            publicAgencyUser.setPassword(DesUtil.encode(userDataZHDto.getPassword(), secretKey));
            publicAgencyUser.setRole(JSON.toJSONString( userDataZHDto.getRole()));
            publicAgencyUser.setLockStatus("UNLOCK");
            publicAgencyUser.setLockTime(new Date());
            publicAgencyUser.setHeight(userDataJBDto.getHeight());
            publicAgencyUser.setWeight(userDataJBDto.getWeight());
            publicAgencyUser.setEmergencyTelephone(userDataJBDto.getEmergencyTelephone());
            publicAgencyUser.setDomicileAddress(userDataJBDto.getDomicileAddress());
            publicAgencyUser.setPosition(userDataJBDto.getPosition()!=null?JSON.toJSONString(userDataJBDto.getPosition()):null);
            publicAgencyUser.setNowAddress(userDataJBDto.getNowAddress());
            publicAgencyUser.setNativePlace(userDataJBDto.getNativePlace());
            publicAgencyUser.setPoliticalOutlook(userDataJBDto.getPoliticalOutlook());
            publicAgencyUserMapper.updateById(publicAgencyUser);


            LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
            qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUser.getSequenceNbr());
            PersonnelBusiness re=personnelBusinessMapper.selectOne(qug);

            FeignClientResult<CompanyModel> companyResult1 = Privilege.companyClient.seleteOne(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            if (companyResult1 == null || companyResult1.getStatus()!=200) {
                throw new BadRequest("修改人员失败！"+companyResult1.getDevMessage());
            }
            re.setRegionalCompaniesSeq(Long.valueOf(userDataJBDto.getRegionalCompaniesSeq()));
            re.setRegionalCompaniesName(companyResult1.getResult().getCompanyName());
            re.setRegionalCompaniesCode(companyResult1.getResult().getOrgCode());
            re.setCertificate(model.getUserDataZZDto()!=null?JSON.toJSONString(model.getUserDataZZDto().getCertificate()):null);
            re.setAmosUnitId(companyResult.getResult().getSequenceNbr());
            re.setAmosUnitName(companyResult.getResult().getCompanyName());
            re.setAmosUnitOrgCode(companyResult.getResult().getOrgCode());
            personnelBusinessMapper.updateById(re);

        }catch (Exception e){

            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }

    }








    @Transactional
    public void replace(String id){
        try {

        //获取当前用户
        LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getSequenceNbr,id);
        PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);
        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);
        personnelBusines.setUserType("2");
        personnelBusinessMapper.updateById(personnelBusines);
       //获取经销商管理员
        LambdaQueryWrapper<UnitInfo> qudg=new LambdaQueryWrapper<>();
        qudg.eq(UnitInfo::getAmosCompanySeq,personnelBusines.getAmosDealerId());
        UnitInfo unitInfo= unitInfoMapper.selectOne(qudg);

        LambdaQueryWrapper<PublicAgencyUser> qudx=new LambdaQueryWrapper<>();
        qudx.eq(PublicAgencyUser::getAmosUserId,unitInfo.getAdminUserId());
        PublicAgencyUser publicAgencyUsex=  publicAgencyUserMapper.selectOne(qudx);
        LambdaQueryWrapper<PersonnelBusiness> qugf=new LambdaQueryWrapper<>();
        qugf.eq(PersonnelBusiness::getFoundationId,publicAgencyUsex.getSequenceNbr());
        PersonnelBusiness personnelBusinesx=personnelBusinessMapper.selectOne(qugf);
        personnelBusinesx.setUserType("1");

        personnelBusinessMapper.updateById(personnelBusinesx);
        unitInfo.setAdminLoginName(publicAgencyUse.getAmosUserName());
        unitInfo.setAdminPhone(publicAgencyUse.getEmergencyTelephone());
        unitInfo.setAdminUserId(publicAgencyUse.getAmosUserId());
        unitInfo.setAdminUserName(publicAgencyUse.getRealName());


        unitInfoMapper.updateById(unitInfo);

        List<String> userId = new ArrayList<>();
        userId.add(publicAgencyUse.getAmosUserId());


        //修改新管理员
        Privilege.groupUserClient.create(userGroupId, userId);

        //删除旧管理员
        Privilege.groupUserClient.deleteGroupUser(userGroupId,publicAgencyUsex.getAmosUserId());



        UserMessage userMessage=  new UserMessage( TaskTypeStationEnum.设置管理员.getCode(), personnelBusines.getSequenceNbr() ,  publicAgencyUse.getAmosUserId(),  new Date(),   "您已成为单位管理员。",  personnelBusines.getAmosUnitOrgCode());

        userMessageMapper.insert(userMessage);
        emqKeeper.getMqttClient().publish("MY_MESSAGE" , JSON.toJSONString(userMessage).getBytes(), 2 ,false);

        }catch (Exception e){
            e.printStackTrace();
            throw new BadRequest("设置失败！");
        }
    }


    @Override
   public UserDataDto getPersonnelBusinessById(String id){

        LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getSequenceNbr,id);
        PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);

        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);

        UserDataZHDto userDataZHDto=new UserDataZHDto();
        UserDataJBDto userDataJBDto=new UserDataJBDto();
        UserDataZZDto userDataZZDto=new UserDataZZDto();

        userDataZZDto.setCertificate(personnelBusines.getCertificate()!=null?JSONArray.parseArray(personnelBusines.getCertificate(), JSONObject.class):null);
        userDataZHDto.setRole(JSONArray.parseArray(publicAgencyUse.getRole(),long.class));
        userDataZHDto.setUserName(publicAgencyUse.getAmosUserName());

        BeanUtils.copyProperties(publicAgencyUse,userDataJBDto);
        userDataJBDto.setPosition(JSONArray.parseArray(publicAgencyUse.getPosition(),String.class));
        userDataJBDto.setRegionalCompaniesSeq(personnelBusines.getRegionalCompaniesSeq()!=null?personnelBusines.getRegionalCompaniesSeq().toString():null);
        userDataJBDto.setAmosUnitId(personnelBusines.getAmosUnitId());
        return new UserDataDto( userDataZHDto, userDataJBDto ,  userDataZZDto);
    }

}