package com.ag.dynamicmodule.common;

import cn.hutool.core.collection.CollectionUtil;
import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.entity.account.SerialConfig;
import com.ag.entity.account.SerialNo;
import com.ag.util.CommonUtil;
import com.ag.util.StrUtil;
import com.ag.util.TimeUtil;
import com.ag.util.UUIDUtil;
import com.wb.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by yangxh on 2019/11/16.
 * 流水号生成，支持3种模式调用
 */
@Service
public class SerialNoService extends BaseService {
    @Autowired
    private DefaultBussniessImpl bizDao;

    /**
     * 提供给wb页面使用
     * @param json
     * @param response
     * @param request
     * @throws IOException
     */
    @Transactional
    public void findSerialNo(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String code = json.getString("serialCode");
        //主工程获取发票号
        if (StrUtil.isEmpty(code) && json.has("mainParams")){
            code = json.getString("mainParams");
        }
        Assert.isTrue(!StrUtil.isEmpty(code), "获取流水号失败，流水code为空！");
        String serialNo = findSerialNo(code, super.getTenancyId(request));
        WebUtil.send(response, serialNo);
    }


    /**
     * 提供给java使用
     */
    @Transactional
    public String findSerialNoForMain(org.json.JSONObject json, HttpServletResponse response, HttpServletRequest request) {
        String code = json.getString("mainParams");
        Assert.isTrue(!StrUtil.isEmpty(code), "获取流水号失败，流水code为空！");
        return findSerialNo(code, null);
    }

    @Transactional
    public synchronized String findSerialNo(String code, String tenancyId){
        Integer num = 1;
        String numStr = "";
        SerialConfig entity = new SerialConfig();
        entity.setCode(code);
        entity.setTenancyId(tenancyId);
        List<SerialConfig> configs = bizDao.findByEntity(entity, SerialConfig.class);
        if (CollectionUtil.isEmpty(configs)){
            throw new RuntimeException("无效的代码流水号【" + code + "】");
        }
        SerialConfig config = configs.get(0);
        if (config.getValidFlag() != 1){
            throw new RuntimeException("代码流水号未启用【" + code + "】");
        }
        SerialNo noSerialNo = new SerialNo();
        noSerialNo.setConfigId(config.getId());
        String sql = bizDao.getSelectByEntity(noSerialNo, false);
        sql += " and DAY >= to_date('"+ TimeUtil.getDate()+"','yyyy-MM-dd HH24:MI:SS')";
        SerialNo dayNum = (SerialNo) bizDao.get(sql, SerialNo.class);
        if (dayNum == null){
            noSerialNo.setId(UUIDUtil.getUUID());
            noSerialNo.setDay(new Date());
            noSerialNo.setCurrentNo(num);
            bizDao.save(noSerialNo);
        } else {
            num = dayNum.getCurrentNo() + 1;
            SerialNo updSerial = new SerialNo();
            updSerial.setId(dayNum.getId());
            updSerial.setCurrentNo(num);
            updSerial.setDay(new Date());
            bizDao.update(updSerial, "ID");
        }
        numStr = String.valueOf(num);
        while(numStr.length() < config.getNumLength()){
            numStr = "0" + numStr;
        }
        String dateFormat = TimeUtil.getDate("yyyyMMdd");
        return StrUtil.join(config.getPrefix(), dateFormat, numStr, config.getPostfix());

    }

    @Transactional
    public void save(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        List<SerialConfig> adds = CommonUtil.getBeanlist(param, "datatable", "create", SerialConfig.class);
        List<SerialConfig> upds = CommonUtil.getBeanlist(param, "datatable", "update", SerialConfig.class);
        List<SerialConfig> dels = CommonUtil.getBeanlist(param, "datatable", "destroy", SerialConfig.class);
        String[] needCols = CommonUtil.getNeedColsByJson(param, null);
        adds.forEach(x->{
            super.setSaveUser(param, x);
            x.setId(UUIDUtil.getUUID());
        });
        upds.forEach(x->super.setUpdateUser(param, x));
        bizDao.saveAll(adds);
        bizDao.updateAll(upds, needCols, "ID");
        bizDao.deleteAll(dels, "ID");
    }
}
