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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectResourceEnum;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectResource;
import com.yeejoin.amos.boot.module.ugp.api.mapper.CompanyMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.WelderMapper;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

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

@Service
public class WelderServiceImpl {

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    ProjectResourceServiceImpl projectResourceService;

    @Value("${amos.secret.key}")
    String secretKey;

    @Autowired
    OrgUsrServiceImpl orgUsrService;

    @Autowired
    WelderMapper welderMapper;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    MaterialServiceImpl materialServiceImpl;

    @Autowired
    DynamicFormInstanceServiceImpl alertFormValueServiceImpl;



    /**
     * 获取当前登录所在单位下的项目中的所有焊工列表
     * @return
     */
    @BusinessIdentify
    public List<Map> getInfo(){
        List<Project> projectList = projectResourceService.getProjectList();
        List<Long> projectIdList = new ArrayList<>();
        List<Long> welderIdList = new ArrayList<>();
        for(Project project:projectList){
            projectIdList.add(project.getSequenceNbr());
        }
        for(Long projectId:projectIdList){
            LambdaQueryWrapper<ProjectResource> projectResourceWrapper = new LambdaQueryWrapper<>();
            projectResourceWrapper.eq(ProjectResource::getType, ProjectResourceEnum.焊工资源.getCode())
                    .eq(ProjectResource::getProjectId,projectId);
            List<ProjectResource> projectResourceList = projectResourceService.list(projectResourceWrapper);
            for(ProjectResource projectResource : projectResourceList){
                welderIdList.add(projectResource.getResourceId());
            }
        }
        List<Map> mapList = new ArrayList<>();
        for(Long welderId:welderIdList){
            mapList.add(orgService.getdetialInfo(String.valueOf(welderId)));
        }
        return mapList;
    }

    public IPage<Map> getpageInfo(){
        IPage<Map> page = new Page<>();
        page.setSize(getInfo().size());
        page.setCurrent(1L);
        page.setRecords(getInfo());
        page.setTotal(getInfo().size());
        return page;
    }

    /**
     * 存人员信息至业务表及平台表
     * @param jsonObject
     * @param bizOrgType
     * @param sequenceNbr
     * @return
     */
    @BusinessIdentify
    public OrgUsrDto savePerson(JSONObject jsonObject, String bizOrgType, String sequenceNbr){
        if(ValidationUtil.isEmpty(sequenceNbr)){
            Long  companyId= orgService.getReginParams().getCompany().getSequenceNbr();
            Long companyUserId =  orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr();
            String orgexpand = orgService.getOrgUsrById(String.valueOf(companyUserId)).getOrgExpandAttr1();
            Set<String> roleNameSet = new HashSet<>();
            List<RoleModel> userRoleList = new ArrayList<>();
            List<Long> roleIds = new ArrayList<>();
            Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            Map<Long,List<RoleModel>> orgRoles = new HashMap<>();
            //用户基本信息
            agencyUserModel.setRealName(jsonObject.getString("name"));
            agencyUserModel.setAgencyCode("ugp");
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setMobile(jsonObject.getString("phone"));
            agencyUserModel.setCreateTime(new Date());
            agencyUserModel.setUserName(jsonObject.getString("phone"));
            agencyUserModel.setPassword(DesUtil.encode(jsonObject.getString("phone"), secretKey));
            agencyUserModel.setRePassword(DesUtil.encode(jsonObject.getString("phone"), secretKey));
            //用户角色信息和权限
            List<RoleModel> allRoleList = Privilege.roleClient.queryRoleList(null,null).getResult();
            List<String> appCodes = new ArrayList<>();
            if(orgexpand.equals(OrgEnum.安装单位.getKey())){
                if(jsonObject.getString("isWelder").equals("1")){
                    roleNameSet.add(OrgEnum.普通人员.getName());
                }else{
                    roleNameSet.add(OrgEnum.安装单位.getName());
                    String[] codes = OrgEnum.安装单位.getAppCode().split(",");
                    for(String code : codes){
                        appCodes.add(code);
                    }
                    agencyUserModel.setAppCodes(appCodes);

                }
            }else if(orgexpand.equals(OrgEnum.建设单位.getKey())){
                roleNameSet.add(OrgEnum.建设单位.getName());
                String[] codes = OrgEnum.建设单位.getAppCode().split(",");
                for(String code : codes){
                    appCodes.add(code);
                }
                agencyUserModel.setAppCodes(appCodes);
            }else if(orgexpand.equals(OrgEnum.监察部门.getKey())){
                roleNameSet.add(OrgEnum.监察部门.getName());
                String[] codes = OrgEnum.监察部门.getAppCode().split(",");
                for(String code : codes){
                    appCodes.add(code);
                }
                agencyUserModel.setAppCodes(appCodes);
            }else if(orgexpand.equals(OrgEnum.监检机构.getKey())){
                roleNameSet.add(OrgEnum.监检机构.getName());
                String[] codes = OrgEnum.监检机构.getAppCode().split(",");
                for(String code : codes){
                    appCodes.add(code);
                }
                agencyUserModel.setAppCodes(appCodes);
            }else if(orgexpand.equals(OrgEnum.设计单位.getKey())){
                roleNameSet.add(OrgEnum.设计单位.getName());
                String[] codes = OrgEnum.设计单位.getAppCode().split(",");
                for(String code : codes){
                    appCodes.add(code);
                }
            }


            //给登录人身份配置
            userRoleList = allRoleList.stream().filter(r -> {
                for(String roleName : roleNameSet){
                    if(r.getRoleName().equals(roleName)){
                        return true;
                    }
                }
                return false;
            }).collect(Collectors.toList());
            userRoleList.stream().forEach(r -> {
                if (!roleIds.contains(r.getSequenceNbr())) {
                    roleIds.add(r.getSequenceNbr());
                }
            });
            //登录人应用权限
//            List<String> appCodes = new ArrayList<>();
//            Map<String,String> map = new HashMap();
//            map.put("APPKey",OrgEnum.普通人员.getAppCode());
//            appCodes.add(map.get("APPKey"));
//            agencyUserModel.setAppCodes(appCodes);
            roleSeqsMap.put(companyId,roleIds);
            orgRoles.put(companyId,userRoleList);
            agencyUserModel.setOrgRoleSeqs(roleSeqsMap);
            agencyUserModel.setOrgRoles(orgRoles);
            //创建用户
            agencyUserModel = Privilege.agencyUserClient.create(agencyUserModel).getResult();
            jsonObject.put("amosOrgId",agencyUserModel.getSequenceNbr());
        }

        return orgService.dataHandling(jsonObject,bizOrgType,sequenceNbr);
    }

    @BusinessIdentify
    public List<Map> welderStatistics() {
        Set<String> personCode = new HashSet<>();
        for(Long companyId: materialServiceImpl.getCompanyIds()){
            personCode.add(orgService.getOrgUsrById(String.valueOf(companyId)).getBizOrgCode());
        }
        return welderMapper.welderStatistics(personCode);
    }


//    @BusinessIdentify
    public Page<Map<String, Object>> getWelderByProjectId(String projectId, Integer current, Integer size, String name, String type) {
        String columnKey = "column";
        String valueKey = "value";
        String sequenceNbrKey = "sequenceNbr";
        String statusKey = "status";
        Page<Map<String, Object>> mapPage = new Page<>();
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        Project byId = projectService.getById(projectId);
        //安装单位ID
        Long installationUnitId = byId.getInstallationUnitId();
        List<Map<String, Object>> mapList;
        // 分页参数为空时返回全部
        if (!ObjectUtils.isEmpty(current) || !ObjectUtils.isEmpty(size)) {
            Page<Map<String, Object>> page = new Page<>(current, size);
            if (!ObjectUtils.isEmpty(type) && "all".equals(type)) {
                page = orgUsrService.getWelderByProjectId(page, projectId, installationUnitId, name, null);
            } else {
                page = orgUsrService.getWelderByProjectId(page, projectId, installationUnitId, name, "bound");
            }
            mapPage.setTotal(page.getTotal());
            mapPage.setSize(page.getSize());
            mapPage.setPages(page.getPages());
            mapList = page.getRecords();
        } else {
            mapList = orgUsrService.getWelderListByProjectId(projectId, installationUnitId, name);
        }

        mapList.forEach(item -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put(statusKey, item.getOrDefault(statusKey, 1));
            if (!ObjectUtils.isEmpty(item.get(sequenceNbrKey))) {
                map.put(sequenceNbrKey, item.get(sequenceNbrKey));
                List<Map<String, Object>> message = alertFormValueServiceImpl.getMessageMapByInstanceId(String.valueOf(item.get(sequenceNbrKey)));
                message.forEach(dataItem -> {
                    if (String.valueOf(dataItem.get(columnKey)).equals("image") && !ObjectUtils.isEmpty(dataItem.get(columnKey)) && !ObjectUtils.isEmpty(dataItem.get(valueKey))) {
                        String value1 = String.valueOf(dataItem.get(valueKey));
                        List<Map<String, Object>> imageMap = (List<Map<String, Object>>) JSON.parse(value1);
                        if (!ObjectUtils.isEmpty(imageMap)) {
                            map.put("files", imageMap);
                        }
                    }
                    map.put(String.valueOf(dataItem.get(columnKey)), dataItem.get(valueKey));
                });
                maps.add(map);
            }
        });

        mapPage.setRecords(maps);
        return mapPage;
    }

}
