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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jcs.api.dto.OrganizationExportDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.OrganizationUserExportDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Organization;
import com.yeejoin.amos.boot.module.jcs.api.entity.OrganizationUser;
import com.yeejoin.amos.boot.module.jcs.api.mapper.OrganizationMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.OrganizationUserMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.OrganizationService;
import org.apache.commons.lang3.ObjectUtils;
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.springframework.util.CollectionUtils;
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;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrganizationImpl extends BaseService<Organization,Organization, OrganizationMapper> implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OrganizationUserMapper organizationUserMapper;

    @Override
    public Page<Map<String, Object>> getOrganizationInfo(Page<Map<String, Object>> page, String bizOrgCode) {
        return organizationMapper.getOrganizationInfo(page, bizOrgCode);
    }

    @Override
    public Page<Map<String, Object>> getOrganizationList(Page<Map<String, Object>> page, String bizOrgCode) {
//        Page<Map<String, Object>> groupPage = new Page<>();
//        Page<Map<String, Object>> group = organizationMapper.getOrganizationGroup(groupPage, bizOrgCode);
//        Page<Map<String, Object>> mapPage = organizationMapper.getOrganizationList(page, bizOrgCode);
//        List<Map<String, Object>> records = group.getRecords();
//        ArrayList<Map<String, Object>> result = new ArrayList<>();
//        for (Map<String, Object> record : records) {
//
//            List<Map<String, Object>> collect = mapPage.getRecords().stream().filter(item -> String.valueOf(record.get("id")).equals(String.valueOf(item.get("groupId")))).collect(Collectors.toList());
//            record.put("persons", collect);
//            result.add(record);
//
//        }
//        mapPage.setRecords(result);
//        return mapPage;
        return organizationMapper.getOrganizationList(page, bizOrgCode);
    }

    @Override
    public List<OrganizationExportDto> selectOrganization(String bizOrgCode) {
        return organizationMapper.selectOrganization(bizOrgCode);
    }

    @Override
    public List<OrganizationUserExportDto> selectOrganizationUserList(String bizOrgCode) {
        return organizationMapper.selectOrganizationUserList(bizOrgCode);
    }

    @Override
    @Transactional
    public void saveOrganization(List<OrganizationExportDto> data, List<OrganizationUserExportDto> userData, String bizOrgCode) {
        int sort = organizationMapper.selectMaxSort();
        for (OrganizationExportDto dto : data) {
            Organization organization = new Organization();
            BeanUtils.copyProperties(dto, organization);
            sort = sort + 1;
            organization.setSort(sort);
            organization.setBizOrgCode(bizOrgCode);
            organizationMapper.insert(organization);
            List<OrganizationUserExportDto> collect = userData.stream().filter(item -> item.getEmergencyTeamName().equals(dto.getEmergencyTeamName())).collect(Collectors.toList());
            for (OrganizationUserExportDto userExportDto : collect) {
                OrganizationUser organizationUser = new OrganizationUser();
                BeanUtils.copyProperties(userExportDto, organizationUser);
                organizationUser.setEmergencyTeamId(String.valueOf(organization.getSequenceNbr()));
                organizationUserMapper.insert(organizationUser);
            }
        }
    }


    @Override
    public Organization saveOrganization(Organization organization) {
        organization.setSort(organizationMapper.selectMaxSort() + 1);
        return this.createWithModel(organization);
    }

    @Override
    public Organization updateModelById(Organization organization) {
        return this.updateWithModel(organization);
    }

    @Override
    public boolean moveTeam(String method, Long id) {
        Organization organization = this.baseMapper.selectById(id);
        if ("up".equals(method)) {
            // 获取需要移动数据
            // 上移，查询上一条数据
            LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
            int sort = organization.getSort();
            wrapper.lt(Organization::getSort, sort);
            wrapper.orderByDesc(Organization::getSort);
            wrapper.last(" limit 1");
            Organization upOrganization = this.baseMapper.selectOne(wrapper);
            if (ObjectUtils.isEmpty(upOrganization)) {
                throw new BadRequest("最顶层数据不可上移");
            }
            organization.setSort(upOrganization.getSort());
            this.updateById(organization);
            upOrganization.setSort(sort);
            this.updateById(upOrganization);
            return true;
        } else {
            // 下移，查询下一条数据
            LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
            int sort = organization.getSort();
            wrapper.gt(Organization::getSort, sort);
            wrapper.orderByAsc(Organization::getSort);
            wrapper.last(" limit 1");
            Organization downOrganization = this.baseMapper.selectOne(wrapper);
            if (ObjectUtils.isEmpty(downOrganization)) {
                throw new BadRequest("最底层数据不可下移");
            }
            organization.setSort(downOrganization.getSort());
            this.updateById(organization);
            downOrganization.setSort(sort);
            this.updateById(downOrganization);
            return true;
        }
    }

    @Override
    public List<Organization> getList() {
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Organization::getSort);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public Organization getDetailsById(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public int deleteById(Long id) {
        LambdaQueryWrapper<OrganizationUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrganizationUser::getEmergencyTeamId, id);
        List<OrganizationUser> organizationUsers = organizationUserMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(organizationUsers)) {
            throw new BadRequest("该应急小组下有成员不可删除!");
        }
        return this.baseMapper.deleteById(id);
    }
}
