package com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.tzs.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.PersonEducationDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.PersonQualityDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.UnitPersonInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.service.IUnitPersonService;
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.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业人员服务实现类
 */
@Service
public class UnitPersonServiceImpl  implements IUnitPersonService {


    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Autowired
    PersonQualityServiceImpl flcPersonQualityServiceImpl;


    @Autowired
    PersonEducationServiceImpl personEducationServiceImpl;


    @Autowired
    ISourceFileService iSourceFileService;


    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;

    @Transactional
    @Override
    public UnitPersonInfoDto saveUser(UnitPersonInfoDto unitPersonInfoDto) {
        unitPersonInfoDto.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        OrgPersonDto orgPersonVo = new OrgPersonDto();
        BeanUtils.copyProperties(unitPersonInfoDto,orgPersonVo);
        try {
            OrgUsrDto result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
            PersonQualityDto personQualityDto = unitPersonInfoDto.getPersonQualityDto();
            PersonEducationDto personEducationDto = unitPersonInfoDto.getPersonEducationDto();


            // 处理图片信息 -- 证照和图片
            Map<String, List<AttachmentDto>> userAttach = new HashMap<>();
            userAttach.put(TzsCommonParam.LICENCE_PIC,unitPersonInfoDto.getLicencePic());
            userAttach.put(TzsCommonParam.HEAD_SHOT,unitPersonInfoDto.getHeadshot());
            iSourceFileService.saveAttachments(result.getSequenceNbr(),userAttach);

            if(personQualityDto != null) {

                String[] licenceTypeCode = personQualityDto.getLicenceTypeCode().split(",");
                List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).in(DataDictionary::getCode,licenceTypeCode));
                String licenceType = "";
                for(DataDictionary temp : list) {
                    licenceType += "," + temp.getName();
                }
                if(licenceType.length() > 0) {
                    licenceType.substring(1);
                    personQualityDto.setLicenceType(licenceType);
                }

                // 创建人员资质信息
                personQualityDto.setPsersonId(result.getSequenceNbr());
                personQualityDto = flcPersonQualityServiceImpl.createWithModel(personQualityDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.LICENCE_INFO,personQualityDto.getLicenceInfo());
                iSourceFileService.saveAttachments(personQualityDto.getSequenceNbr(),userAttach);
            }

            if(personEducationDto != null) {
                // 创建人员教育信息
                personEducationDto.setPsersonId(result.getSequenceNbr());
                personEducationDto = personEducationServiceImpl.createWithModel(personEducationDto);
                userAttach = new HashMap<>();
                userAttach.put(TzsCommonParam.ATTACHMENT,personEducationDto.getAttachment());
                iSourceFileService.saveAttachments(personEducationDto.getSequenceNbr(),userAttach);

            }




            // 创建账号信息
            if(StringUtils.isNotEmpty(unitPersonInfoDto.getOrg_expand_attr1()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrg_expand_attr2())
            && StringUtils.isNotEmpty(unitPersonInfoDto.getOrg_expand_attr3()) && StringUtils.isNotEmpty(unitPersonInfoDto.getOrg_expand_attr4())
            && StringUtils.isNotEmpty(unitPersonInfoDto.getOrg_expand_attr5() )) {

                String roleName = unitPersonInfoDto.getOrg_expand_attr5();
                String orgId = unitPersonInfoDto.getOrg_expand_attr3();// 拿到的是 org_user的id 需要转换成amosid
                OrgUsr temp =  iOrgUsrService.getById(Long.parseLong(orgId));
                Long companyId = Long.parseLong(temp.getAmosOrgId());


                String appcode = unitPersonInfoDto.getOrg_expand_attr4();

                // 创建人员账户信息
                FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
                String pwd = DesUtil.encode(unitPersonInfoDto.getOrg_expand_attr2(), "qaz");

                AgencyUserModel agencyUserModel = new AgencyUserModel();
                agencyUserModel.setUserName(unitPersonInfoDto.getOrg_expand_attr1());
                agencyUserModel.setRealName(unitPersonInfoDto.getBizOrgName());
                agencyUserModel.setLockStatus("UNLOCK");
                agencyUserModel.setPassword(pwd);
                agencyUserModel.setRePassword(pwd);
                agencyUserModel.setAgencyCode("tzs");
                // agencyUserModel.setMobile(adminTel); 不存储电话信息
                // 所属组织
                Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
                List<Long> roleIds = new ArrayList<>();
                List<RoleModel> allRoleList = roleListResult.getResult();
                List<RoleModel> userRoleList = new ArrayList<>();
                allRoleList.stream().forEach(t -> {
                    if(t.getRoleName().equals(roleName)) {
                        userRoleList.add(t);
                    }
                });
                userRoleList.stream().forEach(r -> {
                    roleIds.add(r.getSequenceNbr());
                });

                roleSeqsMap.put(companyId,roleIds);
                List<String> appCodes = new ArrayList<>();
                appCodes.add(appcode);
                agencyUserModel.setAppCodes(appCodes);
                Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                orgRoles.put(companyId,userRoleList);
                agencyUserModel.setOrgRoles(orgRoles);
                agencyUserModel.setOrgRoleSeqs(roleSeqsMap);

                FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(agencyUserModel);
                agencyUserModel = userResult.getResult();
                orgPersonVo.setSequenceNbr(result.getSequenceNbr());
                orgPersonVo.setAmosOrgId(agencyUserModel.getUserId() + "");
                result =  iOrgUsrService.saveOrgPersonFlc(orgPersonVo);
                BeanUtils.copyProperties(result,unitPersonInfoDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitPersonInfoDto;
    }
}