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


import cn.hutool.core.bean.BeanUtil;
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.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.common.api.entity.TzsUserPermission;
import com.yeejoin.amos.boot.module.statistics.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.statistics.api.mapper.UserInfoMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.UserPermissionMapper;
import com.yeejoin.amos.boot.module.statistics.api.vo.TzsUserInfoVo;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Administrator
 */
@Service
public class UserBizByTCMServiceImpl {

    /**
     * 检验人员资质类型
     */
    private final String JYRY_TYPE = "permissionData66151";
    /**
     * 检测人员资质类型
     */
    private final String JCRY_TYPE = "permissionData66152";
    /**
     * 工作人员资质类型
     */
    private final String ZYRY_TYPE = "permissionData6552";


    /**
     * 需要转换的附件字段 jsonString化字段
     */
    private final String[] ATTACHMENTS = {"certAttachment", "itemCode", "permissionItem"};
    @Autowired
    private UserInfoMapper tzsUserInfoMapper;
    @Autowired
    private UserPermissionMapper tzsUserPermissionMapper;
    @Autowired
    private DataDictionaryServiceImpl dictionaryService;

    public Map<String, Object> getDetail(Long id) {
        Map<String, Object> maps = new HashMap<>();
        TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectById(id);
        TzsUserInfoVo tzsUserInfoVo = new TzsUserInfoVo();
        BeanUtils.copyProperties(tzsUserInfo, tzsUserInfoVo, "identification", "profile", "post", "permissionItem", "appointDoc");
        if (!ObjectUtils.isEmpty(tzsUserInfo.getPost())) {
            tzsUserInfoVo.setPost(JSON.parseArray(tzsUserInfo.getPost()));
        }
        if (!ObjectUtils.isEmpty(tzsUserInfo.getNewPost())) {
            tzsUserInfoVo.setNewPost(JSON.parseArray(tzsUserInfo.getNewPost()));
        }
        if (!ObjectUtils.isEmpty(tzsUserInfo.getEquipType())) {
            tzsUserInfoVo.setEquipType(JSON.parseArray(tzsUserInfo.getEquipType()));
        }
        tzsUserInfoVo.setIdentification(ObjectUtils.isEmpty(tzsUserInfo.getIdentification()) ? null : JSON.parseArray(tzsUserInfo.getIdentification()));
        tzsUserInfoVo.setProfile(ObjectUtils.isEmpty(tzsUserInfo.getProfile()) ? null : JSON.parseArray(tzsUserInfo.getProfile()));
        tzsUserInfoVo.setAppointDoc(ObjectUtils.isEmpty(tzsUserInfo.getAppointDoc()) ? null : JSON.parseArray(tzsUserInfo.getAppointDoc()));
        tzsUserInfoVo.setOtherAccessories(ObjectUtils.isEmpty(tzsUserInfo.getOtherAccessories()) ? null : JSON.parseArray(tzsUserInfo.getOtherAccessories()));
        String companyType = getUnitType();
        tzsUserInfoVo.setCompanyType(companyType.contains("个人主体") ? "individual" : "no-individual");
        Map<String, Object> userInfoMap = BeanUtil.beanToMap(tzsUserInfoVo);
//        userInfoMap.putAll(this.getPermissionDataJson(tzsUserInfo.getPermissionData()));
        // 填充资质信息
        Map<? extends String, ?> permissions = this.queryForSubFormByUserSeq(String.valueOf(tzsUserInfo.getSequenceNbr()));
        userInfoMap.putAll(permissions);
        maps.put("userInfo", userInfoMap);
        return maps;
    }

    public String getUnitType() {
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            return "";
        }
        return companyModels.get(0).getCompanyType();
    }

    /**
     * 根据人员的seq 组织可供子表单使用的资质信息数据
     *
     * @param userSeq 人员的seq
     * @return result
     */
    public Map<? extends String, ?> queryForSubFormByUserSeq(String userSeq) {
        Map<String, List<JSONObject>> result = new HashMap<>();
        List<JSONObject> JYRYList = new ArrayList<>();
        List<JSONObject> JCRYList = new ArrayList<>();
        List<JSONObject> ZYRYList = new ArrayList<>();

        LambdaQueryWrapper<TzsUserPermission> lambda = new QueryWrapper<TzsUserPermission>().lambda();
        lambda.eq(TzsUserPermission::getUserSeq, userSeq);
        List<TzsUserPermission> permissionList = tzsUserPermissionMapper.selectList(lambda);

        for (TzsUserPermission permission : permissionList) {
            String permissionPost = permission.getPermissionPost();

            if (JYRY_TYPE.equals(permissionPost)) {
                JYRYList.add(this.convertPermissionToJson(permission));
                continue;
            }
            if (JCRY_TYPE.equals(permissionPost)) {
                JCRYList.add(this.convertPermissionToJson(permission));
                continue;
            }
            if (ZYRY_TYPE.equals(permissionPost)) {
                ZYRYList.add(this.convertPermissionToJson(permission));
            }
        }
        result.putIfAbsent(JYRY_TYPE, JYRYList);
        result.putIfAbsent(JCRY_TYPE, JCRYList);
        result.putIfAbsent(ZYRY_TYPE, ZYRYList);
        return result;
    }

    /**
     * 实体转化为jsonObject 并转化附件
     *
     * @param permission 入参
     * @return result
     */
    public JSONObject convertPermissionToJson(TzsUserPermission permission) {
        JSONObject json = (JSONObject) JSONObject.toJSON(permission);
        for (String field : ATTACHMENTS) {
            if (json.get(field) != null && json.get(field) instanceof String) {
                json.put(field, JSON.parse(json.get(field).toString()));
            }
        }
        // 作业项目【jobItem】 字段特殊处理
        JSONArray jobItem = JSON.parseArray(String.valueOf(json.get("jobItem")));
        json.put("jobItem", jobItem);

        // 处理检验、检测资质级别、项目字典code->名称
        if (JYRY_TYPE.equals(permission.getPermissionPost()) || JCRY_TYPE.equals(permission.getPermissionPost())) {
            List<DictionarieValueModel> dataDictionaryList = Systemctl.dictionarieClient.dictValues("RYJB_JYJC").getResult();
            String permissionLevel = String.valueOf(json.get("permissionLevel"));
            List<DictionarieValueModel> itemDictionaryList = Systemctl.dictionarieClient.dictValues("ZZXM_" + permissionLevel).getResult();
            if (!ValidationUtil.isEmpty(dataDictionaryList)) {
                dataDictionaryList.forEach(item -> {
                    if (item.getDictDataKey().equals(permissionLevel)) {
                        json.put("permissionLevel", item.getDictDataValue());
                    }
                });
            }

            JSONArray permissionItem = JSON.parseArray(String.valueOf(json.get("permissionItem")));
            JSONArray permissionItemName = new JSONArray();
            if (!ValidationUtil.isEmpty(permissionItem)) {
                if (!ValidationUtil.isEmpty(itemDictionaryList)) {
                    for (Object item : permissionItem) {
                        String finalItem = item.toString();
                        item = itemDictionaryList.stream().filter(dict -> dict.getDictDataKey().equals(finalItem)).findFirst().map(DictionarieValueModel::getDictDataValue).orElse(finalItem);
                        permissionItemName.add(item);
                    }
                }
                json.put("permissionItem", permissionItemName);
            }
        }
        return json;
    }
}
