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

import cn.hutool.core.util.StrUtil;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.common.code.SourceEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.matter.dao.MatterDao;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterDatumQuery;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.sheet.model.SheetMatterEntity;
import com.mortals.xhx.module.sheet.service.SheetMatterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 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 SheetMatterService sheetMatterService;
    @Autowired
    private MatterDatumService matterDatumService;

    @Override
    protected void findAfter(MatterEntity entity, PageInfo pageInfo, Context context, List<MatterEntity> list) throws AppException {
        for (MatterEntity matterEntity : list) {
            matterEntity.setDatumCount(matterEntity.getMatterDatumList().size());
            matterEntity.getMatterDatumList().forEach(matterDatumEntity -> {
                matterDatumEntity.setMatterName(matterEntity.getMatterName());
                matterDatumEntity.setMatterNo(matterEntity.getMatterNo());
                matterDatumEntity.setDeptCode(matterEntity.getDeptCode());
            });

            if (entity.getIsTerminal() == YesNoEnum.YES.getValue()) {
                String searchMatterName = StrUtil.subBetween(entity.getMatterFullName(), "%");
                if(!ObjectUtils.isEmpty(searchMatterName)){
                    //终端访问，标红查询参数
                    String str = "<span style=\"color:red;font-weight:bold\">%s</span>";
                    String replaceStr = StrUtil.replace(matterEntity.getMatterFullName(), searchMatterName, String.format(str, searchMatterName));
                    matterEntity.setMatterFullName(replaceStr);
                }

            }
        }
    }

    @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<MatterEntity> matterEntities = new ArrayList<>();
        List<SheetMatterEntity> sheetMatterEntityList = sheetMatterService.get(sheetMatterIds, context);
        for (SheetMatterEntity sheetMatterEntity : sheetMatterEntityList) {
            MatterEntity matterEntity = updateOrSave(sheetMatterEntity, siteId, context);
            if (!ObjectUtils.isEmpty(matterEntity)) {
                matterEntities.add(matterEntity);
                success++;
            } else {
                fail++;
            }
        }
        if (!ObjectUtils.isEmpty(matterEntities)) {
            this.save(matterEntities, context);
        }
        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 MatterEntity updateOrSave(SheetMatterEntity sheetMatterEntity, Long siteId, Context context) {
        int count = this.count(new MatterQuery().siteId(siteId).matterNo(sheetMatterEntity.getMatterNo()), context);
        if (count == 0) {
            MatterEntity matterEntity = new MatterEntity();
            matterEntity.initAttrValue();
            matterEntity.setSiteId(siteId);
            matterEntity.setDeptCode(sheetMatterEntity.getDeptCode());
            matterEntity.setDeptName(sheetMatterEntity.getDeptName());
            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(SourceEnum.政务网.getValue());
            matterEntity.setCreateUserId(this.getContextUserId(context));
            matterEntity.setCreateTime(new Date());
            return matterEntity;
        }
        return null;
    }

    @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);
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        List<MatterDatumEntity> matterDatumlist = matterDatumService.find(new MatterDatumQuery().matterIdList(Arrays.asList(ids)));
        matterDatumService.removeList(matterDatumlist, context);
        super.removeAfter(ids, context, result);
    }
}