package com.artfess.device.base.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryField;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.device.base.dao.AppraiseInfoDao;
import com.artfess.device.base.manager.AppraiseDetailsManager;
import com.artfess.device.base.manager.AppraiseInfoManager;
import com.artfess.device.base.manager.DeviceBaseCompanyManager;
import com.artfess.device.base.manager.DeviceBaseContractManager;
import com.artfess.device.base.model.AppraiseDetails;
import com.artfess.device.base.model.AppraiseInfo;
import com.artfess.device.base.model.DeviceBaseCompany;
import com.artfess.device.base.model.DeviceBaseContract;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 绩效考核-考核情况（DEVICE_APPRAISE_INFO） 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author Limuhua
 * @since 2022-08-02
 */
@Service
public class AppraiseInfoManagerImpl extends BaseManagerImpl<AppraiseInfoDao, AppraiseInfo> implements AppraiseInfoManager {

    @Autowired
    private AppraiseDetailsManager detailsManager;

    @Autowired
    private DeviceBaseContractManager contractManager;

    @Autowired
    private DeviceBaseCompanyManager companyManager;

    @Override
    public boolean save(AppraiseInfo appraiseInfo) {
        Assert.notNull(appraiseInfo, "参数不能为空!");
        Assert.notNull(appraiseInfo.getAssessType(), "考核类型不能为空!");
        Assert.notNull(appraiseInfo.getAssessYear(), "考核年度不能为空!");
        Assert.notNull(appraiseInfo.getAssessType(), "考核标题不能为空!");
        Assert.notNull(appraiseInfo.getReference(), "被考核者不能为空!");

        QueryFilter<AppraiseInfo> queryFilter = getCheckFilter(appraiseInfo);
        queryFilter.getQuerys().add(new QueryField("dai.reference_", appraiseInfo.getReference()));
        Integer repeatCheck = query(queryFilter).getRows().size();
        Assert.isTrue(repeatCheck==0, "【"+appraiseInfo.getReference()+"】已经考核过【"+appraiseInfo.getAssessTitle()+"】！");

        return doSave(appraiseInfo, true);
    }

    @Override
    public boolean updateById(AppraiseInfo appraiseInfo) {
        return doSave(appraiseInfo, false);
    }

    private boolean doSave(AppraiseInfo appraiseInfo, boolean insert){
        Assert.isTrue(appraiseInfo.getDetailsList().stream().map(AppraiseDetails::getInfoId).distinct().count() == 1,"detailsList中的infoId必须唯一。");
        if(insert){
            super.save(appraiseInfo);
        }
        List<AppraiseDetails> details = appraiseInfo.getDetailsList();
        BigDecimal resultScore = new BigDecimal(0);
        for (AppraiseDetails d : details) {
            // 新增回填ID
            d.setInfoId(appraiseInfo.getId());
            detailsManager.getResult(d);
            resultScore = resultScore.add(d.getItemResult());
        }
        appraiseInfo.setResult(resultScore);
        boolean result = super.updateById(appraiseInfo);
        detailsManager.saveOrUpdateBatch(appraiseInfo.getDetailsList());
        return result;
    }

    @Override
    public AppraiseInfo getById(Serializable id) {
//        AppraiseInfo result = super.getById(id);
//        result.setDetailsList(detailsManager.list(new QueryWrapper<AppraiseDetails>().eq("info_id_",result.getId())));
        QueryFilter queryFilter = QueryFilter.build();
        List<QueryField> fields = Lists.newArrayList();
        fields.add(new QueryField("dai.ID_", id));
        queryFilter.setQuerys(fields);
        queryFilter.setPageBean(new PageBean(1,1));
        List<AppraiseInfo> result = query(queryFilter).getRows();
        return BeanUtils.isEmpty(result)?null:result.get(0);
    }

    @Override
    public PageList<AppraiseInfo> query(QueryFilter<AppraiseInfo> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        QueryWrapper<AppraiseInfo> queryWrapper = convert2Wrapper(queryFilter, currentModelClass());
        IPage<AppraiseInfo> result = baseMapper.queryPage(convert2IPage(pageBean), queryWrapper);
        List<AppraiseDetails> detailsList = detailsManager.list();
        result.getRecords().forEach(r->{
            List<AppraiseDetails> details = new ArrayList<>();
            detailsList.forEach(dl->{
                if(dl.getInfoId().equals(r.getId())){
                    details.add(dl);
                }
            });
            r.setDetailsList(details);
        });
        return new PageList<>(result);
    }

    @Override
    public boolean closeInfo(String infoId) {
        return update(new UpdateWrapper<AppraiseInfo>().eq("ID_", infoId).set("CLOSE_STATUS_", "1"));
    }

    @Override
    public List<String> getExaminees(AppraiseInfo dto) {
        Assert.notNull(dto, "参数不能为空!");
        Assert.notNull(dto.getAssessType(), "考核类型不能为空!");
        Assert.notNull(dto.getAssessYear(), "考核年度不能为空!");
        Assert.notNull(dto.getAssessType(), "考核标题不能为空!");

        // 如果后续要所有信息的话，result改成JSONArray
        List<String> result = Lists.newArrayList();
        List<String> exclued = Lists.newArrayList();

        QueryFilter<AppraiseInfo> queryFilter = getCheckFilter(dto);
        query(queryFilter).getRows().forEach(d->{
            exclued.add(d.getReference());
        });

        if ("1".equals(dto.getAssessType())){// 单位考核
            companyManager.getBaseMapper().selectList(new QueryWrapper<DeviceBaseCompany>().notIn(BeanUtils.isNotEmpty(exclued),"COMPANY_NAME_", exclued)).forEach(com->{
                result.add(com.getCompanyName());
            });

        } else if ("2".equals(dto.getAssessType())) { //  合同考核
            contractManager.getBaseMapper().selectList(new QueryWrapper<DeviceBaseContract>().notIn(BeanUtils.isNotEmpty(exclued),"CONTRACT_NAME_", exclued)).forEach(con->{
                result.add(con.getContractName());
            });
        }else{
            Assert.isTrue(false, "传入考核类型有误");
        }

        return result;
    }

    private QueryFilter<AppraiseInfo> getCheckFilter(AppraiseInfo dto){
        QueryFilter<AppraiseInfo> queryFilter = QueryFilter.build();
        List<QueryField> querys = Lists.newArrayList();
        querys.add(new QueryField("dab.ASSESS_TITLE_", dto.getAssessTitle()));
        querys.add(new QueryField("dab.ASSESS_TYPE_", dto.getAssessType()));
        querys.add(new QueryField("dab.ASSESS_YEAR_", dto.getAssessYear()));
        queryFilter.setQuerys(querys);
        queryFilter.setPageBean(new PageBean(1, -1));
        return queryFilter;
    }
}
