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.sun.org.apache.bcel.internal.generic.NEW;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrFormDto;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
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 freemarker.template.utility.DateUtil;
import lombok.extern.slf4j.Slf4j;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


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

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OrganizationUserMapper organizationUserMapper;

    private static String NAME = "组员信息表第";
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Override
    public Page<Map<String, Object>> getOrganizationInfo(Page<Map<String, Object>> page, String bizOrgCode) {
        Page<Map<String, Object>> page1 = new Page<>();
        List<Map<String, Object>> list = organizationMapper.getOrganizationInfo(bizOrgCode);
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Organization::getSort);
        List<Organization> organizations = this.baseMapper.selectList(wrapper);
        List<Map<String, Object>> res = new ArrayList<>();
        if (0 < list.size()) {
            // 获取值长
            Map<String, Object> resMap = this.baseMapper.getTeamLeader();
            Map<String, Object> leaderMap = new HashMap<>();
            if (ObjectUtils.isEmpty(resMap.get("value"))) {
                leaderMap.put("name", resMap.get("name") + "");
                leaderMap.put("value", "");
            } else {
                // 跟现场确认此处值长只有一人，所以只做一人处理
                leaderMap.put("name", resMap.get("name") + " " + "1人");
                leaderMap.put("value", resMap.get("value") + ( ObjectUtils.isNotEmpty(resMap.get("tel")) ? "-" + resMap.get("tel") : "" ));
            }
            res.add(leaderMap);

            for (Map<String, Object> map : list) {
                Map<String, Object> tempMap = new HashMap<>();
                if (ObjectUtils.isEmpty(map.get("value"))) {
                    tempMap.put("name", map.get("name") + "");
                    tempMap.put("value", "");
                } else {
                    tempMap.put("name", map.get("name") + " " + map.get("value") + "人");
                    List<Organization> organizationList = organizations.stream().filter(x -> x.getEmergencyTeamName().equals(map.get("name"))).collect(Collectors.toList());
                    if (0 < organizationList.size()) {
                        Organization organization = organizationList.get(0);
                        String[] nameArr = organization.getGroupLeader().split(",");
                        List<String> nameList = Arrays.asList(nameArr);
                        String[] telArr = new String[nameList.size()];
                        if (ObjectUtils.isNotEmpty(organization.getGroupLeaderTel())) {
                            telArr = organization.getGroupLeaderTel().split("\n");
                        }
                        List<String> telList = Arrays.asList(telArr);
                        List<String> valueList = new ArrayList<>();
                        for (int i = 0; i < nameList.size(); i++) {
                            valueList.add(nameList.get(i) + "-" + telList.get(i));
                        }
                        tempMap.put("value", String.join(",", valueList));
                    }
                }
                res.add(tempMap);
            }
        }
        page1.setRecords(res);
        return page1;
    }

    @Override
    public Page<Map<String, Object>> getOrganizationList(Page<Map<String, Object>> page, String bizOrgCode) {

        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 || data.size() > 0 || userData.size() > 0) {
            throw new BadRequest("请填入数据导入！");
        }
        //对分组数据入库

        int sort1 = 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);
                sort1 = sort1 + 1;
                organization.setSort(sort1);
                organization.setBizOrgCode(bizOrgCode);
                organizationMapper.insert(organization);
            }

        }

        //对人员数据入库

        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);
            }
        }


    }

    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(NAME + (i + 1) + "行, 应急救援小组名称为必填信息！");
            }
            if (ObjectUtils.isEmpty(dto.getMemberName())) {
                throw new BadRequest(NAME + (i + 1) + "行, 组员姓名为必填信息！");
            }
            if (ObjectUtils.isEmpty(dto.getTelephone())) {
                throw new BadRequest(NAME + (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);
        } 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);
    }

    @Override
    public Map<String, Object> getSystemOnlineDate(String id) {
        try {
            OrgUsrFormDto orgUsrFormDto = iOrgUsrService.selectCompanyById(Long.parseLong(id));
            if (ObjectUtils.isNotEmpty(orgUsrFormDto)) {
                String operationDate = String.valueOf(orgUsrFormDto.getMap().get("operationDate"));
                Date beginDate = DateUtils.convertStrToDate(operationDate, DateUtils.DATE_PATTERN);
                Date now = DateUtils.getDateNow();
                return DateUtils.dayComparePrecise(beginDate, now);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取系统上线时间失败：{}", e.getMessage());
        }
        return new HashMap<>(1);
    }
}
