package com.mortals.xhx.module.matter.service.impl;

import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.MatterSourceEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.common.utils.StringUtils;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import com.mortals.xhx.module.sheet.dao.SheetMatterDao;
import com.mortals.xhx.module.sheet.model.SheetMatterEntity;
import com.mortals.xhx.module.sheet.model.SheetMatterQuery;
import com.mortals.xhx.module.sheet.service.SheetMatterService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.matter.dao.MatterDao;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.service.MatterService;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * MatterService
 * 事项申请材料 service实现
 *
 * @author zxfei
 * @date 2022-09-27
 */
@Service("matterService")
public class MatterServiceImpl extends AbstractCRUDServiceImpl<MatterDao, MatterEntity, Long> implements MatterService {

    private static int RECOMMEND_COUNT = 5;
    @Autowired
    private ParamService paramService;
    @Autowired
    private SheetMatterService sheetMatterService;
    @Autowired
    private MatterDatumService matterDatumService;

    @Override
    protected MatterEntity findBefore(MatterEntity params, PageInfo pageInfo, Context context) throws AppException {
        if (StringUtils.isNotEmpty(params.getMatterName())) {
            params.setMatterName("%".concat(params.getMatterName()).concat("%"));
        }
        return params;
    }

//    @Override
//    protected void updateBefore(MatterEntity entity, Context context) throws AppException {
//        entity.setIsRecommend(null);
//        this.validData(entity, context);
//    }

//    @Override
//    protected void removeBefore(Long[] ids, Context context) throws AppException {
//        List<MatterEntity> queryList = this.get(ids, context);
//        if (CollectionUtils.isNotEmpty(queryList)) {
//            int recommendCount = paramService.getParamIntValue(ParamKey.MATTER_RECOMMEND_COUNT);
//            for (MatterEntity matterEntity : queryList) {
//                if (matterEntity.getIsRecommend() == 1) {
//                    recommendCount--;
//                }
//            }
//            paramService.setValueByKey(ParamKey.MATTER_RECOMMEND_COUNT, String.valueOf(recommendCount));
//        }
//    }

    @Override
    protected void findAfter(MatterEntity entity, PageInfo pageInfo, Context context, List<MatterEntity> list) throws AppException {
        if (CollectionUtils.isNotEmpty(list)) {
            for (MatterEntity matterEntity : list) {
                MatterDatumEntity query = new MatterDatumEntity();
                query.setMatterId(matterEntity.getId());
                int datumCount = matterDatumService.count(query, context);
                matterEntity.setDatumCount(datumCount);
            }
        }
    }

    @Override
    public Rest<String> createMatterbBySheetMatter(Long[] sheetMatterIds, Long siteId, Context context) {
        if (ObjectUtils.isEmpty(sheetMatterIds)) {
            throw new AppException("事项ids is null");
        }
        int success = 0;
        int fail = 0;
        List<SheetMatterEntity> sheetMatterEntityList = sheetMatterService.get(sheetMatterIds, context);
        for (SheetMatterEntity sheetMatterEntity : sheetMatterEntityList) {
            Boolean bool = updateOrSave(sheetMatterEntity, siteId, context);
            if (bool) {
                success++;
            } else {
                fail++;
            }
        }
        String msg = "当前加入事项已存在！";
        if (sheetMatterIds.length == 1) {
            if (success > 0) {
                msg = "加入事项成功！";
            }
        } else if (sheetMatterIds.length > 1) {
            if (success > 0 && fail == 0) {
                msg = String.format("加入事项成功%d条!", success);
            } else if (success > 0 && fail > 0) {
                msg = String.format("加入事项成功%d条，重复加入事项%d条！", success, fail);
            } else if (success == 0 && fail > 0) {
                msg = String.format("重复加入事项%d条！", fail);
            }
        }
        return Rest.ok(msg);
    }

    private Boolean updateOrSave(SheetMatterEntity sheetMatterEntity, Long siteId, Context context) {
        MatterEntity siteMatterEntity = this.selectOne(new MatterQuery().siteId(siteId).tcode(sheetMatterEntity.getTcode()));
        if (ObjectUtils.isEmpty(siteMatterEntity)) {
            MatterEntity matterEntity = new MatterEntity();
            matterEntity.initAttrValue();
            matterEntity.setSiteId(siteId);
            matterEntity.setDeptCode(sheetMatterEntity.getDeptCode());
            matterEntity.setTid(sheetMatterEntity.getTid());
            matterEntity.setTcode(sheetMatterEntity.getTcode());
            matterEntity.setTname(sheetMatterEntity.getTname());
            matterEntity.setMatterName(sheetMatterEntity.getMatterName());
            matterEntity.setEnglishName(sheetMatterEntity.getEnglishName());
            matterEntity.setMatterNo(sheetMatterEntity.getMatterNo());
            matterEntity.setMatterFullName(sheetMatterEntity.getMatterName());
            matterEntity.setSource(MatterSourceEnum.AUTO.getValue());
            matterEntity.setCreateUserId(this.getContextUserId(context));
            matterEntity.setCreateTime(new Date());
            this.save(matterEntity, context);
            return true;
        }
        return false;
    }

    @Override
    public Rest<String> recommend(Long id, Context context) {
        MatterEntity matterEntity = this.get(id, context);
        if (matterEntity == null) {
            throw new AppException("数据已更改,请重试");
        }
        String msg="推荐成功！";
        int recommendCount = this.count(new MatterQuery().siteId(matterEntity.getSiteId()).isRecommend(YesNoEnum.YES.getValue()), null);
        if (matterEntity.getIsRecommend() == YesNoEnum.NO.getValue()) {
            if (recommendCount >= RECOMMEND_COUNT) {
                throw new AppException("超过推荐个数!");
            }
            matterEntity.setIsRecommend(YesNoEnum.YES.getValue());
        } else {
            matterEntity.setIsRecommend(YesNoEnum.NO.getValue());
             msg="取消推荐成功！";
        }
        this.update(matterEntity, context);
        return Rest.ok(msg);
    }
}