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.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.mapper.CompanyMapper;
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.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
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.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

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

/**
 * 企业信息表服务实现类
 *
 * @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;

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


    /**
     * 分页查询+筛选
     */
    @Override
    public IPage<CompanyDto> queryCompanyPage(int current, int size, Company company) {
        IPage<CompanyDto> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        return companyMapper.queryCompanyPage(page,company);
    }

    /**
     * 新增部门和负责人
     * @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 = this.getById(sequenceNbr);
        company.setApproved(model.getApproved());

        if (company.getApproved().equals("已审核")){
            final CompanyModel companyModel = new CompanyModel();
            AgencyUserModel agencyUserModel = new AgencyUserModel();

            //创建平台企业
            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.create(companyModel).getResult();

        //创建平台用户
            //设置用户角色
            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(!appCodeSet.contains(OrgEnum.codeMap.get(code))){
                    appCodeSet.add(OrgEnum.codeMap.get(code));
                }
            }
            Iterator iterator = roleNameSet.iterator();

            allRoleList.stream().forEach(r -> {
                if(roleNameSet.contains(r.getRoleName())){
                    userRoleList.add(r);
                }
            });

            userRoleList.stream().forEach(r -> {
                roleIds.add(r.getSequenceNbr());
            });
            roleSeqsMap.put(companyModelFeignClient.getSequenceNbr(),roleIds);
            orgRoles.put(companyModelFeignClient.getSequenceNbr(),userRoleList);
            agencyUserModel.setOrgRoleSeqs(roleSeqsMap);
            agencyUserModel.setOrgRoles(orgRoles);
            //设置用户信息
            String adminName = company.getAdminName();
            String adminLoginName = company.getAdminLoginName();
            String adminPhone = company.getAdminTel();
            String adminPassword = company.getAdminLoginPwd();
            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.create(agencyUserModel).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);
        }
        return this.updateById(company);
    }

}