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.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.feign.privilege.Privilege;
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.apache.lucene.queryparser.flexible.messages.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
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.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
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
    ICompanyService iCompanyService;

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

    @Autowired
    OrgServiceImpl orgServiceImpl;

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


    /**
     * 分页查询+筛选
     */
        public Page<CompanyDto> queryCompanyPage(int current, int size, CompanyDto companyDto) {
        Page<CompanyDto> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        Page<CompanyDto> page1 = queryForPage(page, null, false);

        if (companyDto.getName() != null) {
            List<CompanyDto> collect = page1.getRecords().stream().filter(a -> a.getName().equals(companyDto.getName())).collect(Collectors.toList());
            page1.setRecords(collect);
        }

        return page1;
    }




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

        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));
            }
            userRoleList = allRoleList.stream().filter(r -> r.getRoleName().equals(roleNameSet)).collect(Collectors.toList());
            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));
            Privilege.agencyUserClient.create(agencyUserModel);

            //企业动态表单存储
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(company));
            jsonObject.put("amosOrgId",companyModelFeignClient.getSequenceNbr());
            jsonObject.put("amosOrgCode",companyModelFeignClient.getOrgCode());
            orgServiceImpl.dataHandling(jsonObject,bizOrgType,null);

            //企业管理员人员 动态表单存储
            jsonObject = null;
            jsonObject.put("name",adminName);
            jsonObject.put("phone",adminPhone);
            jsonObject.put("amosOrgId",agencyUserModel.getSequenceNbr());
            orgServiceImpl.dataHandling(jsonObject, OrgEnum.企业管理员.getKey(),null);
        }
        return this.updateById(company);
    }

}