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

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.MaintenanceCompanyDto;
import com.yeejoin.amos.boot.module.common.api.dto.MaintenancePersonExcleDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.DynamicFormInstanceMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.MaintenanceCompanyMapper;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
import org.apache.commons.lang3.StringUtils;
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.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 维保单位服务实现类
 *
 * @author system_generator
 * @date 2021-07-16
 */
@Service
public class MaintenanceCompanyServiceImpl
        extends BaseService<MaintenanceCompanyDto, MaintenanceCompany, MaintenanceCompanyMapper>
        implements IMaintenanceCompanyService {

    private static final String MAINTENANCE_COMPANY = "maintenanceCompany";
    private static final String MAINTENANCE_PERSON = "maintenancePerson";
    private static final String MAINTENANCE_DEPARTMENT = "maintenanceDepartment";

    private static final String PERSON = "PERSON";
    private static final String COMPANY = "COMPANY";
    private static final String DEPARTMENT = "DEPARTMENT";

    @Autowired
    DynamicFormInstanceServiceImpl dynamicFormInstanceService;

    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;

    @Autowired
    Sequence sequence;

    @Autowired
    MaintenanceCompanyMapper maintenanceCompanyMapper;

    @Autowired
    IOrgUsrService iOrgUsrService;

    @Autowired
    DynamicFormInstanceMapper dynamicFormInstanceMapper;

    @Autowired
    SourceFileServiceImpl sourceFileService;

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

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

    /**
     * 添加维保单位基本信息
     *
     * @param maintenanceCompany
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MaintenanceCompany saveCompanyDetail(MaintenanceCompany maintenanceCompany) {
        Long instanceId = saveDynamicFormList(maintenanceCompany);
        // 设置单位code
        setTargetObjCode(maintenanceCompany);

        maintenanceCompany.setOrgCode(null);
        maintenanceCompany.setBizCode(sequence.nextId() + "");
        maintenanceCompany.setInstanceId(instanceId);
        maintenanceCompany.setType(maintenanceCompany.getType().toUpperCase());
        maintenanceCompany.setIsDelete(false);
        this.save(maintenanceCompany);
        if (maintenanceCompany.getAttachments().isEmpty()) {
            sourceFileService.saveAttachments(maintenanceCompany.getSequenceNbr(), maintenanceCompany.getAttachments());
        }
        return maintenanceCompany;
    }

    /**
     * 设置单位code
     *
     * @param targetObj
     */
    private void setTargetObjCode(MaintenanceCompany targetObj) {
        MaintenanceCompany parent = getById(targetObj.getParentId());
        if (!ValidationUtil.isEmpty(parent)) {
            // 当前的code为上级单位code+6位随机数
            targetObj.setCode(parent.getCode() + TreeParser.genTreeCode());
        } else {
            targetObj.setCode(TreeParser.genTreeCode());
        }
    }

    @Override
    public MaintenanceCompany savePersonDetail(MaintenanceCompany maintenanceCompany) {
        Long instanceId = saveDynamicFormList(maintenanceCompany);
        Long parentId = maintenanceCompany.getParentId();
        // 设置人员code
        setTargetObjCode(maintenanceCompany);
        maintenanceCompany.setOrgCode(null);
        if (ValidationUtil.isEmpty(maintenanceCompany.getBizCode())) {
            maintenanceCompany.setBizCode(sequence.nextId() + "");
        }
        maintenanceCompany.setInstanceId(instanceId);
        maintenanceCompany.setParentId(parentId);
        maintenanceCompany.setIsDelete(false);
        this.save(maintenanceCompany);
        if (maintenanceCompany.getAttachments().isEmpty()) {
            sourceFileService.saveAttachments(maintenanceCompany.getSequenceNbr(), maintenanceCompany.getAttachments());
        }
        return maintenanceCompany;
    }

    /**
     * 添加动态表单信息
     *
     * @param maintenanceCompany
     * @return
     */
    public Long saveDynamicFormList(MaintenanceCompany maintenanceCompany) {
        Long instanceId = sequence.nextId();
        List<DynamicFormInstance> dynamicFormInstanceList = maintenanceCompany.getDynamicFormValue();
        for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
            dynamicFormInstance.setInstanceId(instanceId);
            dynamicFormInstanceService.save(dynamicFormInstance);
        }
        return instanceId;
    }

    @Override
    public MaintenanceCompany saveDepartmentDetail(MaintenanceCompany maintenanceCompany) {
        Long instanceId = saveDynamicFormList(maintenanceCompany);
        Long parentId = maintenanceCompany.getParentId();
        setTargetObjCode(maintenanceCompany);
        maintenanceCompany.setOrgCode(null);
        maintenanceCompany.setBizCode(sequence.nextId() + "");
        maintenanceCompany.setInstanceId(instanceId);
        maintenanceCompany.setType(maintenanceCompany.getType().toUpperCase());
        maintenanceCompany.setParentId(parentId);
        maintenanceCompany.setIsDelete(false);
        this.save(maintenanceCompany);
        if (maintenanceCompany.getAttachments().isEmpty()) {
            sourceFileService.saveAttachments(maintenanceCompany.getSequenceNbr(), maintenanceCompany.getAttachments());
        }
        return maintenanceCompany;
    }

    @Override
    public boolean deleteById(Long sequenceNbr) {
        MaintenanceCompany maintenanceCompany = maintenanceCompanyMapper.selectById(sequenceNbr);
        if (ObjectUtils.isEmpty(maintenanceCompany)) {
            return false;
        }
        // 新增删除维保单位逻辑，BUG 2500 单位下有子单位或者人员时应无法直接删除. by litw  satrt
        LambdaQueryWrapper<MaintenanceCompany> wrapperCompany = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapperCompany.eq(MaintenanceCompany::getParentId, sequenceNbr);
        wrapperCompany.eq(MaintenanceCompany::getIsDelete, false);
        int count = maintenanceCompanyMapper.selectCount(wrapperCompany);
        if (count > 0) {
            throw new BadRequest("单位下有子单位或者人员,无法删除");
        }

        // 新增删除维保单位逻辑，BUG 2500 单位下有子单位或者人员时应无法直接删除. by litw  end
        maintenanceCompany.setIsDelete(true);
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getSequenceNbr, sequenceNbr);

        int number = maintenanceCompanyMapper.update(maintenanceCompany, wrapper);
        if (number > 0) {
            // 更新动态表单字段为删除状态
            List<DynamicFormInstance> dyInstance = dynamicFormInstanceService
                    .list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId,
                            maintenanceCompany.getInstanceId()));
            dyInstance.forEach(i -> i.setIsDelete(true));
            dynamicFormInstanceService.updateBatchById(dyInstance);
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getMaintenanceCompanyDropDownList() {
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.select(MaintenanceCompany::getCode, MaintenanceCompany::getName, MaintenanceCompany::getSequenceNbr);
        wrapper.eq(MaintenanceCompany::getType, COMPANY);
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        return maintenanceCompanyMapper.selectMaps(wrapper);
    }

    @Override
    public boolean checkPersonCodeExists(String code) {
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getBizCode, code);
        MaintenanceCompany detail = maintenanceCompanyMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(detail)) {
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getAllMaintenanceList(String maintenanceType) {
        String type = null;
        switch (maintenanceType.toUpperCase()) {
            case PERSON:
                type = MAINTENANCE_PERSON;
                break;
            case DEPARTMENT:
                type = MAINTENANCE_DEPARTMENT;
                break;
            default:
                type = MAINTENANCE_COMPANY;
        }
        if (StringUtils.isBlank(type)) {
            return null;
        }
        List<Map<String, Object>> dynamicFormList = dynamicFormInstanceService.listAll(type);
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        List<MaintenanceCompany> maintenanceCompany = this.list(wrapper);

        Map<Long, MaintenanceCompany> maintenanceCompanyMap = maintenanceCompany.stream()
                .collect(Collectors.toMap(MaintenanceCompany::getInstanceId, Function.identity()));
        dynamicFormList.forEach(r -> {
            MaintenanceCompany detail = maintenanceCompanyMap.get(Long.parseLong(r.get("instanceId").toString()));
            if (!ObjectUtils.isEmpty(detail)) {
                if (detail.getParentId() != null) {
                    MaintenanceCompany map = maintenanceCompanyMapper.selectById(detail.getParentId());
                    r.put("parentName", map.getName());
                }
                r.putAll(Bean.BeantoMap(detail));
            }
        });
        return dynamicFormList;
    }

    public List<Map<String, Object>> getAllMaintenanceEexcleList(String maintenanceType, Map parms) {
        String type = null;
        switch (maintenanceType.toUpperCase()) {
            case PERSON:
                type = MAINTENANCE_PERSON;
                break;
            case DEPARTMENT:
                type = MAINTENANCE_DEPARTMENT;
                break;
            default:
                type = MAINTENANCE_COMPANY;
        }
        if (StringUtils.isBlank(type)) {
            return null;
        }
        List<Map<String, Object>> dynamicFormList = dynamicFormInstanceService.listAll(type);
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        if (parms != null && parms.size() > 0) {
            String name = parms.containsKey("name") ? parms.get("name").toString() : null;
            String parentId = parms.containsKey("parentId") ? parms.get("parentId").toString() : null;
            if (name != null) {
                wrapper.like(MaintenanceCompany::getName, name);
            }
            if (parentId != null) {
                wrapper.eq(MaintenanceCompany::getParentId, parentId);
            }

        }
        List<MaintenanceCompany> maintenanceCompany = this.list(wrapper);

        Map<Long, MaintenanceCompany> maintenanceCompanyMap = maintenanceCompany.stream()
                .collect(Collectors.toMap(MaintenanceCompany::getInstanceId, Function.identity()));
        dynamicFormList.forEach(r -> {
            MaintenanceCompany detail = maintenanceCompanyMap.get(Long.parseLong(r.get("instanceId").toString()));
            if (!ObjectUtils.isEmpty(detail)) {
                if (detail.getParentId() != null && detail.getName() != null) {
                    MaintenanceCompany map = maintenanceCompanyMapper.selectById(detail.getParentId());
                    r.put("parentName", map.getName());
                    r.putAll(Bean.BeantoMap(detail));
                }
            }
        });
        return dynamicFormList.stream().filter(i -> i.containsKey("name")).collect(Collectors.toList());
    }

    @Override
    public List<MaintenancePersonExcleDto> exportToMaintenancePersonExcel(Map map) {
        List<Map<String, Object>> list = this.getAllMaintenanceEexcleList(PERSON, map);
        return JSONArray.parseArray(JSONArray.toJSONString(list), MaintenancePersonExcleDto.class);
    }

    @Override
    public List<MaintenanceCompany> findByInstanceIdAndType(Long instanceId, String type) {
        List<MaintenanceCompany> list = maintenanceCompanyMapper.findByInstanceIdAndType(instanceId, type);
        if (!CollectionUtils.isEmpty(list)) {
            return list;
        }
        return Lists.newArrayList();
    }

    @Override
    public List<MaintenanceCompany> findByCodeAndType(String code, String type) {
        List<MaintenanceCompany> list = maintenanceCompanyMapper.findByCodeAndType(code, type);
        if (!CollectionUtils.isEmpty(list)) {
            return list;
        }
        return Lists.newArrayList();
    }

    @Override
    public List<MaintenanceCompany> findPersonByAmosOrgId(String code, String userId) {
        LambdaQueryWrapper<MaintenanceCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaintenanceCompany::getType, code);
        queryWrapper.eq(MaintenanceCompany::getAmosId, userId);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public MaintenanceCompany getOne(Long parentId) {
        return this.getById(parentId);
    }

    /**
     * 维保单位人员信息分頁信息显示时的字段过滤
     *
     * @param current
     * @param size
     * @param list
     * @param arrayType
     * @return
     */
    public IPage<Map<String, Object>> getLegalList(int current, int size, IPage<Map<String, Object>> list,
                                                   String[] arrayType) {
        List<Map<String, Object>> returnlist = new ArrayList<Map<String, Object>>();
        Map<String, Object> legalMap = null;
        for (Map<String, Object> map : list.getRecords()) {
            legalMap = new HashMap<String, Object>();
            for (Map.Entry<String, Object> m : map.entrySet()) {
                if (Arrays.asList(arrayType).contains(m.getKey())) {
                    legalMap.putAll(map);
                }
            }
            returnlist.add(legalMap);
        }
        Page<Map<String, Object>> pegaIPage = new Page<Map<String, Object>>();
        pegaIPage.setCurrent(current);
        pegaIPage.setSize(size);
        pegaIPage.setRecords(returnlist);
        return pegaIPage;
    }

    @Override
    public IPage<Map<String, Object>> getPageMaintenanceList(Map<String, Object> paramsMap) {
        if (!paramsMap.containsKey("current") && !paramsMap.containsKey("size")) {
            return null;
        }
        if (!paramsMap.containsKey("maintenanceType")) {
            return null;
        }
        int current = Integer.parseInt(paramsMap.get("current").toString());
        int size = Integer.parseInt(paramsMap.get("size").toString());
        String maintenanceType = paramsMap.get("maintenanceType").toString().toUpperCase();
        Map<String, String> filedParamsMap = Maps.newHashMap();

        List<MaintenanceCompany> mainTableList;
        String type;
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        switch (maintenanceType) {
            case PERSON:
                type = MAINTENANCE_PERSON;
                filedParamsMap = new HashMap<>();
                if (paramsMap.containsKey("status")) {
                    filedParamsMap.put("status", paramsMap.get("status").toString());
                }
                mainTableList = this.checkMaintenanceCompanyList(wrapper, paramsMap);
                /*BUG 2503  人员头像存在附件中，获取附件信息返回前端  start*/
                for (MaintenanceCompany m : mainTableList
                ) {
                    m.setAttachments(sourceFileService.getAttachments(m.getSequenceNbr()));
                }
                /* *BUG 2503 end*/
                List<Long> instanceIds = Lists.transform(mainTableList, MaintenanceCompany::getInstanceId);
                filedParamsMap.put("instanceIds", Joiner.on(",").join(instanceIds));
                break;
            case COMPANY:
                type = MAINTENANCE_COMPANY;
                wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
                mainTableList = this.list(wrapper);
                break;
            case DEPARTMENT:
                type = MAINTENANCE_DEPARTMENT;
                wrapper.eq(MaintenanceCompany::getType, maintenanceType.toUpperCase());
                mainTableList = this.list(wrapper);
                break;
            default:
                throw new IllegalStateException("Unexpected maintenanceType: " + maintenanceType);
        }
        if (StringUtils.isBlank(type)) {
            return null;
        }
        IPage<Map<String, Object>> page = dynamicFormInstanceService.pageList(current, size, type, filedParamsMap);

        Map<Long, MaintenanceCompany> maintenanceCompanyMap = mainTableList.stream()
                .collect(Collectors.toMap(MaintenanceCompany::getInstanceId, Function.identity()));

        page.getRecords().forEach(r -> {
            MaintenanceCompany detail = maintenanceCompanyMap.get(Long.parseLong(r.get("instanceId").toString()));
            if (!ObjectUtils.isEmpty(detail)) {
                r.putAll(Bean.BeantoMap(detail));
            }

        });
        return page;
    }

    public List<MaintenanceCompany> checkMaintenanceCompanyList(LambdaQueryWrapper<MaintenanceCompany> wrapper,
                                                                Map<String, Object> paramsMap) {
        if (paramsMap.containsKey("name")) {
            wrapper.like(MaintenanceCompany::getName, paramsMap.get("name").toString());
        }
        if (paramsMap.containsKey("parentId") && !"-1".equals(paramsMap.get("parentId"))) {
            Long parentId = Long.parseLong(paramsMap.get("parentId").toString());
            MaintenanceCompany company = getOne(
                    new LambdaQueryWrapper<MaintenanceCompany>().eq(MaintenanceCompany::getSequenceNbr, parentId));
            wrapper.likeRight(MaintenanceCompany::getCode, company.getCode());
        }
        wrapper.eq(MaintenanceCompany::getType, PERSON);

        return maintenanceCompanyMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> findBySequenceNbr(Long sequenceNbr) {
        MaintenanceCompany maintenanceCompany = maintenanceCompanyMapper.selectById(sequenceNbr);
        String type;
        switch (maintenanceCompany.getType()) {
            case PERSON:
                type = MAINTENANCE_PERSON;
                break;
            case DEPARTMENT:
                type = MAINTENANCE_DEPARTMENT;
                break;
            default:
                type = MAINTENANCE_COMPANY;
        }
        Map<String, Object> mainMap = Bean.BeantoMap(maintenanceCompany);
        Map<String, Object> dynamicMap = dynamicFormInstanceService.getOneMap(maintenanceCompany.getInstanceId(), type);
        mainMap.put("attachments", sourceFileService.getAttachments(maintenanceCompany.getSequenceNbr()));
        mainMap.put("dynamicFormValue", dynamicMap);
        return mainMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMaintenanceCompanyDetail(MaintenanceCompany model) throws Exception {
        return updateMaintenanceDetail(model, COMPANY);
    }

    public boolean updateMaintenanceDetail(MaintenanceCompany model, String type) throws Exception {
        return updateDetail(model, type);
    }

    public boolean updateDetail(MaintenanceCompany model, String type) throws Exception {
        // 1、更新动态表单数据
        iOrgUsrService.updateDynamicFormInstance(model.getInstanceId(), model.getDynamicFormValue());
        // 2、更新单位及子单位code
        updateCode(model);
        // 3、更新主表数据
        model.setType(type);
        this.updateById(model);
        if (ValidationUtil.isEmpty(model.getParentId())) {
            update(new LambdaUpdateWrapper<MaintenanceCompany>().set(MaintenanceCompany::getParentId, null).eq(MaintenanceCompany::getSequenceNbr, model.getSequenceNbr()));
        }
        // 4、更新附件
        sourceFileService.saveAttachments(model.getSequenceNbr(), model.getAttachments());
        return true;
    }

    /**
     * 更新单位及子单位code
     *
     * @return company 维保单位/部门/人员
     */
    public void updateCode(MaintenanceCompany company) {
        MaintenanceCompany parent = getById(company.getParentId());
        // 新父节点的code
        String parentCode = "";
        // 父节点不为空
        if (!ValidationUtil.isEmpty(parent)) {
            parentCode = parent.getCode();
        }
        // 旧父节点的code
        if (company.getCode() != null) {
            String oldParentCode = company.getCode().substring(0, company.getCode().length() - TreeParser.CODE_LENGTH);
            List<MaintenanceCompany> children =
                    list(new LambdaQueryWrapper<MaintenanceCompany>().eq(MaintenanceCompany::getIsDelete, false).likeRight(MaintenanceCompany::getCode, company.getCode()).ne(MaintenanceCompany::getSequenceNbr, company.getSequenceNbr()));
            if (!ValidationUtil.isEmpty(children)) {
                String finalParentCode = parentCode;
                children.forEach(i -> {
                    i.setCode(i.getCode().replaceFirst(oldParentCode, finalParentCode));
                });
                updateBatchById(children);
            }
            company.setCode(company.getCode().replaceFirst(oldParentCode, parentCode));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMaintenancePersonDetail(MaintenanceCompany model) throws Exception {
        return updateMaintenanceDetail(model, PERSON);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMaintenanceDepartmentDetail(MaintenanceCompany model) throws Exception {
        return updateMaintenanceDetail(model, DEPARTMENT);
    }

    @Override
    public List<MaintenanceCompany> getCompanyAndDepartmentTree() {
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
                MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
        wrapper.eq(MaintenanceCompany::getIsDelete, 0);
        wrapper.in(MaintenanceCompany::getType, Arrays.asList(COMPANY, DEPARTMENT));
        List<MaintenanceCompany> list = maintenanceCompanyMapper.selectList(wrapper);
        if (list == null) {
            return new ArrayList<>();
        }
        list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<MaintenanceCompany> getDepartmentAndPersonTree(long sequenceNbr) {
        List<MaintenanceCompany> departmentList = getDepartmentList(sequenceNbr);
        if (departmentList == null) {
            return new ArrayList<>();
        }
        return departmentList.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
    }

    @Override
    public List<MaintenanceCompany> getDepartmentList(long sequenceNbr) {
        MaintenanceCompany companyDetail = maintenanceCompanyMapper.selectById(sequenceNbr);
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
                MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        wrapper.in(MaintenanceCompany::getType, Arrays.asList(PERSON, DEPARTMENT));
        wrapper.likeRight(MaintenanceCompany::getCode, companyDetail.getCode());
        List<MaintenanceCompany> maintenanceCompanyList = maintenanceCompanyMapper.selectList(wrapper);
        return maintenanceCompanyList;
    }

    public List<MaintenanceCompany> getPersonList(long sequenceNbr) {
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.select(MaintenanceCompany::getSequenceNbr, MaintenanceCompany::getName, MaintenanceCompany::getCode,
                MaintenanceCompany::getType, MaintenanceCompany::getBizCode, MaintenanceCompany::getParentId);
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        wrapper.eq(MaintenanceCompany::getType, PERSON);
        wrapper.eq(MaintenanceCompany::getParentId, sequenceNbr);
        return maintenanceCompanyMapper.selectList(wrapper);
    }

    /**
     * 根据维保单位查询所有机场单位(返回List<Map>类型) 不带分页
     *
     * @param seq
     * @return
     */
    public List<Map<String, Object>> queryOrgUsrMsg(Long seq) {
        if (ValidationUtil.isEmpty(this.queryBySeq(seq))) {
            throw new BadRequest("参数校验失败.");
        } else {
            List<Map<String, Object>> companys = new ArrayList<>();
            // 机场单位列表基本信息
            List<OrgUsrDto> orgUsrDtos = this.baseMapper.selectOrgUsrList(seq);
            // 机场组装单位动态表单数据
            orgUsrDtos.forEach(orgUsrDto -> {
                Map<String, Object> map = Bean.BeantoMap(orgUsrDto);
                mapCopy(dynamicFormInstanceService.getOneMap(orgUsrDto.getSequenceNbr(), OrgPersonEnum.公司.getKey()),
                        map);

                companys.add(map);
            });
            return companys;
        }
    }

    /**
     * 根据维保单位查询所有机场单位(返回List<Map>类型) 带分页
     *
     * @param pageNum
     * @param pageSize
     * @param seq
     * @param amosUserId
     * @return
     */
    public Page<Map<String, Object>> queryOrgUsrMsgPage(int pageNum, int pageSize, Long seq, String amosUserId) {
        MaintenanceCompany maintenanceCompany = new MaintenanceCompany();
        if (ValidationUtil.isEmpty(seq)) {
            maintenanceCompany = getMaintenanceCompany(amosUserId);
            seq = maintenanceCompany.getSequenceNbr();
        }
        // 机场单位列表基本信息
        if (pageNum == -1 || pageSize == -1) {
            pageSize = Integer.MAX_VALUE;
        }
        Page page = new Page(pageNum, pageSize);
        Page<Map<String, Object>> companys = new Page<>(pageNum, pageSize);
        Page<OrgUsrDto> pageResult = this.baseMapper.selectOrgUsrPageList(page, seq);
        List<Map<String, Object>> finalResultMap = Lists.newArrayList();
        // 机场组装单位动态表单数据
        pageResult.getRecords().forEach(orgUsrDto -> {
            Map<String, Object> map = Bean.BeantoMap(orgUsrDto);
            mapCopy(dynamicFormInstanceService.getOneMap(orgUsrDto.getSequenceNbr(), OrgPersonEnum.公司.getKey()), map);
            finalResultMap.add(map);
        });
        companys.setRecords(finalResultMap);
        companys.setTotal(pageResult.getTotal());
        companys.setPages(pageResult.getPages());
        return companys;
    }

    /**
     * 根据平台用户id查询登陆人所属维保单位
     *
     * @param amosUserId
     * @return
     */
    public MaintenanceCompany getMaintenanceCompany(String amosUserId) {
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        wrapper.eq(MaintenanceCompany::getAmosId, amosUserId);
        MaintenanceCompany maintenancePerson = this.baseMapper.selectOne(wrapper);
//		DynamicFormInstance dyFormInstance = dynamicFormInstanceService.getOne(
//				new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getFieldCode, "amosAccount")
//						.eq(DynamicFormInstance::getFieldValue, amosUserId));
        if (ValidationUtil.isEmpty(maintenancePerson)) {
            throw new BadRequest("维保账号不存在或未关联系统账号.");
        }
//		MaintenanceCompany person = this.getOne(new LambdaQueryWrapper<MaintenanceCompany>()
//				.eq(MaintenanceCompany::getInstanceId, dyFormInstance.getInstanceId()));
//		if (ValidationUtil.isEmpty(person)) {
//			throw new BadRequest("维保账号不存在或未关联系统账号.");
//		}
        MaintenanceCompany	maintenanceCompany = this.getOne(new LambdaQueryWrapper<MaintenanceCompany>()
				.eq(MaintenanceCompany::getSequenceNbr, maintenancePerson.getParentId()));
		if (ValidationUtil.isEmpty(maintenanceCompany)) {
			throw new BadRequest("维保公司不存在或未关联系统账号.");
		}
        return maintenanceCompany;
    }

    public List<Map<String, Object>> queryCompanyMsg() {
        List<Map<String, Object>> companysMsg = new ArrayList<>();
        LambdaQueryWrapper<MaintenanceCompany> wrapper = new LambdaQueryWrapper<MaintenanceCompany>();
        wrapper.eq(MaintenanceCompany::getIsDelete, false);
        wrapper.eq(MaintenanceCompany::getType, COMPANY);
        // 查询所有维保单位信息
        List<MaintenanceCompany> lists = maintenanceCompanyMapper.selectList(wrapper);
        //List<MaintenanceCompany> lists = this.list();
        lists.forEach(list -> {
            Map<String, Object> maintenanceCompany = new HashMap<>();
            maintenanceCompany.put("id", list.getSequenceNbr());
            maintenanceCompany.put("code", list.getCode());
            maintenanceCompany.put("name", list.getName());
            maintenanceCompany.put("type", 1);
            maintenanceCompany.put("parentId", 0);
            // 查询该维保单位下的业主信息
            List<OrgUsrDto> orgUsrDtos = this.baseMapper.selectOrgUsrList(list.getSequenceNbr());
            orgUsrDtos.forEach(orgUsrDto -> {
                Map<String, Object> airCompany = new HashMap<>();
                airCompany.put("id", orgUsrDto.getSequenceNbr());
                airCompany.put("code", orgUsrDto.getBizOrgCode());
                airCompany.put("name", orgUsrDto.getBizOrgName());
                airCompany.put("type", 2);
                airCompany.put("parentId", list.getSequenceNbr());
                companysMsg.add(airCompany);
            });
            companysMsg.add(maintenanceCompany);
        });
        return companysMsg;
    }

    /**
     * 复制map对象
     *
     * @param paramsMap 被拷贝对象
     * @param resultMap 拷贝后的对象
     * @explain 将paramsMap中的键值对全部拷贝到resultMap中；
     */
    private static void mapCopy(Map paramsMap, Map resultMap) {
        if (resultMap == null) {
            return;
        }
        if (paramsMap == null) {
            return;
        }
        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
        }
    }

    @Override
    public List<DynamicFormInstance> maintenancePersonExcleDtoToDynamicFormInstanceList(List<DynamicFormColumn> columns,
                                                                                        MaintenancePersonExcleDto maintenancePersonExcleDto, long instanceId, List<DynamicFormInstance> list) {

        Map<String, Object> maintenancePersonExcleDtoMap = Bean.BeantoMap(maintenancePersonExcleDto);
        // 填充动态表单的属性

        columns.stream().forEach(item -> {
            if (maintenancePersonExcleDtoMap.containsKey(item.getFieldCode())) {
                DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
                String valueString = maintenancePersonExcleDtoMap.get(item.getFieldCode()).toString();
                Bean.copyExistPropertis(item, dynamicFormInstance);

                dynamicFormInstance.setAppKey(RequestContext.getAppKey());
                dynamicFormInstance.setInstanceId(instanceId);
                dynamicFormInstance.setSequenceNbr(sequence.nextId());
                dynamicFormInstance.setFormColumnId(item.getSequenceNbr());
                dynamicFormInstance.setFieldValue(maintenancePersonExcleDtoMap.get(item.getFieldCode()) != null
                        ? maintenancePersonExcleDtoMap.get(item.getFieldCode()).toString()
                        : "");
                if (valueString.contains("@")) {
                    String[] mapDetailArray = valueString.split("@");
                    dynamicFormInstance.setFieldValue(mapDetailArray[0]);
                    if (mapDetailArray.length > 1) {
                        dynamicFormInstance.setFieldValueLabel(mapDetailArray[1]);
                    }
                }
                if (dynamicFormInstance != null && dynamicFormInstance.getSequenceNbr().longValue() > 0) {
                    list.add(dynamicFormInstance);
                }
            }

        });

        return list;
    }

    public boolean saveDynamicFormInstanceBatch(List<DynamicFormInstance> list) {
        dynamicFormInstanceService.saveBatch(list);
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMaintenanceCompanyBatch(List<MaintenanceCompany> companyList, List<DynamicFormInstance> list) {
        saveDynamicFormInstanceBatch(list);
        this.saveBatch(companyList);
        return false;
    }

    /**
     * 查询当前登陆用户所在维保单位下的维保人员列表部门列表,不分页
     *
     * @param companyId
     * @param userId
     * @return
     */
    public List<Map<String, Object>> getPersonListByCompanyId(Long companyId, String userId) {
        MaintenanceCompany company;
        if (ValidationUtil.isEmpty(companyId)) {
            company = getMaintenanceCompany(userId);
            if (ValidationUtil.isEmpty(company)) {
                throw new BadRequest("用户不存在");
            }
        } else {
            company = this.getById(companyId);
        }
        // 查询公司下人列表
        List<MaintenanceCompany> personList = list(new LambdaQueryWrapper<MaintenanceCompany>()
                .eq(MaintenanceCompany::getIsDelete, false).eq(MaintenanceCompany::getType, PERSON)
                .eq(MaintenanceCompany::getParentId,company.getParentId()));
        List<Long> instanceIdList = Lists.transform(personList, MaintenanceCompany::getInstanceId);
        // 查询手机号
        List<DynamicFormInstance> dynamicFormInstanceList = dynamicFormInstanceService
                .list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getFieldCode, "tel")
                        .in(DynamicFormInstance::getInstanceId, instanceIdList));
        Map<Long, List<DynamicFormInstance>> dyMap = dynamicFormInstanceList.stream()
                .collect(Collectors.groupingBy(DynamicFormInstance::getInstanceId));
        List<Map<String, Object>> resultList = Lists.newArrayList();
        personList.forEach(person -> {
            Map<String, Object> map = Maps.newHashMap();
            map.put("sequenceNbr", person.getSequenceNbr());
            map.put("name", person.getName());
            map.put("tel", dyMap.get(person.getInstanceId()) != null ? dyMap.get(person.getInstanceId()).get(0).getFieldValue() : null);
            resultList.add(map);
        });
        return resultList;
    }
}