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

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.entity.BaseEntity;
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) {

        //由于可以单独导入组，或者单独导入人，只做都为空效验
        if(data==null&&userData==null){
            throw new BadRequest("请填入数据导入！");
        }
        //对分组数据入库
        if(data.size()>0){
            int sort = organizationMapper.selectMaxSort();
            checkOrganizationData(data);
            for (OrganizationExportDto dto : data) {
                LambdaQueryWrapper<Organization> lambda = new QueryWrapper<Organization>().lambda();
                lambda.eq(Organization::getIsDelete, false);
                lambda.eq(Organization::getEmergencyTeamName, dto.getEmergencyTeamName());
                List<Organization> organizations = organizationMapper.selectList(lambda);
                Organization organization = new Organization();
                if (CollectionUtils.isEmpty(organizations)){
                    BeanUtils.copyProperties(dto, organization);
                    sort = sort + 1;
                    organization.setSort(sort);
                    organization.setBizOrgCode(bizOrgCode);
                    organizationMapper.insert(organization);
                }
//                else{
//                    throw new BadRequest("用户组"+dto.getEmergencyTeamName()+"已存不能重复导入！");
//                }
            }
        }
        //对人员数据入库
        if(userData.size()>0){
            checkOrganizationUserData(userData);
            int sort = organizationMapper.selectOrganizationUserMaxSort();
            for (OrganizationUserExportDto userExportDto : userData) {
                OrganizationUser organizationUser = new OrganizationUser();
                BeanUtils.copyProperties(userExportDto, organizationUser);

                LambdaQueryWrapper<Organization> lambda = new QueryWrapper<Organization>().lambda();
                lambda.eq(Organization::getIsDelete, false);
                lambda.eq(Organization::getEmergencyTeamName, userExportDto.getEmergencyTeamName());
                List<Organization> organizations = organizationMapper.selectList(lambda);
                if (CollectionUtils.isEmpty(organizations)){
                    throw new BadRequest("用户组"+userExportDto.getEmergencyTeamName()+"不存在，请先导入用户组！");
                }else{
                    organizationUser.setEmergencyTeamId(String.valueOf(organizations.get(0).getSequenceNbr()));
                    sort = sort + 1;
                    organizationUser.setSort(sort);
                    organizationUserMapper.insert(organizationUser);
                }
            }
        }

//        int sort = organizationMapper.selectMaxSort();
//        checkOrganizationData(data);
//        checkOrganizationUserData(userData);
//        for (OrganizationExportDto dto : data) {
//            LambdaQueryWrapper<Organization> lambda = new QueryWrapper<Organization>().lambda();
//            lambda.eq(Organization::getIsDelete, false);
//            lambda.eq(Organization::getEmergencyTeamName, dto.getEmergencyTeamName());
//            List<Organization> organizations = organizationMapper.selectList(lambda);
//            Organization organization = new Organization();
//            if (CollectionUtils.isEmpty(organizations)){
//                BeanUtils.copyProperties(dto, organization);
//                sort = sort + 1;
//                organization.setSort(sort);
//                organization.setBizOrgCode(bizOrgCode);
//                organizationMapper.insert(organization);
//            }else {
//                Organization organization1 = organizations.get(0);
//                BeanUtils.copyProperties(organization1, 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);
//            }
//        }
    }

    private void checkOrganizationData(List<OrganizationExportDto> data) {
        for (int i = 0; i < data.size(); i++) {
            OrganizationExportDto dto = data.get(i);
            if (ObjectUtils.isEmpty(dto.getEmergencyTeamName())) {
                throw new BadRequest("应急救援小组信息表第" +(i + 1)  + "行, 应急救援小组名称为必填信息！");
            }
            if (ObjectUtils.isEmpty(dto.getGroupLeader())) {
                throw new BadRequest("应急救援小组信息表第" + (i + 1) + "行, 组长为必填信息！");
            }
        }
    }

    private void checkOrganizationUserData(List<OrganizationUserExportDto> data) {
        for (int i = 0; i < data.size(); i++) {
            OrganizationUserExportDto dto = data.get(i);
            if (ObjectUtils.isEmpty(dto.getEmergencyTeamName())) {
                throw new BadRequest("组员信息表第" + (i + 1) + "行, 应急救援小组名称为必填信息！");
            }
            if (ObjectUtils.isEmpty(dto.getMemberName())) {
                throw new BadRequest("组员信息表第" + (i + 1) + "行, 组员姓名为必填信息！");
            }
            if (ObjectUtils.isEmpty(dto.getTelephone())) {
                throw new BadRequest("组员信息表第" + (i + 1)+ "行, 组员电话为必填信息！");
            }
        }
    }


    @Override
    public Organization saveOrganization(Organization organization) {
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Organization::getEmergencyTeamName, organization.getEmergencyTeamName());
        List<Organization> organizations = this.list(wrapper);
        if (!CollectionUtils.isEmpty(organizations)) {
            throw new BadRequest("应急小组名称重复!");
        }
        organization.setSort(organizationMapper.selectMaxSort() + 1);
        return this.createWithModel(organization);
    }

    @Override
    public Organization updateModelById(Organization organization) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(BaseEntity::getSequenceNbr, organization.getSequenceNbr());
        queryWrapper.eq(Organization::getEmergencyTeamName, organization.getEmergencyTeamName());
        List<Organization> organizations = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(organizations)) {
            throw new BadRequest("应急小组名称重复!");
        }
        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.gt(Organization::getSort, sort);
            wrapper.orderByAsc(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.lt(Organization::getSort, sort);
            wrapper.orderByDesc(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.orderByDesc(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);
    }
}
