package com.foreverwin.mesnac.common.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.foreverwin.mesnac.common.dto.NextNumberDto;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.helper.NextNumberHelper;
import com.foreverwin.mesnac.common.model.NextNumber;
import com.foreverwin.mesnac.common.service.NextNumberCodeService;
import com.foreverwin.mesnac.common.service.NextNumberService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.I18nUtil;
import com.foreverwin.modular.core.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Roc Li
 * @since 2020-09-03
 */
@Controller
@RequestMapping("/nextNumber")
public class NextNumberController {

    @Autowired
    public NextNumberHelper nextNumberHelper;
    @Autowired
    public NextNumberService nextNumberService;
    @Autowired
    public NextNumberCodeService nextNumberCodeService;




    @ResponseBody
    @PostMapping("/save")
    public R save(@RequestBody Map<String, Object> paramMap) {
        try {
            List<String> prefixes = new ArrayList<>();
            List<NextNumber> ruleList = new ArrayList();
            List numberRuleList = (List) paramMap.get("NUMBER_RULE_LIST");
            //-------------------------------------------------------------------------------------------------------------------------------------
            String site = "";
            for (int i = 0; i < numberRuleList.size(); i++) {
                Map<String, Object> item = (Map<String, Object>) numberRuleList.get(i);
                NextNumberDto nextNumberDto = JSON.parseObject(JSON.toJSONString(item), NextNumberDto.class);//numberRulelist.get(i);
                site = nextNumberDto.getSite();
                String numberType = nextNumberDto.getNumberType();
                String handle = HandleEnum.NEXT_NUMBER.getHandle(site, numberType);
                String prefix = nextNumberDto.getPrefix();
                String postfix = nextNumberDto.getPostfix();
                BigDecimal sequenceLength = nextNumberDto.getSequenceLength();
                String sample = nextNumberDto.getSample();
                String repetition = nextNumberDto.getRepetition();
                String remark = nextNumberDto.getRemarks();
                String skipNumber = nextNumberDto.getSkipNumber();
                BigDecimal startSequence = null;
                BigDecimal currentSequence = null;
                //-------------------------------------------------------------------------------------------------------------------------------------
                if (!StrUtil.isBlank(prefix)) prefix = prefix.toUpperCase();
                if (!StrUtil.isBlank(postfix)) postfix = postfix.toUpperCase();
                //-------------------------------------------------------------------------------------------------------------------------------------
                if (StrUtil.isBlank(numberType) || StrUtil.isBlank(prefix) || StrUtil.isBlank(String.valueOf(sequenceLength))) {
                    throw BusinessException.build("common.nextNumber.check.error", i+1);
                }
                if (prefixes.contains(site+"-"+prefix)) {
                    throw BusinessException.build("common.nextNumber.repeat.error", i+1);
                }
                if (nextNumberDto.getStartSequence() != null) {
                    startSequence = nextNumberDto.getStartSequence();
                    if (startSequence.longValue() <= 0)  throw BusinessException.build("common.nextNumber.startSeq.error", i+1);
                }
                /*
                if (numberTypeMap.get("CURRENT_SEQ") != null && !StrUtil.isBlank(StrUtil.toString(numberTypeMap.get("CURRENT_SEQ")))) {
                    currentSequence = new BigDecimal(String.valueOf(numberTypeMap.get("CURRENT_SEQ")));
                    Long maxCurrentSeq = nextNumberCodeService.getMaxCurrentSeq(handle);
                    if (maxCurrentSeq != null && maxCurrentSeq > currentSequence.longValue()) {
                        throw BusinessException.build("请检查第 " + (i+1) + " 行编码规则的当前序列只可以改大，不可以小于" + maxCurrentSeq + "！");
                    } else {
                        nextNumberCodeService.updateCurrentSeqByNextNumber(currentSequence, handle);
                    }
                }*///if
                //-------------------------------------------------------------------------------------------------------------------------------------
                NextNumber numberRule = new NextNumber();
                numberRule.setHandle(handle);
                numberRule.setSite(site);
                numberRule.setNumberType(numberType);
                numberRule.setPrefix(prefix);
                numberRule.setPostfix(postfix);
                numberRule.setSequenceLength(sequenceLength);
                numberRule.setSample(sample);
                numberRule.setRepetition(repetition);
                numberRule.setRemarks(remark);
                numberRule.setStartSequence(startSequence);
                numberRule.setSkipNumber(skipNumber);
                numberRule.setCreatedUserBo(CommonMethods.getUserBo());
                numberRule.setCreatedDateTime(LocalDateTime.now());
                ruleList.add(numberRule);
                //-------------------------------------------------------------------------------------------------------------------------------------
                prefixes.add(site+"-"+prefix);
            }//for
            //-------------------------------------------------------------------------------------------------------------------------------------
            nextNumberService.batchSave(site, ruleList);
            //-------------------------------------------------------------------------------------------------------------------------------------
            return R.ok(I18nUtil.getI18nText("common.nextNumber.save.success"));
        } catch (Exception e) {
            return R.failed("", I18nUtil.getI18nText("common.nextNumber.save.failue")+e.getMessage());
        }
    }

    @ResponseBody
    @GetMapping("/list")
    public R list(String site){
        return R.ok(nextNumberService.selectListBySite(site));
    }

    @ResponseBody
    @GetMapping("/getNextNumber")
    public R getNextNumber(String numberType, int qty){
        return R.ok(nextNumberHelper.getNextNumber(CommonMethods.getSite(), numberType, qty, null));
    }


}