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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.ugp.api.Enum.CompanyExamineEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.api.entity.SuperviseRule;
import com.yeejoin.amos.boot.module.ugp.api.entity.UnitLicence;
import com.yeejoin.amos.boot.module.ugp.api.mapper.CompanyMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.SuperviseRuleMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.UnitLicenceMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.ICompanyService;
import com.yeejoin.amos.boot.module.ugp.api.dto.CompanyDto;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.*;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import org.ehcache.shadow.org.terracotta.offheapstore.HashingMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;

/**
 * 企业信息表服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service

public class CompanyServiceImpl extends BaseService<CompanyDto, Company, CompanyMapper> implements ICompanyService {

    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    OrgServiceImpl orgService;
    ICompanyService iCompanyService;

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

    @Autowired
    OrgServiceImpl orgServiceImpl;
    @Autowired
    private SuperviseRuleMapper superviseRuleMapper;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    TaskServiceImpl taskService;

    @Autowired
    UnitLicenceServiceImpl unitLicenceService;

    @Autowired
    CompanyServiceImpl companyServiceImpl;

    @Autowired
    UnitLicenceMapper unitLicenceMapper;

    @Autowired
    AmosRequestContext requestContext;
    /**
     * 列表查询 示例
     */
    public List<CompanyDto> queryForCompanyList() {
        return this.queryForList("", false);
    }


    /**
     * 分页查询+筛选
     */
    private static final String ZERO="0";
    private static final String ONE="1";
    private static final String  UNREVIEWED="未审核";
    private static final String  INSANITY="已审核";
    @Override
    @BusinessIdentify
    public IPage<CompanyDto> queryCompanyPage(int current, int size, Company company) {
        IPage<Company> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        IPage<CompanyDto> page1 = new Page<>();
        page1.setSize(size);
        page1.setCurrent(current);
        ArrayList<CompanyDto> list = Lists.newArrayList( );
        String companyType = orgService.getReginParams( ).getBusinessInfo( ).getCompanyType( );
        Long companySequenceNbr = orgService.getReginParams( ).getBusinessInfo( ).getCompanySequenceNbr( );
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>( );
        if (!ValidationUtil.isEmpty(companyType)) {
            if (OrgEnum.监察部门.getKey().equals(companyType)) {
                wrapper.eq(SuperviseRule::getSuperviseDeptId,companySequenceNbr);
                List<SuperviseRule> superviseRules = superviseRuleMapper.selectList(wrapper);
                superviseRules.forEach(s->{
                    LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>( );
                    wrapper1.eq(Company::getRegionCode,s.getAdminRegionCode())
                            .like(!ValidationUtil.isEmpty(company.getName()),Company::getName,company.getName());
                    IPage<Company> companyIPage = companyMapper.selectPage(page, wrapper1);
                    companyIPage.getRecords().forEach(company1 -> {
                        CompanyDto companyDto = new CompanyDto( );
                        BeanUtils.copyProperties(company1,companyDto);
                        companyDto.setType(OrgEnum.监察部门.getName());
                        if (ZERO.equals(company1.getApproved())) {
                          companyDto.setApproved(UNREVIEWED);
                        }else if (ONE.equals(company1.getApproved())) {
                            companyDto.setApproved(INSANITY);
                        }
                        list.add(companyDto);
                    });
                });
              page1.setRecords(list);
                if (!ValidationUtil.isEmpty(list)) {
                    page1.setTotal(list.size());
                }
              return page1;
            }else if (OrgEnum.监检机构.getKey().equals(companyType)){
                wrapper.eq(SuperviseRule::getInspectionUnitId,companySequenceNbr);
                List<SuperviseRule> superviseRules = superviseRuleMapper.selectList(wrapper);
                superviseRules.forEach(s->{
                    LambdaQueryWrapper<Company> wrapper1 = new LambdaQueryWrapper<>( );
                    wrapper1.eq(Company::getRegionCode,s.getAdminRegionCode())
                            .like(!ValidationUtil.isEmpty(company.getName()),Company::getName,company.getName());
                    IPage<Company> companyIPage = companyMapper.selectPage(page, wrapper1);
                    companyIPage.getRecords().forEach(company1 -> {
                        CompanyDto companyDto = new CompanyDto( );
                        BeanUtils.copyProperties(company1,companyDto);
                        companyDto.setType(OrgEnum.监检机构.getName());
                        if (ZERO.equals(company1.getApproved())) {
                            companyDto.setApproved(UNREVIEWED);
                        }else if (ONE.equals(company1.getApproved())) {
                            companyDto.setApproved(INSANITY);
                        }
                        list.add(companyDto);
                    });
                });
                page1.setRecords(list);
                if (!ValidationUtil.isEmpty(list)) {
                    page1.setTotal(list.size());
                }
                return page1;

            }
        }
        if (!ValidationUtil.isEmpty(list)) {
            page1.setTotal(list.size());
        }
        return page1;
    }

    /**
     * 新增部门和负责人
     * @return
     */
    @BusinessIdentify
    public Boolean saveDepartment(JSONObject jsonObject,String sequenceNbr){
        if (ValidationUtil.isEmpty(jsonObject)) {
            return false;
        }
        if (ValidationUtil.isEmpty(sequenceNbr)) {
            //平台添加
            DepartmentModel departmentModel = new DepartmentModel( );
            ReginParams reginParams = orgService.getReginParams();
            departmentModel.setCompanySeq(reginParams.getCompany().getSequenceNbr());
            departmentModel.setDepartmentName(jsonObject.getString("name"));
            departmentModel.setLevel("dept");
            departmentModel.setParentId(1L);
            departmentModel = Privilege.departmentClient.create(departmentModel).getResult();
            //业务添加
            jsonObject.put("amosOrgId",departmentModel.getSequenceNbr());
            jsonObject.put("amosOrgCode",departmentModel.getOrgCode());
        }
        orgService.dataHandling(jsonObject, OrgEnum.部门.getKey(), sequenceNbr);
        return  true;
    }

    public Boolean companyCheck(CompanyDto model, Long sequenceNbr, String bizOrgType) throws Exception{
        Set<String> roleNameSet = new HashSet<>();
        List<RoleModel> userRoleList = new ArrayList<>();
        List<Long> roleIds = new ArrayList<>();
        Map<Long, List<Long>> roleSeqsMap = new HashMap<>();
        Map<Long,List<RoleModel>> orgRoles = new HashMap<>();
        Set<String> appCodeSet = new HashSet<>();
        Company company = companyMapper.selectById(sequenceNbr);
        company.setApproved(model.getApproved());
        if (!ValidationUtil.isEmpty(company)) {
            if ("已审核".equals(company.getApproved())){
//                final CompanyModel companyModel = new CompanyModel();
                //设置用户信息
                String adminName = company.getAdminName();
                String adminLoginName = company.getAdminLoginName();
                String adminPhone = company.getAdminTel();
                String adminPassword = company.getAdminLoginPwd();
                List<AgencyUserModel> agencyUserModels = Privilege.agencyUserClient.list(adminName,adminLoginName).getResult();
                if(agencyUserModels.size() != 1){
                    throw new Exception("匹配到多个用户名，清重新输入用户名！");
                }
                AgencyUserModel agencyUserModel = agencyUserModels.iterator().next();
                agencyUserModel = Privilege.agencyUserClient.queryByUserId(agencyUserModel.getUserId()).getResult();
                //创建平台企业 (tzs已创建)
//                companyModel.setCompanyName(company.getName());
//                companyModel.setCompanyCode(company.getCreditCode());
//                companyModel.setAddress(company.getAddress());
//                companyModel.setParentId(0L);
//                companyModel.setLevel("headquarter");
//                companyModel.setAgencyCode("ugp");
                CompanyModel companyModelFeignClient = Privilege.companyClient.queryByCompanyName(model.getName()).getResult();

                //创建平台用户（tzs已创建，但需要新增ugp的角色）
                //设置用户角色
                List<RoleModel> allRoleList = Privilege.roleClient.queryRoleList(null,null).getResult();
                String[] unitTypeCodes = company.getType().split(",");
                for(String code : unitTypeCodes) {
                    roleNameSet.add(OrgEnum.map.get(code));
                }
//                    if(!ValidationUtil.isEmpty(OrgEnum.codeMap.get(code))){
//                        String[] codes = OrgEnum.codeMap.get(code).split(",");
//                        for(int i = 0;i <codes.length; i++){
//                            if(!appCodeSet.contains(codes[i])){
//                                appCodeSet.add(codes[i]);
//                            }
//                        }
//                    }
//                }
//                Iterator iterator = roleNameSet.iterator();

                //将用户原来的角色与ugp中的角色合并
                roleIds.addAll(agencyUserModel.getOrgRoleSeqs().get(companyModelFeignClient.getSequenceNbr()));
                userRoleList.addAll(agencyUserModel.getOrgRoles().get(companyModelFeignClient.getSequenceNbr()));
                allRoleList.stream().forEach(r -> {
                    if(roleNameSet.contains(r.getRoleName())){
                        if(!userRoleList.contains(r)) {
                            userRoleList.add(r);
                        }
                    }
                });
                userRoleList.stream().forEach(r -> {
                    if(!roleIds.contains(r.getSequenceNbr())) {
                        roleIds.add(r.getSequenceNbr());
                    }
                });
                roleSeqsMap.put(companyModelFeignClient.getSequenceNbr(),roleIds);
                orgRoles.put(companyModelFeignClient.getSequenceNbr(),userRoleList);
                agencyUserModel.setOrgRoleSeqs(roleSeqsMap);
                agencyUserModel.setOrgRoles(orgRoles);

                //tzs已经存在这些信息，不需要重复
//                agencyUserModel.setRealName(adminName);
//                agencyUserModel.setAgencyCode("ugp");
//                agencyUserModel.setLockStatus("UNLOCK");
//                agencyUserModel.setMobile(adminPhone);
//                agencyUserModel.setCreateTime(new Date());
//                agencyUserModel.setUserName(adminLoginName);
//                agencyUserModel.setPassword(DesUtil.encode(adminPassword, secretKey));
//                agencyUserModel.setRePassword(DesUtil.encode(adminPassword, secretKey));
//                List<String> appCodes = new ArrayList<>(appCodeSet);
//                agencyUserModel.setAppCodes(appCodes);
                agencyUserModel = Privilege.agencyUserClient.update(agencyUserModel, agencyUserModel.getUserId()).getResult();
//
                //企业动态表单存储
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(company));
                jsonObject.put("amosOrgId",companyModelFeignClient.getSequenceNbr());
                jsonObject.put("amosOrgCode",companyModelFeignClient.getOrgCode());
                orgServiceImpl.dataHandling(jsonObject,bizOrgType,null);

                //企业管理员人员 动态表单存储
                jsonObject = new JSONObject();
                jsonObject.put("name",adminName);
                jsonObject.put("phone",adminPhone);
                jsonObject.put("amosOrgId",agencyUserModel.getSequenceNbr());
                jsonObject.put("isCheck",companyModelFeignClient.getSequenceNbr());
                orgServiceImpl.dataHandling(jsonObject, OrgEnum.普通人员.getKey(),null);
            }
        }

//        //获取当前注册企业的区域规则 （不需要任务）
//        String regionCode = model.getRegionCode();
//        if(regionCode.contains("#")){
//            String[] regionCodes = regionCode.split("#");
//            regionCode = regionCodes[0];
//        }
//        SuperviseRule superviseRule = superviseRuleService.getOne(new LambdaQueryWrapper<SuperviseRule>().eq(SuperviseRule::getAdminRegionCode,regionCode));
//        List<Long> unitIds = new ArrayList<>();
//        if(!ValidationUtil.isEmpty(superviseRule)) {
//            unitIds.add(superviseRule.getSuperviseDeptId());
//            unitIds.add(superviseRule.getInspectionUnitId());
//        }
//        //新增企业审核任务信息
//        taskService.saveOrUpdateTask(null, true, TaskTypeEnum.企业审核.getKey(), new Date(), model.getSequenceNbr(), TaskTypeEnum.企业审核.getKey(), unitIds,null);
        return this.updateById(company);
    }

    public CompanyDto queryBySeq1(Long sequenceNbr) {
        return companyMapper.queryBySeq1(sequenceNbr);
    }

    public CompanyDto save(CompanyDto model){
        JSONArray jsonArray = model.getLincensePicUrl();
        List<String> adminLincensePic = new ArrayList<>();
        Company companys = new Company();
        if(!ValidationUtil.isEmpty(jsonArray)) {
            for (Object o : jsonArray) {
                JSONObject object = JSON.parseObject(JSON.toJSONString(o));
                String url = object.getString("url");
                adminLincensePic.add(url);
            }
            model.setAdminLincensePic(JSON.toJSONString(adminLincensePic));
        }
        model.setApproved(CompanyExamineEnum.企业审核.getNo());
        model.setRecDate(new Date());


        SuperviseRule superviseRules = superviseRuleService.getOne(new LambdaQueryWrapper<SuperviseRule>().likeRight(SuperviseRule::getAdminRegionCode,model.getRegionCodeC()));
        if (model.getType().equals(OrgEnum.监检机构.getKey())){
            if (model.getRegionCode().equals(model.getRegionCodeD())){
                if (ValidationUtil.isEmpty(superviseRules)){
                    model.setRegionCode(model.getRegionCodeP().concat("#").concat(model.getRegionCode()));
                }else {
                    model.setRegionCode(model.getRegionCodeC().concat("#").concat(model.getRegionCode()));
                }
            } else if (model.getRegionCode().equals(model.getRegionCodeC())) {
                model.setRegionCode(model.getRegionCodeP().concat("#").concat(model.getRegionCode()));
            }else {
                model.setRegionCode(model.getRegionCode());
            }

        }

        //添加许可证号和有效期
        LambdaQueryWrapper<UnitLicence> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UnitLicence::getUnitCode,model.getCreditCode());
        List<UnitLicence> unitLicenceLists = unitLicenceMapper.selectList(wrapper);
        for (UnitLicence unitLicencelist : unitLicenceLists){
            if(!ValidationUtil.isEmpty(unitLicencelist)){
                model.setLicenseNumber(unitLicencelist.getCertNo());
                model.setExpirationDate(unitLicencelist.getExpiryDate());
            }
            break;
        }


        //存入数据
        model = companyServiceImpl.createWithModel(model);
//        //浅拷贝
//        BeanUtils.copyProperties(model,companys);
//        //获取当前注册企业的区域规则
//        String recgionCode = model.getRegionCode().substring(0,6);
//        SuperviseRule superviseRule = superviseRuleService.getOne(new LambdaQueryWrapper<SuperviseRule>().likeRight(SuperviseRule::getAdminRegionCode,recgionCode));
//        List<Long> unitIds = new ArrayList<>();
//        //当区域规则表没有时,更新unitid为区域code
//        if (ValidationUtil.isEmpty(superviseRule)){
//            unitIds.add(Long.valueOf(model.getRegionCode()));
//            unitIds.add(Long.valueOf(model.getRegionCode()));
//        }else {
//            unitIds.add(superviseRule.getSuperviseDeptId());
//            unitIds.add(superviseRule.getInspectionUnitId());
//        }
//
//        //新增企业审核任务信息
//        taskService.saveOrUpdateTask(null, false, TaskTypeEnum.企业审核.getKey(), new Date(), model.getSequenceNbr(), TaskTypeEnum.企业审核.getKey(), unitIds,null);
        return model;
    }

    public JSONObject getUnitLicenseCode(Long unitId) {
        UnitLicence unitLicence = new UnitLicence();
        Company company = companyServiceImpl.getById(unitId);
        String creditCode = company.getCreditCode();
        LambdaQueryWrapper<UnitLicence> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UnitLicence::getUnitCode, creditCode);
        List<UnitLicence> list = unitLicenceService.list(wrapper);
        Iterator<UnitLicence> iterator = list.iterator();
        String licenseCode = "";
        while (iterator.hasNext()) {
            unitLicence = iterator.next();
            if(ValidationUtil.isEmpty(licenseCode)){
                licenseCode = unitLicence.getCertNo();
            } else {
                licenseCode = licenseCode + "," + unitLicence.getCertNo();
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("licenseCode",licenseCode);
        return jsonObject;
    }

    public void syncCompany(Object object) throws Exception {
//        ugpAuthServiceImpl.setRequestContext();
        RequestContext.setAppKey("AMOS_STUDIO");
        RequestContext.setProduct("AMOS_STUDIO_WEB");
        RequestContext.setToken(requestContext.getToken());
        String type = "";
        String jsonString = JSON.toJSONString(object);
        CompanyDto model = JSON.parseObject(jsonString, CompanyDto.class);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        for (Object obj : jsonObject.getJSONArray("unitTypeCodeList")){
            if(!ValidationUtil.isEmpty(OrgEnum.dictionaryCodeMap.get(obj.toString()))) {
                if (!ValidationUtil.isEmpty(type)) {
                    type = type + "," + OrgEnum.dictionaryCodeMap.get(obj.toString());
                } else {
                    type = OrgEnum.dictionaryCodeMap.get(obj.toString());
                }
            }
        }
        Collection<RegionModel> regionModels = Systemctl.regionClient.queryForTree(jsonObject.getString("district")).getResult();
        RegionModel provence = regionModels.iterator().next();
        RegionModel city = provence.getChildren().iterator().next();
        RegionModel district = city.getChildren().iterator().next();
        int regionCodeD = district.getRegionCode();
        int regionCodeC = city.getRegionCode();
        int regionCodeP = provence.getRegionCode();
        model.setRegionCode(String.valueOf(regionCodeD));
        model.setRegionCodeD(String.valueOf(regionCodeD));
        model.setRegionCodeC(String.valueOf(regionCodeC));
        model.setRegionCodeP(String.valueOf(regionCodeP));
        model.setType(type);
        model.setCreditCode(jsonObject.getString("unitCode"));
        model.setContact(jsonObject.getString("adminName"));
        model.setContactPhone(jsonObject.getString("adminTel"));

        try {
            this.save(model);
            //自动审核企业
            model.setApproved("已审核");
            this.companyCheck(model, model.getSequenceNbr(), OrgEnum.公司.getKey());
        } catch (Exception e) {
            //删除企业表数据
            if(!ValidationUtil.isEmpty(this.getById(model.getSequenceNbr()))) {
                this.deleteBySeq(model.getSequenceNbr());
            }

            //先删除动态表单的人员信息
            if(!ValidationUtil.isEmpty(orgService.getInfoByName(model.getAdminName()))) {
                String orgUsrId = String.valueOf(orgService.getInfoByName(model.getAdminName()).getSequenceNbr());
                if (!ValidationUtil.isEmpty(orgService.getOrgUsrById(orgUsrId))) {
                    orgService.delectInfo(orgUsrId);
                }
            }

            //再删除动态表单的企业信息
            if(!ValidationUtil.isEmpty(orgService.getOrgUsrById(String.valueOf(model.getSequenceNbr())))) {
                orgService.delectInfo(String.valueOf(model.getSequenceNbr()));
            }

            throw new Exception("同步失败，已删除同步内容");
        }
    }



}