package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.WxCouponPassword;
import com.iformall.enums.EnumCouponPasswordStatus;
import com.iformall.domain.vo.WxCouponPasswordCountInfoVO;
import com.iformall.common.ErrorCode;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxCouponPasswordMapper;
import com.iformall.service.ExcelService;
import com.iformall.service.WxCouponPasswordService;
import com.iformall.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class WxCouponPasswordServiceImpl implements WxCouponPasswordService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxCouponPasswordMapper wxCouponPasswordMapper;

    @Autowired
    ExcelService excelService;


    @Override
    public PageInfo<WxCouponPassword> listAsPage(WxCouponPassword record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxCouponPasswordMapper.findList(record));
    }

    @Override
    public WxCouponPassword getById(Long id) {
        return wxCouponPasswordMapper.selectById(id);
    }

    @Override
    public WxCouponPassword getByObj(WxCouponPassword obj) {
        String errMsg = "兑换码已失效";
        List<WxCouponPassword> pwdList = wxCouponPasswordMapper.findList(obj);
        if (pwdList.size() <= 0) {
            logger.error(ErrorCode.COUPON_PASSWORD_NOT_FOUND.getMessage());
            throw new MallinkException(ErrorCode.COUPON_PASSWORD_NOT_FOUND.getCode(), errMsg);
        }

        WxCouponPassword password = null;
        Integer errCode = EnumCouponPasswordStatus.INIT.getCode();
        for( WxCouponPassword pwd: pwdList) {
            if (pwd.getStatus().equals(EnumCouponPasswordStatus.USED.getCode())) {
                errCode = EnumCouponPasswordStatus.USED.getCode();
                continue;
            }
            if (!pwd.getStatus().equals(EnumCouponPasswordStatus.USED.getCode()) &&
                    !pwd.getStatus().equals(EnumCouponPasswordStatus.CANCEL.getCode())) {
                password = pwd;
            }
        }
        if (password == null) {
            if (errCode.equals(EnumCouponPasswordStatus.USED.getCode())) {
                logger.error(ErrorCode.COUPON_PASSWORD_HAD_USED.getMessage());
                throw new MallinkException(ErrorCode.COUPON_PASSWORD_HAD_USED.getCode(), errMsg);
            } else {
                logger.error(ErrorCode.COUPON_PASSWORD_IS_CANCELED.getMessage());
                throw new MallinkException(ErrorCode.COUPON_PASSWORD_IS_CANCELED.getCode(), errMsg);
            }
        }
        return password;
    }

    @Override
    public void saveOrUpdate(WxCouponPassword record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxCouponPasswordMapper.insert(record);
        } else {
            wxCouponPasswordMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxCouponPasswordMapper.deleteById(id);
    }

    @Override
    public void mkPasswords(String tenantId, Long couponId, Integer inventory) {
        String strAll = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 1.获取 coupon short 1
        int couponShort = 0;
        String couponShortStr = "0";
        WxCouponPassword pwQ = new WxCouponPassword();
        pwQ.setTenantId(tenantId);
        List<WxCouponPassword> pwgList = wxCouponPasswordMapper.findCouponGroupList(pwQ);
        couponShort = pwgList.size();
        couponShortStr = String.valueOf(strAll.charAt(couponShort));
        // 2.随机字符
        Random rand = new Random();
        List<String> pwList = new ArrayList<>();
        while (true) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < 9; j++) {
                int f = (int) (Math.random() * 62);
                sb.append(strAll.charAt(f));
                if (j == 4) {
                    sb.append(couponShortStr);
                }
            }
            String pwd = sb.toString();
            if (!pwList.stream().anyMatch(oPwd->oPwd.equals(pwd))) {
                pwList.add(pwd);
            } else {
                continue;
            }

            if (pwList.size() >= inventory) {
                break;
            }
        }
        // 3. save to db
        final IdWorker idWorker = IdWorker.get();
        Date curDate = new Date();
        List<WxCouponPassword> couponPasswords = new ArrayList<>();
        for (int i=0;i<pwList.size();i++) {
            WxCouponPassword newOne = new WxCouponPassword();
            newOne.setId(idWorker.nextId());
            newOne.setTenantId(tenantId);
            newOne.setCouponId(couponId);
            newOne.setCouponShort(couponShortStr);
            newOne.setPassword(pwList.get(i));
            newOne.setStatus(EnumCouponPasswordStatus.INIT.getCode());
            newOne.setCreateDate(curDate);
            newOne.setUpdateDate(curDate);
            couponPasswords.add(newOne);
        }
        wxCouponPasswordMapper.insertCouponPasswds(couponPasswords);
    }

    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, WxCouponPassword couponPassword) {
        if (couponPassword.getCouponId() != null) {
            wxCouponPasswordMapper.downloadByCouponId(couponPassword.getCouponId());
        }
        List<WxCouponPassword> pwdList = wxCouponPasswordMapper.findAvaPasswordListByCouponId(couponPassword);
        excelService.exportExcel(pwdList, null, "兑换码", WxCouponPassword.class, "卡兑换码.xlsx", response, false);

    }

    @Override
    public PageInfo<WxCouponPasswordCountInfoVO> findCouponList(WxCouponPassword record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxCouponPasswordMapper.findCouponCountInfo(record));
    }

    @Override
    public List<WxCouponPassword> findList(WxCouponPassword wxCouponPassword) {
        return wxCouponPasswordMapper.findList(wxCouponPassword);
    }

    /*
    public static void main(String[] args) {
        WxCouponPasswordServiceImpl ll = new WxCouponPasswordServiceImpl();
        long startTime =  System.currentTimeMillis();
        System.out.println(startTime);
        ll.mkPasswords("456", 12345L, 100);
        long endTime =  System.currentTimeMillis();
        System.out.println(endTime);
        long usedTime = (endTime-startTime)/1000;
        System.out.println("耗时：" + usedTime  + "s");
    }
    */
    
    
}
