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


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.feign.AmosFeignService;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.QrcodeColorEnum;
import com.yeejoin.amos.boot.module.jxiop.api.dto.CustomizeItems;
import com.yeejoin.amos.boot.module.jxiop.api.dto.PersonBasicDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.RiskBizInfoVo;
import com.yeejoin.amos.boot.module.jxiop.api.dto.RiskDynamicDetailsVo;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonAccount;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonBasic;
import com.yeejoin.amos.boot.module.jxiop.api.feign.AgencyuserFeign;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonAccountFedMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IPersonBasicService;
import com.yeejoin.amos.boot.module.jxiop.api.util.Constants;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 人员基本信息服务实现类
 *
 * @author system_generator
 * @date 2023-04-20
 */
@Service
public class PersonBasicServiceImpl extends BaseService<PersonBasicDto, PersonBasic, PersonBasicMapper> implements IPersonBasicService {

    @Autowired
    PersonBasicMapper personBasicMapper;


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


    @Autowired
    private AmosFeignService amosFeignService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    protected EmqKeeper emqKeeper;


    @Autowired
    private AgencyuserFeign agencyuserFeign;

    /**
     * 人员赋码触发风险模型
     */
    public static final String RYFM_DATA_MQTT_TOPIC = "ryfm/data/analysis";


    /**
     * 人员红黄码恢复为绿码
     */
    public static final String RYFM_GREEN = "ryfm/person/green";



    private String UPDATE="UPDATE";
    private String INSERT="INSERT";
    @Autowired
    PersonAccountFedMapper personAccountFedMapper;


    public RiskBizInfoVo fetchData(PersonBasic personBasic, PersonAccount personAccount, String content) {
        RiskBizInfoVo riskBizInfoVo = new RiskBizInfoVo();
        riskBizInfoVo.setWarningObjectName(personAccount.getProjectName() + personBasic.getPostName() + personAccount.getName());
        riskBizInfoVo.setWarningObjectCode(String.valueOf(personBasic.getSequenceNbr()));
        riskBizInfoVo.setSourceAttribution(personBasic.getProjectOrgCode());
        riskBizInfoVo.setSourceAttributionDesc(personAccount.getProjectName());
        riskBizInfoVo.setWarningObjectType("RYFM");
        List<RiskDynamicDetailsVo> detailsVos = new ArrayList<>();
        RiskDynamicDetailsVo dynamicDetailsVo = new RiskDynamicDetailsVo();
        dynamicDetailsVo.setTabName("预警详情");
        detailsVos.add(dynamicDetailsVo);
        riskBizInfoVo.setDynamicDetails(detailsVos);
        CustomizeItems customizeItems = new CustomizeItems();
        customizeItems.setWarningContent(content);
        riskBizInfoVo.setCustomizeItems(customizeItems);
        return riskBizInfoVo;
    }

    public void addRedisPostAndCerInfo() {
        List<DictionarieValueModel> elevatorCategory = null;
        try {
            elevatorCategory = amosFeignService.listDictionaryByDictCode("YGZYJNJDZS");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> collect = elevatorCategory.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataDesc));
        redisUtils.set(Constants.JXIOP_DICT_POST, collect);

        List<DictionarieValueModel> elevator = null;
        try {
            elevator = amosFeignService.listDictionaryByDictCode("岗位资质鉴定证书");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> collect2 = elevator.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataDesc));
        redisUtils.set(Constants.JXIOP_DICT_CERTIFICATES, collect2);
    }

    public Page<Map<String, Object>> getPersonYardByPage(String parentCode,
                                                         Integer current,
                                                         Integer size,
                                                         String date,
                                                         String qrCodeColor,
                                                         String ne,
                                                         BigDecimal score) {
        List<Map<String, Object>> resultList = personBasicMapper.getPersonYardByPage((current - 1) * size, size , parentCode, date, qrCodeColor, ne);
        Integer count = personBasicMapper.getPersonYardByPageCount(parentCode, date, qrCodeColor, ne);

        resultList.forEach(item -> {
            String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
            item.put("name", name);
            item.put("faultInfo", "证书不全或临期");
            item.put("faultLevel", "严重");
            if (!Objects.isNull(score) && count != 0) {
                BigDecimal divide = new BigDecimal(100).subtract(score).divide(BigDecimal.valueOf(count), 10, 2);
                BigDecimal bigDecimal = divide.setScale(getNonZeroDecimalPlaces(divide), RoundingMode.HALF_UP);
                item.put("mark", bigDecimal);
            }
        });
        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setRecords(resultList);
        mapPage.setCurrent(current);
        mapPage.setSize(size);
        mapPage.setTotal(count);
        return mapPage;
    }

    public static int getNonZeroDecimalPlaces(BigDecimal number) {
        String str = number.stripTrailingZeros().toPlainString();
        int index = str.indexOf(".");
        if (index < 0) {
            return 0;
        }
        for (int i = index + 1; i < str.length(); i++) {
            if (str.charAt(i) != '0') {
                return i - index;
            }
        }
        return 0;
    }

    public Map<String, Object> getPersonDetailInfoByObjectId(String objectId) {
        Map<String, Object> resultMap = personBasicMapper.getPersonDetailInfoByObjectId(objectId);
        return resultMap;
    }
}