package ink.wgink.module.form.service.docno.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SearchException;
import ink.wgink.module.form.dao.docno.IDocNoDao;
import ink.wgink.module.form.enums.docno.DocNoTypeEnum;
import ink.wgink.module.form.pojo.bos.docno.DocNoBO;
import ink.wgink.module.form.pojo.dtos.docno.DocNoDTO;
import ink.wgink.module.form.pojo.pos.docno.DocNoPO;
import ink.wgink.module.form.pojo.pos.docnolog.DocNoLogPO;
import ink.wgink.module.form.pojo.vos.docno.DocNoVO;
import ink.wgink.module.form.pojo.vos.docnolog.DocNoLogVO;
import ink.wgink.module.form.service.docno.IDocNoService;
import ink.wgink.module.form.service.docnolog.IDocNoLogService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.map.HashMapUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: DocNoServiceImpl
 * @Description: 文号
 * @Author: CodeFactory
 * @Date: 2022-06-24 15:06:48
 * @Version: 3.0
 **/
@Service
public class DocNoServiceImpl extends DefaultBaseService implements IDocNoService {

    @Autowired
    private IDocNoDao docNoDao;
    @Autowired
    private IDocNoLogService docNoLogService;

    @Override
    public void save(DocNoVO docNoVO) {
        saveReturnId(docNoVO);
    }

    @Override
    public void save(String token, DocNoVO docNoVO) {
        saveReturnId(token, docNoVO);
    }

    @Override
    public String saveReturnId(DocNoVO docNoVO) {
        return saveReturnId(null, docNoVO);
    }

    @Override
    public String saveReturnId(String token, DocNoVO docNoVO) {
        String docNoId = UUIDUtil.getUUID();
        Map<String, Object> params = HashMapUtil.beanToMap(docNoVO);
        params.put("docNoId", docNoId);
        if (StringUtils.isBlank(token)) {
            setSaveInfo(params);
        } else {
            setAppSaveInfo(token, params);
        }
        docNoDao.save(params);
        return docNoId;
    }

    @Override
    public void remove(List<String> ids) {
        remove(null, ids);
    }

    @Override
    public void remove(String token, List<String> ids) {
        Map<String, Object> params = getHashMap(2);
        params.put("docNoIds", ids);
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        docNoDao.remove(params);
    }

    @Override
    public void delete(List<String> ids) {
        Map<String, Object> params = getHashMap(2);
        params.put("docNoIds", ids);
        docNoDao.delete(params);
    }

    @Override
    public void update(String docNoId, DocNoVO docNoVO) {
        update(null, docNoId, docNoVO);
    }

    @Override
    public void update(String token, String docNoId, DocNoVO docNoVO) {
        Map<String, Object> params = HashMapUtil.beanToMap(docNoVO);
        params.put("docNoId", docNoId);
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        docNoDao.update(params);
    }

    @Override
    public DocNoDTO get(Map<String, Object> params) {
        return docNoDao.get(params);
    }

    @Override
    public DocNoDTO get(String docNoId) {
        Map<String, Object> params = super.getHashMap(2);
        params.put("docNoId", docNoId);
        return get(params);
    }

    @Override
    public DocNoPO getPO(Map<String, Object> params) {
        return docNoDao.getPO(params);
    }

    @Override
    public DocNoPO getPO(String docNoId) {
        Map<String, Object> params = super.getHashMap(2);
        params.put("docNoId", docNoId);
        return getPO(params);
    }

    @Override
    public List<DocNoDTO> list(Map<String, Object> params) {
        return docNoDao.list(params);
    }

    @Override
    public List<DocNoPO> listPO(Map<String, Object> params) {
        return docNoDao.listPO(params);
    }

    @Override
    public SuccessResultList<List<DocNoDTO>> listPage(ListPage page) {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<DocNoDTO> docNoDTOs = list(page.getParams());
        PageInfo<DocNoDTO> pageInfo = new PageInfo<>(docNoDTOs);
        return new SuccessResultList<>(docNoDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }

    @Override
    public Integer count(Map<String, Object> params) {
        Integer count = docNoDao.count(params);
        return count == null ? 0 : count;
    }

    @Override
    public DocNoBO getLatestNewDocNoBO(String docNoId, String docNoUsedId) {
        DocNoPO docNoPO = getPO(docNoId);
        if (docNoPO == null) {
            throw new SearchException("文号不存在");
        }
        if (StringUtils.equals(DocNoTypeEnum.MANUAL.getValue(), docNoPO.getType())) {
            LOG.debug("文号类型为手动生成");
            return null;
        }
        return getLatestNewDocNoBO(docNoPO, docNoUsedId);
    }

    @Override
    public DocNoBO getLatestNewDocNoBO(DocNoPO docNoPO, String docNoUsedId) {
        int startNu = docNoPO.getStartNu();
        int nuLength = docNoPO.getNuLength();
        // 文号模板
        String template = docNoPO.getTemplate();
        // 获取最新的文号
        DocNoLogPO latestDocNoLogPO = docNoLogService.getLatestPOByDocNoIdAndUsedId(docNoPO.getDocNoId(), docNoUsedId);
        DateTime dateTime = DateTime.now();

        int fullYearIndex = template.indexOf("yyyy");
        int shortYearIndex = template.indexOf("yy");
        int currentDocNoYear = fullYearIndex > -1 ? dateTime.getYear() : shortYearIndex > -1 ? dateTime.getYear() % 100 : 0;
        int monthIndex = template.indexOf("MM");
        int currentDocNoMonth = monthIndex > -1 ? dateTime.getMonthOfYear() : 0;
        int dayIndex = template.indexOf("dd");
        int currentDocNoDay = dayIndex > -1 ? dateTime.getDayOfMonth() : 0;

        DocNoBO docNoBO = new DocNoBO();
        docNoBO.setDocNoYear(currentDocNoYear);
        docNoBO.setDocNoMonth(currentDocNoMonth);
        docNoBO.setDocNoDay(currentDocNoDay);
        int currentDocNoNu;
        // 文号不存在
        if (latestDocNoLogPO == null) {
            currentDocNoNu = startNu;
        } else {
            // 编号是否重置
            boolean isNuReset = false;
            // 文号存在，计算文号
            if (StringUtils.equals(DocNoTypeEnum.YEAR.getValue(), docNoPO.getType())) {
                if (latestDocNoLogPO.getDocNoYear() != currentDocNoYear) {
                    isNuReset = true;
                }
            } else if (StringUtils.equals(DocNoTypeEnum.MONTH.getValue(), docNoPO.getType())) {
                if (latestDocNoLogPO.getDocNoMonth() != currentDocNoDay) {
                    isNuReset = true;
                } else if (latestDocNoLogPO.getDocNoYear() != currentDocNoYear) {
                    isNuReset = true;
                }
            } else if (StringUtils.equals(DocNoTypeEnum.DAY.getValue(), docNoPO.getType())) {
                if (latestDocNoLogPO.getDocNoDay() != currentDocNoMonth) {
                    isNuReset = true;
                } else if (latestDocNoLogPO.getDocNoMonth() != currentDocNoDay) {
                    isNuReset = true;
                } else if (latestDocNoLogPO.getDocNoYear() != currentDocNoYear) {
                    isNuReset = true;
                }
            }
            if (isNuReset) {
                currentDocNoNu = 1;
            } else {
                currentDocNoNu = latestDocNoLogPO.getDocNoNu() + 1;
            }
        }
        docNoBO.setDocNoNu(currentDocNoNu);
        docNoBO.setDocNoFull(docNoPO.getTitle() + generateDocNo(template, dateTime, String.format("%0" + nuLength + "d", currentDocNoNu)));
        return docNoBO;
    }

    @Override
    public synchronized String saveAndReturnLatestDocNo(String docNoId, String docNoUsedId) {
        DocNoBO latestNewDocNoBO = getLatestNewDocNoBO(docNoId, docNoUsedId);
        if (latestNewDocNoBO == null) {
            return null;
        }
        DocNoLogVO docNoLogVO = new DocNoLogVO();
        BeanUtils.copyProperties(latestNewDocNoBO, docNoLogVO);
        docNoLogVO.setDocNoId(docNoId);
        docNoLogVO.setDocNoUsedId(docNoUsedId);
        docNoLogService.save(docNoLogVO);
        return latestNewDocNoBO.getDocNoFull();
    }

    /**
     * 生成文号
     *
     * @param template 模板
     * @param dateTime 时间
     * @param latestNo 最新数字
     * @return
     */
    private String generateDocNo(String template, DateTime dateTime, String latestNo) {
        String docNo = template;
        if (template.indexOf("yyyy") > -1) {
            docNo = docNo.replaceAll("yyyy", String.valueOf(dateTime.getYear()));
        } else if (docNo.indexOf("yy") > -1) {
            docNo = docNo.replaceAll("yy", String.valueOf(dateTime.getYear()).substring(2, 4));
        }
        docNo = docNo.replaceAll("MM", dateTime.getMonthOfYear() < 10 ? ("0" + dateTime.getMonthOfYear()) : String.valueOf(dateTime.getMonthOfYear()));
        docNo = docNo.replaceAll("dd", dateTime.getDayOfMonth() < 10 ? ("0" + dateTime.getDayOfMonth()) : String.valueOf(dateTime.getDayOfMonth()));
        docNo = docNo.replaceAll("nn", latestNo);
        return docNo;
    }

}