package com.tax.token.service.impl;

import com.alibaba.fastjson.JSON;
import com.tax.token.mapper.SmsRecordMapper;
import com.tax.token.model.*;
import com.tax.token.service.api.SmsRecordLogService;
import com.tax.token.service.api.SmsRecordService;
import com.tax.token.service.api.SmsSampleService;
import com.tax.token.service.api.TkUserService;
import com.tax.token.service.util.SmsUtil;
import com.tax.token.utils.EncryptUtil;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.common.service.AbstractService;
import com.yxcheng.token.utils.DateUtils;
import com.yxcheng.token.utils.MD5Util;
import com.yxcheng.token.utils.MyBeanUtils;
import com.yxcheng.token.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Component
@ComponentScan(basePackages = {"com.tax.token.dao", "com.tax.token.integration"})
public class SmsRecordServiceImpl  extends AbstractService<SmsRecordMapper,SmsRecordExample,SmsRecord> implements SmsRecordService {

    private static final Logger logger = LoggerFactory.getLogger(SmsRecordServiceImpl.class);

    @Autowired
    private SmsRecordLogService smsRecordLogService;
    @Autowired
    private SmsSampleService smsSampleService;
    @Autowired
    private TkUserService tkUserService;


    public JsonResult<String> saveSmsCode(String cellphone, String requestUid, String smsCode, String smsDate,
                                          String smsFrom, String sendCellphone, String zoneCode, String validCode, String userCode, String functionNo, SmsSendReq smsSendReq) {
        JsonResult jsonResult = new JsonResult();
        TaxSmsModel taxSmsModel = null;
        if(StringUtil.isNotEmpty(zoneCode) && StringUtil.isNotEmpty(validCode)) {
            taxSmsModel = new TaxSmsModel(zoneCode, validCode);
        } else {
            taxSmsModel = smsSampleService.parseZoneCode(requestUid, smsCode);
        }
        smsCode = StringUtil.getShortLog(smsCode, 800);

        SmsRecord smsRecord = null;
        if(taxSmsModel.isSuccess()) {
            SmsResFulModel smsResFulModel = SmsUtil.pushSms(requestUid, cellphone, taxSmsModel.getZoneCode(), taxSmsModel.getValidCode(), smsFrom, userCode, smsSendReq);
            if(smsResFulModel.getCode().equals("0")) {
                smsRecord = baseMapper.findSmsRecordByPhoneAndZone(cellphone, taxSmsModel.getZoneCode());
                if(null==smsRecord) {
                    smsRecord = createSmsRecord(cellphone, requestUid, smsCode, smsDate, smsFrom, sendCellphone, taxSmsModel, userCode);
                    insert(smsRecord);
                } else {
                    smsRecord.setTimeFlag(requestUid);
                    smsRecord.setUpdateDate(DateUtils.getDate());
                    smsRecord.setSmsCode(smsCode);
                    smsRecord.setSmsFrom(smsFrom);
                    smsRecord.setSendCellphone(sendCellphone);
                    smsRecord.setZoneCode(taxSmsModel.getZoneCode());
                    smsRecord.setValidCode(taxSmsModel.getValidCode());
                    if(StringUtil.isNotEmpty(smsDate)) {
                        smsRecord.setSmsDate(DateUtils.str2Date(smsDate, DateUtils.datetimeFormat));
                    }
                    updateByPrimaryKey(smsRecord);
                }
                jsonResult.setData(transShowModel(userCode, smsResFulModel, functionNo));
            } else {
                smsRecord = createSmsRecord(cellphone, requestUid, smsCode, smsDate, smsFrom, sendCellphone, taxSmsModel, userCode);
                jsonResult.error(smsResFulModel.getCode(), smsResFulModel.getMessage());
            }

        } else {
            jsonResult.errorResponse(ResultEnum.sms_parse_fail);
            smsRecord = createSmsRecord(cellphone, requestUid, smsCode, smsDate, smsFrom, sendCellphone, taxSmsModel, userCode);
        }
        SmsRecordLog smsLog = new SmsRecordLog();
        try {
            MyBeanUtils.copyBean2Bean(smsLog, smsRecord);
            smsLog.setId(null);
            smsLog.setLogDate(DateUtils.getDate());
            smsRecordLogService.insert(smsLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.error(requestUid + " saveSmsCode taxno : " + cellphone + " is over!jsonResult is " + jsonResult);
        return jsonResult;
    }

    private SmsRecord createSmsRecord(String cellphone, String requestUid, String smsCode, String smsDate, String smsFrom, String sendCellphone, TaxSmsModel taxSmsModel, String userCode) {
        Date curDate = DateUtils.getDate();
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setCellphone(cellphone);
        smsRecord.setTimeFlag(requestUid);
        smsRecord.setCreateDate(curDate);
        smsRecord.setUpdateDate(curDate);
        smsRecord.setSmsCode(smsCode);
        smsRecord.setSmsFrom(smsFrom);
        smsRecord.setSendCellphone(sendCellphone);
        smsRecord.setZoneCode(taxSmsModel.getZoneCode());
        smsRecord.setValidCode(taxSmsModel.getValidCode());
        smsRecord.setUserCode(userCode);
        if(StringUtil.isNotEmpty(smsDate)) {
            smsRecord.setSmsDate(DateUtils.str2Date(smsDate, DateUtils.datetimeFormat));
        }
        return smsRecord;
    }

    private Object transShowModel(String userCode, SmsResFulModel smsResFulModel, String functionNo) {
        Object dataObj = null;
        SmsResShowModel showModel = new SmsResShowModel();
        showModel.setProxyIp(smsResFulModel.getProxyip());
        showModel.setTaxno(smsResFulModel.getTaxno());
        showModel.setCookie(smsResFulModel.getToken());
        showModel.setSession(smsResFulModel.getSession());
        showModel.setRequestId(smsResFulModel.getRequestId());
        showModel.setUserGroupId((StringUtil.isNotEmpty(smsResFulModel.getUserName())? MD5Util.MD5Encode(smsResFulModel.getUserName()):""));
        showModel.setUserGroupName(smsResFulModel.getUserName());

        TkUser tkUser = tkUserService.getUserByUserCode(userCode, functionNo);
        if(null!=tkUser.getJsonFlag() && tkUser.getJsonFlag().equals("1")) {
            if(null!=tkUser.getShowFlag() && tkUser.getShowFlag().equals("1")) {
                dataObj = EncryptUtil.encryptAesCk(JSON.toJSONString(showModel));
            } else {
                dataObj = JSON.toJSON(showModel);
            }
        } else {
            if (null != tkUser.getShowFlag() && tkUser.getShowFlag().equals("1")) {
                dataObj = EncryptUtil.encryptAesCk(smsResFulModel.getToken());
            } else {
                dataObj = smsResFulModel.getToken();
            }
        }
        return dataObj;
    }
}
