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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.cylinder.api.dto.TzsUserInfoDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.CommonFile;
import com.yeejoin.amos.boot.module.cylinder.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.cylinder.api.entity.TzsUserQualifications;
import com.yeejoin.amos.boot.module.cylinder.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.cylinder.api.service.ITzsUserInfoService;
import com.yeejoin.amos.boot.module.cylinder.api.vo.TzsUserInfoVo;
import com.yeejoin.amos.boot.module.cylinder.api.vo.TzsUserQualificationsVo;
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 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.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.*;

@Service
public class TzsUserInfoServiceImpl extends BaseService<TzsUserInfoDto, TzsUserInfo, TzsUserInfoMapper> implements ITzsUserInfoService {

    @Autowired
    private TzsUserInfoMapper tzsUserInfoMapper;

    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;

    @Autowired
    private TzsUserQualificationsServiceImpl tzsUserQualificationsService;
    @Override
    public Page<TzsUserInfoDto> page(TzsUserInfoDto dto, Page<TzsUserInfoDto> page) {
        Page<TzsUserInfoDto> tzsUserInfoDtoPage = tzsUserInfoMapper.selectPageMessage(page, dto);
        tzsUserInfoDtoPage.getRecords().forEach(item ->{
            if (!ObjectUtils.isEmpty(item.getProfile())){
                List<CommonFile> commonFiles = JSON.parseArray(item.getProfile(), CommonFile.class);
                item.setProfile(commonFiles.get(0).getUrl());
            }
            if (!ObjectUtils.isEmpty(item.getBirthday())){
                int age = getAge(item.getBirthday());
                item.setAge(Math.max(age, 0));
            }
            if (!ObjectUtils.isEmpty(item.getPost())){
                JSONArray objects = JSON.parseArray(item.getPost());
                item.setPost(null);
                LambdaQueryWrapper<DataDictionary> lambda = new QueryWrapper<DataDictionary>().lambda();
                lambda.in(DataDictionary::getSequenceNbr, objects);
                List<DataDictionary> dataDictionaries = dataDictionaryMapper.selectList(lambda);
                dataDictionaries.forEach(post ->{
                    if (!ObjectUtils.isEmpty(item.getPost())){
                        item.setPost(item.getPost() + "," +post.getName());
                    }else {
                        item.setPost(post.getName());
                    }
                });
            }
        });
        return tzsUserInfoDtoPage;
    }


    public int getAge(Date birth) {
        Calendar cal = Calendar.getInstance();
        int thisYear = cal.get(Calendar.YEAR);
        int thisMonth = cal.get(Calendar.MONTH);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birth);
        int birthYear = cal.get(Calendar.YEAR);
        int birthMonth = cal.get(Calendar.MONTH);
        int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        int age = thisYear - birthYear;

        // 未足月
        if (thisMonth <= birthMonth) {
            // 当月
            if (thisMonth == birthMonth) {
                // 未足日
                if (dayOfMonth < birthdayOfMonth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }

    @Override
    public void addQualificationsMessage(String userId, List<TzsUserQualifications> list) {
        list.forEach(item -> {
            item.setUserInfoId(userId);
        });
        tzsUserQualificationsService.saveOrUpdateBatch(list);
    }

    @Override
    public void updateQualificationsMessage(String userId, List<TzsUserQualifications> list) {
        LambdaQueryWrapper<TzsUserQualifications> lambda = new QueryWrapper<TzsUserQualifications>().lambda();
        lambda.eq(TzsUserQualifications::getUserInfoId, userId);
        tzsUserQualificationsService.getBaseMapper().delete(lambda);
        addQualificationsMessage(userId, list);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        LambdaQueryWrapper<TzsUserInfo> lambda = new QueryWrapper<TzsUserInfo>().lambda();
        lambda.in(TzsUserInfo::getSequenceNbr, ids);
        TzsUserInfo tzsUserInfo = new TzsUserInfo();
        tzsUserInfo.setIsDelete(true);
        tzsUserInfoMapper.update(tzsUserInfo, lambda);
        LambdaQueryWrapper<TzsUserQualifications> qualificationsLambda = new QueryWrapper<TzsUserQualifications>().lambda();
        qualificationsLambda.in(TzsUserQualifications::getUserInfoId, ids);
        TzsUserQualifications tzsUserQualifications = new TzsUserQualifications();
        tzsUserQualifications.setIsDelete(true);
        tzsUserQualificationsService.update(tzsUserQualifications, qualificationsLambda);
    }

    @Override
    public Map<String, Object> getDetail(Long id) {
        Map<String, Object> maps = new HashMap<>();
        TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectById(id);
        TzsUserInfoVo tzsUserInfoVo = new TzsUserInfoVo();
        BeanUtils.copyProperties(tzsUserInfo, tzsUserInfoVo, "identification","profile","post");
        if (!ObjectUtils.isEmpty(tzsUserInfo.getPost())){
            tzsUserInfoVo.setPost(JSON.parseArray(tzsUserInfo.getPost()));
        }
        tzsUserInfoVo.setIdentification(ObjectUtils.isEmpty(tzsUserInfo.getIdentification()) ? new ArrayList() : JSON.parseArray(tzsUserInfo.getIdentification()));
        tzsUserInfoVo.setProfile(ObjectUtils.isEmpty(tzsUserInfo.getProfile()) ? new ArrayList() : JSON.parseArray(tzsUserInfo.getProfile()));
        maps.put("userInfo", tzsUserInfoVo);
        LambdaQueryWrapper<TzsUserQualifications> lambda = new QueryWrapper<TzsUserQualifications>().lambda();
        lambda.eq(TzsUserQualifications::getUserInfoId, id);
        ArrayList<TzsUserQualificationsVo> tzsUserQualificationsVos = new ArrayList<>();
        List<TzsUserQualifications> list = tzsUserQualificationsService.getBaseMapper().selectList(lambda);
        list.forEach(item ->{
            TzsUserQualificationsVo vo = new TzsUserQualificationsVo();
            BeanUtils.copyProperties(item, vo,"file");
            vo.setFile(ObjectUtils.isEmpty(item.getFile()) ? new ArrayList() : JSON.parseArray(item.getFile()));
            tzsUserQualificationsVos.add(vo);
        });
        HashMap<String, Object> subForm = new HashMap<>();
        subForm.put("subForm", tzsUserQualificationsVos);
        maps.put("qualificationsInfo",subForm);
        return maps;
    }

    @Override
    public boolean BindAccount(Map<String, Object> map) {
        String loginName = map.get("userName").toString();
        String pwd = map.get("password").toString();
        String sequenceNbr = map.get("sequenceNbr").toString();
        String roles = map.get("role").toString();
        String status = map.get("status").toString();

        FeignClientResult<AgencyUserModel> userResult = null;
        try {
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(loginName);
            agencyUserModel.setRealName(loginName);
            agencyUserModel.setLockStatus(status);
            agencyUserModel.setPassword(pwd);
            agencyUserModel.setRePassword(pwd);
            agencyUserModel.setAgencyCode("tzs");
            agencyUserModel.setMobile(null);

            ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            if (ObjectUtils.isEmpty(reginParams)) {
                return false;
            }
            Long companySeq = reginParams.getCompany().getSequenceNbr();
            List<String> appCodesSet = reginParams.getUserModel().getAppCodes();
            List<RoleModel> allRoleList = new ArrayList<>();
            List<Long> roleIds = new ArrayList<>();
            DataDictionary unitType = iDataDictionaryService
                    .getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getCode, roles));
            String role = unitType.getExtend() != null ? unitType.getExtend() : "";
            for (String s : role.split(",")) {
                RoleModel roleModel = Privilege.roleClient.seleteOne(Long.valueOf(s)).getResult();
                allRoleList.add(roleModel);
            }
            allRoleList.forEach(r -> {
                if (!roleIds.contains(r.getSequenceNbr())) {
                    roleIds.add(r.getSequenceNbr());
                }
            });

            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
            roleSeqMap.put(companySeq, roleIds);
            orgRoles.put(companySeq, allRoleList);
            agencyUserModel.setAppCodes(new ArrayList<>(appCodesSet));
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            userResult = Privilege.agencyUserClient.create(agencyUserModel);
            if (userResult.getStatus() == 200) {
                TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectById(sequenceNbr);
                tzsUserInfo.setAmosUserId(userResult.getResult().getUserId());
                tzsUserInfo.setAmosUserName(userResult.getResult().getUserName());
                tzsUserInfoMapper.updateById(tzsUserInfo);
            }
            return true;
        } 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());
        }

    }
}
