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


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.module.jxiop.api.dto.*;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IPersonBasicService;
import com.yeejoin.amos.boot.module.jxiop.biz.activemq.QuerueProduce;
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.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.LoginInfoModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员基本信息服务实现类
 *
 * @author system_generator
 * @date 2023-04-20
 */
@Service
public class PersonBasicServiceImpl extends BaseService<PersonBasicDto, PersonBasic, PersonBasicMapper> implements IPersonBasicService {

    @Autowired
    PersonBasicMapper personBasicMapper;


    //人员账号信息service
    @Autowired
    PersonAccountServiceImpl personAccountService;
    //人员归属信息service
    @Autowired
    PersonAscriptionServiceImpl personAscriptionService;
    //人员资质信息service
    @Autowired
    PersonCertificateServiceImpl personCertificateService;
    //人员教育信息
    @Autowired
    PersonSkillEducationServiceImpl personSkillEducationService;
    @Value("${amos.secret.key}")
    String secretKey;
    @Autowired
    QuerueProduce querueProduce;

    private String UPDATE="UPDATE";
    private String INSERT="INSERT";


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

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

    /**
     * 新增
     */
    @Transactional
    public void addPerson(PersonDto model, HttpServletRequest httpServletRequest) {


        //获取人员基本信息数据
        PersonUser personUser = model.getPersonUser();
        //获取人员资质信息
        PersonCertificate personCertificate = model.getPersonCertificate();
        //获取人员账号信息
        PersonAccount personAccount = model.getPersonAccount();
        personUser.setPhone(personAccount.getPhoneNum());

        //人员基础信息
        PersonBasic personBasic = new PersonBasic();
        BeanUtils.copyProperties(personUser, personBasic);
        this.baseMapper.insert(personBasic);
        //人员技能学历信息
        PersonSkillEducation personSkillEducation = new PersonSkillEducation();
        BeanUtils.copyProperties(personUser, personSkillEducation);
        personSkillEducation.setPersonId(personBasic.getSequenceNbr());
        personSkillEducationService.save(personSkillEducation);
        //人员资质信息
        personCertificate.setPersonId(personBasic.getSequenceNbr());

        personCertificateService.save(personCertificate);
        //人员账号信息
        personAccount.setPersonId(personBasic.getSequenceNbr());
        personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        personAccountService.save(personAccount);
        //新增平台账号
        //组装数据
        AgencyUserModel usd = new AgencyUserModel();
        //应用
        usd.setAppCodes(personAccount.getApplication());
        //手机号
        usd.setMobile(personUser.getPhone());
        //角色
        Map<Long, List<Long>> map = new HashMap<>();
        List<Long> cdids = personAccount.getRoles().stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); //测点数组
        if (personAccount.getDepartmentId() != null) {

            map.put(personAccount.getDepartmentId(), cdids);
        } else {
            map.put(personAccount.getProjectId(), cdids);
        }
        usd.setOrgRoleSeqs(map);
        //密码
        usd.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        //二次密码
        usd.setRePassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        //用户名
        usd.setRealName(personAccount.getName());
        //账号
        usd.setUserName(personAccount.getAccountName());
        usd.setLockStatus("UNLOCK");
        //新增平台用户
        AgencyUserModel agencyUserModel = this.setcreateUser(usd);
        //设置userID
        usd.setUserId(agencyUserModel.getUserId());
        //设置工号
        usd.setUserName(personAccount.getJobNumber());
        //创建支持工号登录
        this.createLoginInfo(usd);
        //查询部门
        DepartmentModel departmentModel = null;
        if (personAccount.getDepartmentId() != null) {
            departmentModel = this.getdepartmentModel(personAccount.getDepartmentId());
        }
        CompanyModel companyModel = new CompanyModel();
        //单位
        companyModel = this.getCompanyModel(personAccount.getProjectId());
        if (departmentModel != null) {
            //personBasic.setProjectOrgCode(departmentModel.getOrgCode());
            personAccount.setProjectDepartmentName(departmentModel.getDepartmentName());
        }
            personBasic.setProjectOrgCode(companyModel.getOrgCode());


        if (personUser.getNativePlace()!=null) {
            personBasic.setNativePlace(JSON.toJSONString(personUser.getNativePlace()));
        }
        personAccount.setPuserId(agencyUserModel.getUserId());
        personAccount.setProjectName(companyModel.getCompanyName());
        personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        this.personBasicMapper.updateById(personBasic);
        this.personAccountService.updateById(personAccount);


        Map<String, Object> data=new HashMap<>();
        data.put("SEQUENCE_NBR",agencyUserModel.getSequenceNbr());
        ProduceMsg produceMsg=  new ProduceMsg(data, INSERT,agencyUserModel.getUserId());
        querueProduce.produceMsg(JSON.toJSONString(produceMsg));

    }


    @Transactional
    public PersonDto updatePerson(PersonDto model, HttpServletRequest httpServletRequest, Long sequenceNbr) {


        //获取人员基本信息数据
        PersonUser personUser = model.getPersonUser();
        //获取人员资质信息
        PersonCertificate personCertificate = model.getPersonCertificate();
        //获取人员账号信息
        PersonAccount personAccount = model.getPersonAccount();
        personUser.setPhone(personAccount.getPhoneNum());

        //人员基础信息
        PersonBasic personBasic = new PersonBasic();
        personBasic.setSequenceNbr(sequenceNbr);
        personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        this.personBasicMapper.updateById(personBasic);
        //人员归属信息
        PersonSkillEducation personSkillEducation = new PersonSkillEducation();
        BeanUtils.copyProperties(personUser, personSkillEducation);
        personSkillEducation.setPersonId(personBasic.getSequenceNbr());
        PersonSkillEducation personSkillEducationd = personSkillEducationService.getOne(new QueryWrapper<PersonSkillEducation>().eq("person_id", personBasic.getSequenceNbr()));
        personSkillEducation.setSequenceNbr(personSkillEducationd.getSequenceNbr());
        personSkillEducationService.updateById(personSkillEducation);
        //人员资质信息
        personCertificateService.updateById(personCertificate);
        //人员账号信息
        personAccount.setPersonId(sequenceNbr);
        personAccountService.updateById(personAccount);
        //新增平台账号
        //组装数据
        AgencyUserModel usd = new AgencyUserModel();
        //应用
        usd.setAppCodes(personAccount.getApplication());
        //手机号
        usd.setMobile(personUser.getPhone());
        //角色
        Map<Long, List<Long>> map = new HashMap<>();
        List<Long> cdids = personAccount.getRoles().stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); //测点数组
        if (personAccount.getDepartmentId() != null) {

            map.put(personAccount.getDepartmentId(), cdids);
        } else {
            map.put(personAccount.getProjectId(), cdids);
        }
        usd.setOrgRoleSeqs(map);
        //密码
        usd.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        //二次密码
        usd.setRePassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        //用户名
        usd.setRealName(personAccount.getName());
        //账号
        usd.setUserName(personAccount.getAccountName());
        usd.setLockStatus("UNLOCK");
        usd.setUserId(personAccount.getPuserId());
        //新增平台用户
        AgencyUserModel agencyUserModel = this.updateuser(personAccount.getPuserId(), usd);
        //设置userID
        usd.setUserId(agencyUserModel.getUserId());
        //设置工号
        usd.setUserName(personAccount.getJobNumber());
        //创建支持工号登录
        this.updateLoginInfo(personAccount.getJobNumber(),usd);
        //查询部门
        DepartmentModel departmentModel = null;
        if (personAccount.getDepartmentId() != null) {
            departmentModel = this.getdepartmentModel(personAccount.getDepartmentId());
        }
        CompanyModel companyModel = new CompanyModel();
        //单位
        companyModel = this.getCompanyModel(personAccount.getProjectId());

        BeanUtils.copyProperties(personUser, personBasic);
        if (departmentModel != null) {
            //personBasic.setProjectOrgCode(departmentModel.getOrgCode());
            personAccount.setProjectDepartmentName(departmentModel.getDepartmentName());
        }
            personBasic.setProjectOrgCode(companyModel.getOrgCode());

        if (personUser.getNativePlace() != null) {
            personBasic.setNativePlace(JSON.toJSONString(personUser.getNativePlace()));
        }
        personAccount.setProjectName(companyModel.getCompanyName());
        personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
        personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
        this.personBasicMapper.updateById(personBasic);
        personAccountService.updateById(personAccount);

        Map<String, Object> data=new HashMap<>();
        data.put("SEQUENCE_NBR",agencyUserModel.getSequenceNbr());
        ProduceMsg produceMsg=  new ProduceMsg(data, UPDATE,agencyUserModel.getUserId());
        querueProduce.produceMsg(JSON.toJSONString(produceMsg));
        return model;
    }

    @Transactional
    public PersonDto getPerson(Long sequenceNbr) {
        PersonDto personDto = new PersonDto();
        PersonUser personUser = new PersonUser();
        QueryWrapper<PersonBasic> wrapper1 = new QueryWrapper();
        wrapper1.eq("sequence_nbr", sequenceNbr);
        wrapper1.eq("is_delete", 0);
        //人员基础信息
        PersonBasic personBasic = this.getOne(wrapper1);
        BeanUtils.copyProperties(personBasic, personUser);
        //人员技能学历信息
        QueryWrapper<PersonSkillEducation> wrapper2 = new QueryWrapper();
        wrapper2.eq("person_id", sequenceNbr);
        PersonSkillEducation personSkillEducation = personSkillEducationService.getOne(wrapper2);
        BeanUtils.copyProperties(personSkillEducation, personUser);


        QueryWrapper<PersonCertificate> wrapper3 = new QueryWrapper();
        wrapper3.eq("person_id", sequenceNbr);
        //人员资质信息
        PersonCertificate personCertificate = personCertificateService.getOne(wrapper3);


        QueryWrapper<PersonAccount> wrapper4 = new QueryWrapper();
        wrapper4.eq("person_id", sequenceNbr);
        //人员账号信息
        PersonAccount personAccount = personAccountService.getOne(wrapper4);
        personAccount.setPhoneNum(personBasic.getPhone());
        //对于密码进行解密
        personAccount.setPassword(DesUtil.decode(personAccount.getPassword(), secretKey));
        personAccount.setSecondaryPassword(DesUtil.decode(personAccount.getSecondaryPassword(), secretKey));
        if (personBasic.getNativePlace() != null) {
            personUser.setNativePlace(JSON.parseArray(personBasic.getNativePlace(), Integer.class));
        }
        personDto.setPersonUser(personUser);
        personDto.setPersonCertificate(personCertificate);
        personDto.setPersonAccount(personAccount);
        return personDto;
    }

    @Transactional
    public int deletePerson(String[] ids) {

        //查询所有平台用户
        QueryWrapper<PersonAccount> wrapper = new QueryWrapper();
        wrapper.in("person_id", ids);
        List<PersonAccount> list = personAccountService.list(wrapper);
        List<String> userid = new ArrayList<>();
        List<String> loginId = new ArrayList<>();
        for (PersonAccount personAccount : list) {
            userid.add(personAccount.getPuserId());
        }
        //删除平台
        int deleteResult = personBasicMapper.deleteList(ids);
        this.deleuser(String.join(",", userid));
        this.deleteLoginInfo(String.join(",", loginId));
        return deleteResult;
    }

    //新增平台用户
    private AgencyUserModel setcreateUser(AgencyUserModel userDto) {
        FeignClientResult<AgencyUserModel> amosUser = Privilege.agencyUserClient.create(userDto);

        AgencyUserModel user = new AgencyUserModel();

        if (!ObjectUtils.isEmpty(amosUser)) {
            if (amosUser.getStatus() == 200) {
                user = amosUser.getResult();
            } else {
                throw new RuntimeException(amosUser.getMessage());
            }
        }
        return user;
    }
    private LoginInfoModel createLoginInfo(AgencyUserModel userDto) {
        FeignClientResult<LoginInfoModel> amosLoginfo = null;
        try {
            amosLoginfo = Privilege.agencyUserClient.createLoginInfo(userDto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return amosLoginfo.getResult();
    }

    //修改平台用户
    private AgencyUserModel updateuser(String userId, AgencyUserModel userDto) {
        FeignClientResult<AgencyUserModel> amosUser = Privilege.agencyUserClient.update(userDto, userId);
        AgencyUserModel user = new AgencyUserModel();

        if (!ObjectUtils.isEmpty(amosUser)) {
            if (amosUser.getStatus() == 200) {
                user = amosUser.getResult();
            } else {
                throw new RuntimeException(amosUser.getMessage());
            }
        }
        return user;
    }
    private LoginInfoModel updateLoginInfo(String loginId,AgencyUserModel userDto) {
        FeignClientResult<LoginInfoModel> amosLoginfo = null;
        try {
            amosLoginfo = Privilege.agencyUserClient.updateLoginInfo(userDto,loginId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return amosLoginfo.getResult();
    }
    private DepartmentModel getdepartmentModel(Long departmentId) {
        FeignClientResult<DepartmentModel> de = Privilege.departmentClient.seleteOne(departmentId);

        DepartmentModel departmentModel = new DepartmentModel();

        if (!ObjectUtils.isEmpty(de)) {
            if (de.getStatus() == 200) {
                departmentModel = de.getResult();
            } else {
                throw new RuntimeException(de.getMessage());
            }
        }
        return departmentModel;
    }

    public CompanyModel getCompanyModel(Long projectId) {
        FeignClientResult<CompanyModel> cResult = Privilege.companyClient.seleteOne(projectId);
        CompanyModel companyModel = new CompanyModel();

        if (!ObjectUtils.isEmpty(cResult)) {
            if (cResult.getStatus() == 200) {
                companyModel = cResult.getResult();
            } else {
                throw new RuntimeException(cResult.getMessage());
            }
        }
        return companyModel;
    }

    private void deleuser(String userid) {
        FeignClientResult<List<String>> cResult = Privilege.agencyUserClient.multDeleteUser(userid);

        if (!ObjectUtils.isEmpty(cResult)) {
            if (cResult.getStatus() != 200) {
                throw new RuntimeException(cResult.getMessage());
            }
        }
    }

    private String deleteLoginInfo(String loginId) {
        FeignClientResult<String> amosLoginfo = null;
        try {
            amosLoginfo = Privilege.agencyUserClient.deleteLoginInfo(loginId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return amosLoginfo.getResult();
    }
    /**
     * 分页查询
     */
    public Page<UserMapperDto> queryPage(Page<UserMapperDto> page,
                                         String name,
                                         String accountName,
                                         String projectName, String orgCode) {

        List<UserMapperDto> list = personBasicMapper.queryPage((page.getCurrent() - 1) * page.getSize(), page.getSize(), name,
                accountName,
                projectName, orgCode);
        List<UserMapperDto> listcount = personBasicMapper.queryPagecount(name,
                accountName,
                projectName, orgCode);
        page.setTotal(listcount.size());
        page.setRecords(list);
        return page;
    }

}