package com.yeejoin.amos.fas.business.service.impl;

import com.google.common.base.Joiner;
import com.yeejoin.amos.fas.business.dao.mapper.RiskFactorMapper;
import com.yeejoin.amos.fas.business.dao.mapper.RiskSourceMapper;
import com.yeejoin.amos.fas.business.dao.repository.IFmeaDao;
import com.yeejoin.amos.fas.business.dao.repository.IRiskFactorDao;
import com.yeejoin.amos.fas.business.dao.repository.IRiskLevelDao;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.param.CommonPageInfoParam;
import com.yeejoin.amos.fas.business.service.intfc.IRiskFactorService;
import com.yeejoin.amos.fas.dao.entity.Fmea;
import com.yeejoin.amos.fas.dao.entity.RiskFactor;
import com.yeejoin.amos.fas.exception.YeeException;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("riskFactorService")
public class RiskFactorServiceImpl implements IRiskFactorService {

    @Autowired
    RiskFactorMapper riskFactorMapper;
    @Autowired
    IRiskFactorDao iRiskFactorDao;
    @Autowired
    IFmeaDao iFmeaDao;

    @Autowired
    RiskSourceMapper riskSourceMapper;
    @Autowired
    IRiskLevelDao iRiskLevelDao;
	@Autowired
	private RemoteSecurityService remoteSecurityService;
    @Override
    public Page<HashMap<String, Object>> queryRiskFactorPage(String toke,String product,String appKey,CommonPageInfoParam param) {
        long total = riskFactorMapper.countPageData(param);
        List<HashMap<String, Object>> content = riskFactorMapper.queryRiskFactorPage(param);
        if(!CollectionUtils.isEmpty(content)){
            List<DictionarieValueModel> typeNameList = Systemctl.dictionarieClient.dictValues("INDUSTRY_TYPE").getResult();
            Map<String, String> typeName = typeNameList.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
            Set<String> userIds = new HashSet<>();
            Set<String> deptIds = new HashSet<>();
            for(HashMap<String, Object> map : content)
            {
                map.put("typeName",typeName.get(map.get("type")));
                String userId = String.valueOf(map.get("createBy"));
                String deptId = String.valueOf(map.get("deptId"));
                userIds.add(userId);
                deptIds.add(deptId);

            }
            userIds.remove(null);
            userIds.remove("");
            deptIds.remove(null);
            deptIds.remove("");
            List<AgencyUserModel> users = new ArrayList<>();
            if(!CollectionUtils.isEmpty(userIds)){
                users = remoteSecurityService.listUserByUserIds(toke, product, appKey, Joiner.on(",").join(userIds));
            }
            Map<String, String> userMap = users.stream().collect(Collectors.toMap(AgencyUserModel::getUserId,AgencyUserModel::getRealName));
            List<DepartmentModel> depts = new ArrayList<>();
            if(!CollectionUtils.isEmpty(deptIds)){
                depts = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, Joiner.on(",").join(deptIds));
            }
            Map<String, String > deptMap = depts.stream().collect(Collectors.toMap(e-> e.getSequenceNbr().toString(),DepartmentModel::getDepartmentName));
            content.forEach(e -> {
                e.put("userName",userMap.get(e.get("createBy")));
                e.put("deptName",deptMap.get(e.get("deptId")));
            });
        }
        Page<HashMap<String, Object>> result = new PageImpl<>(content, param, total);
        return result;
    }

    @Override
    public List<RiskFactor> queryRiskFactor() {
        return iRiskFactorDao.findAll();
    }

    @Override
    public void editRiskFactor(HashMap<String, Object> map) {
        RiskFactor param = (RiskFactor) map.get("param");
        String orgCode = map.get("org_code") == null ? "" : map.get("org_code").toString();
        String userId = map.get("user_id") == null ? "0" : map.get("user_id").toString();
        String deptId = map.get("dept_id") == null ? "0" : map.get("dept_id").toString();
        param.setOrgCode(orgCode);
        param.setDeptId(deptId);
        param.setCreateBy(userId);
        param.setCreateDate(new Date());


        iRiskFactorDao.save(param);
    }




    @Override
    public void detRiskFactor(Long[] param) {
        //1.校验
        for (Long id : param) {
            checkBeforeDet(id);
        }
        //2.删除
        iRiskFactorDao.deleteAllByIds(param);


    }

    /**
     * 删除前校验
     *
     * @param id
     */
    private void checkBeforeDet(Long id) {
        List<Fmea> list = iFmeaDao.findByRiskFactorsId(id);
        if (null != list && list.size() > 0) {
            throw new YeeException("FMEA" + list.get(0).getId() + "在使用中，不能删除");
        }
    }

    @Override
    public Long countRepeatData(RiskFactor param) {
        // TODO Auto-generated method stub
        return riskFactorMapper.countRepeatData(param);
    }

}
