package com.hzs.system.config.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EBarcodeStatus;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.system.config.BdBarCode;
import com.hzs.common.domain.system.config.BdBarCodeItems;
import com.hzs.common.domain.system.config.ext.BdBarCodeItemsExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.config.mapper.BdBarCodeItemsMapper;
import com.hzs.system.config.service.IBdBarCodeItemsService;
import com.hzs.system.config.service.IBdBarCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 条码配置明细表 服务实现类
 *
 * @author zhangjing
 * @since 2022-10-18
 */
@Service
public class BdBarCodeItemsServiceImpl extends ServiceImpl<BdBarCodeItemsMapper, BdBarCodeItems> implements IBdBarCodeItemsService {

    @Autowired
    private IBdBarCodeService barCodeService;

    /**
     * @description: 查询条形码列表
     * @author: zhang jing
     * @date: 2022/10/19 10:31
     * @param: [barCodeItems]
     * @return: java.util.List<com.hzs.common.domain.system.config.BdBarCodeItems>
     **/
    @Override
    public List<BdBarCodeItemsExt> queryBarCodeItemsList(BdBarCodeItemsExt barCodeItems) {
        if (barCodeItems.getEndDate() != null) {
            barCodeItems.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, barCodeItems.getEndDate()));
        }
        if (barCodeItems.getEndDatePrint() != null) {
            barCodeItems.setEndDatePrint(DateUtils.afterDate(1, ChronoUnit.DAYS, barCodeItems.getEndDatePrint()));
        }
        return baseMapper.queryBarCodeItemsList(barCodeItems);
    }

    /**
     * @description: 生成条形码
     * @author: zhang jing
     * @date: 2022/10/19 13:43
     * @param: [barCodeItems]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean savBarCode(List<Long> pkBarCodeList, int generateCount) {
        for (Long pkBarCode : pkBarCodeList) {
            BdBarCode bdBarCode = barCodeService.getOneBarCode(pkBarCode);

            BdBarCodeItems barCodeItems = new BdBarCodeItems();
            barCodeItems.setPkCountry(SecurityUtils.getPkCountry());
            barCodeItems.setPkCreator(SecurityUtils.getUserId());
            barCodeItems.setCodeStatus(EBarcodeStatus.GENERATE.getValue());
            barCodeItems.setPkBarCode(bdBarCode.getPkId());
            barCodeItems.setCreationTime(new Date());

            //获取年,月
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            String month = "";
            String year = "";
            if (bdBarCode.getIsYear() == EYesNo.YES.getIntValue()) {
                year = calendar.get(Calendar.YEAR) + "";
            }
            if (StringUtils.isNotNull(bdBarCode.getIsMonth())) {
                month = autoGenericCode(calendar.get(Calendar.MONTH) + 1, 2);
            }
            String base = "";
            if (bdBarCode.getTailNumber() >= 1) {
                base = getBase(bdBarCode.getTailNumber());
            }
            long addend = 0;
            long currentNumber = 0;
            if (StringUtils.isNull(bdBarCode.getCurrentNumber())) {
                bdBarCode.setCurrentNumber(bdBarCode.getEndNumber());
                addend = bdBarCode.getCurrentNumber(); //尾号初始值
                currentNumber = bdBarCode.getCurrentNumber();
            } else {
                addend = bdBarCode.getCurrentNumber() + MagicNumberConstants.ADDEND; //尾号初始值
                currentNumber = bdBarCode.getCurrentNumber() + MagicNumberConstants.ADDEND;
            }


            QueryWrapper<BdBarCodeItems> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_BAR_CODE", bdBarCode.getPkId());
            queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
            List<BdBarCodeItems> bbciList = baseMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(bbciList)) {
                barCodeItems.setBatch(bdBarCode.getBatch() + 1);
                bdBarCode.setBatch(bdBarCode.getBatch() + 1);
            } else {
                barCodeItems.setBatch(bdBarCode.getBatch());
                bdBarCode.setBatch(bdBarCode.getBatch());
            }
            for (int i = 1; i <= generateCount; i++) {
                //例如0000001 + 1 = 0000002
                base = String.format("%0" + base.length() + "d", Long.parseLong(base) + addend);
                String barCode = bdBarCode.getPrefix() + year + month + base;
                barCodeItems.setBarCode(barCode);

                barCodeItems.setCreationTime(new Date());
                baseMapper.insert(barCodeItems);
                currentNumber = currentNumber + MagicNumberConstants.ADDEND;
                addend = MagicNumberConstants.ADDEND;
                if (i == generateCount) {
                    bdBarCode.setCurrentNumber(currentNumber - MagicNumberConstants.ADDEND);
                }
            }
            bdBarCode.setTotalBarCode(bdBarCode.getTotalBarCode() + generateCount);
            barCodeService.updateById(bdBarCode);
        }
        return true;
    }

    /**
     * @description: 获取尾号补位
     * @author: zhang jing
     * @date: 2022/10/19 14:46
     * @param: [tailNumber]
     * @return: java.lang.String
     **/
    public String getBase(Integer tailNumber) {
        StringBuilder base = new StringBuilder();
        for (int i = 0; i < tailNumber; i++) {
            base.append("0");
        }
        return base.toString();
    }

    /**
     * @description: 月份补位
     * @author: zhang jing
     * @date: 2022/10/19 15:24
     * @param: [code, num]
     * @return: java.lang.String
     **/
    private String autoGenericCode(Integer code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度为4
        // d 代表参数为正数型
        result = String.format("%0" + 2 + "d", code);
        return result;
    }

    @Override
    public List<BdBarCodeItemsExt> queryPrintBarCode(List<String> barCodeList, Integer pkCountry) {
        return baseMapper.queryPrintBarCode(barCodeList, pkCountry);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean clearBarCode(List<Integer> barCodeItemsIdList, Integer pkCountry, Long userId) {
        Date nowDate = new Date();
        // 条码解绑
        UpdateWrapper<BdBarCodeItems> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in(SystemFieldConstants.PK_ID, barCodeItemsIdList);
        updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        updateWrapper.set("CODE_STATUS", EBarcodeStatus.PRINT.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        baseMapper.update(null, updateWrapper);
        // 更新条码已使用总数
        barCodeService.updateUsedBarCode(barCodeItemsIdList, -1, userId, pkCountry);

        return true;
    }

}
