package com.library.service.Impl;

import com.library.TopUp.model.ResultsModel;
import com.library.config.NameValue;
import com.library.mapper.AutomaticQueueMapper;
import com.library.mapper.CurrencyMapper;
import com.library.model.AutomaticQueueModel;
import com.library.model.OrderLogModel;
import com.library.model.OrderModel;
import com.library.service.AutomaticCodeService;
import com.library.util.Paygo24Utils;
import com.library.util.TransformationTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
@Transactional
public class AutomaticCodeServiceImpl implements AutomaticCodeService {
    @Resource
    private AutomaticQueueMapper automaticQueueMapper;
    @Resource
    private CurrencyMapper currencyMapper;
    private static String PREFIX_ZERO = "0";
    public static String REGULARLY = "^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    private static final String SegmentType_Cellcard = "Cellcard";
    private static final String SegmentType_Metfone = "Metfone";
    private static final String SegmentType_Smart = "Smart";
    private static final String SegmentType_Seatel = "Seatel";

    @Override
    public boolean isChinaPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return false;
        }
        String removePhone = phone;
        if (phone.startsWith(PREFIX_ZERO)) {
            removePhone = phone;

        }
        // 判断是否是中国手机号
        // 是
        return Pattern.matches(REGULARLY, removePhone);
    }

    //开始自动充值
    @Override
    public void automaticForTack() {
        // 得到最早的一条充值记录
        Map<String, Object> map = automaticQueueMapper.selectEarlyOne();
        if (map != null) {
            // 充值业务状态
            boolean success = false;
            //自动处理状态说明
            String desc = "";
            AutomaticQueueModel automaticQueueModel = null;
            String top_up_num = "";

            try {
                automaticQueueModel = (AutomaticQueueModel) TransformationTools.ToObjectOne(AutomaticQueueModel.class, map);
                // 修改状态
                automaticQueueModel.setStatus(1);
                currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(automaticQueueModel, NameValue.Table_automatic_queue, "id", null));
                //获取订单信息
                Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(automaticQueueModel.getOrder_num());
                OrderModel orderModel = (OrderModel) TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
                OrderLogModel orderLogModel = new OrderLogModel();
                orderLogModel.setLog_order_number(orderModel.getOrder_number());
                orderLogModel.setLog_type(5);
                orderLogModel.setTime(new Timestamp(System.currentTimeMillis()));
                orderLogModel.setLog_content("自动充值-准备开始充值");
                //添加订单操作日志
                currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));


                //生成充值的订单编号。每次都会变，以后可能会复查使用到。
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                top_up_num = sdf.format(new Date());

                //去充值
                ResultsModel resultsModel = sentTopup(automaticQueueModel, top_up_num);
                desc = resultsModel.getTip();
                success = resultsModel.isSuccessful();
                top_up_num = resultsModel.getTopUpNum();
            } catch (Exception var11) {
                var11.printStackTrace();
                desc = "System error.";
            }

            this.automaticForTackResult(automaticQueueModel, success, desc, top_up_num);
        }

    }

    private ResultsModel sentTopup(AutomaticQueueModel automaticQueueModel, String top_up_datetime) {
        ResultsModel resultsModel = null;

        try {
//            //充值订单编号
//            String orderNumId = top_up_datetime;

            //通过手机前三位获取到运营商
            String phoneThree = automaticQueueModel.getOrder_phone().substring(0, 3);
            Map<String, Object> map = this.automaticQueueMapper.selectSegment(phoneThree);

            //1.先判断这是哪个公司的充值订单,然后发起充值
//
//            SegmentModel segmentModel = (SegmentModel)TransformationTools.ToObjectOne(SegmentModel.class, map);
//            if (segmentModel.getOperator().equals("Cellcard")) {
//                //Cellcard的手机号，则选择Cellcard公司的api发起充值
//
//                resultsModel = CellcardSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), top_up_datetime, automaticQueueModel.getOrder_money().intValue());
//                resultsModel.setTopUpNum(top_up_datetime);
//            } else if (segmentModel.getOperator().equals("Metfone")) {
//                resultsModel = MetfoneSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), top_up_datetime);
//                resultsModel.setTopUpNum(top_up_datetime);
//            } else if (segmentModel.getOperator().equals("Smart")) {
//                resultsModel = SmartSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), top_up_datetime);
//                resultsModel.setTopUpNum(top_up_datetime);
//            } else if (segmentModel.getOperator().equals("Seatel")) {
//                resultsModel = SeatelSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue());
//
//                //这个不用返回订单num,里面已经做了处理
//
//            } else {
            Paygo24Utils paygo = new Paygo24Utils();
            String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
            resultsModel = new ResultsModel();
            resultsModel.setTip(result);
            if (result.equals("SUCCESS")) {
                resultsModel.setSuccessful(true);
            } else {
                resultsModel.setSuccessful(false);
            }

            resultsModel.setTopUpNum(top_up_datetime);
//            }

            return resultsModel;
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }


    //自动处理结果
    @Override
    public void automaticForTackResult(AutomaticQueueModel early, boolean success, String desc, String top_up_num) {
        Timestamp newTime = new Timestamp(System.currentTimeMillis());
        Map mapOrder;
        OrderModel orderModel;
        OrderLogModel orderLogModel;
        //充值成功
        if (success) {
            try {
                mapOrder = this.automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
                orderModel = (OrderModel)TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
                orderModel.setState(3);
                orderModel.setPaygo_time(newTime);
                orderModel.setPaygo_remark(desc);
                orderModel.setTop_up_num(top_up_num);
                //更新订单表的状态
                this.currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", (List)null));

                orderLogModel = new OrderLogModel();
                orderLogModel.setLog_order_number(early.getOrder_num());
                orderLogModel.setLog_type(3);
                orderLogModel.setTime(newTime);
                orderLogModel.setLog_content("自动充值-充值成功");

                //添加订单操作日志
                this.currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", (List)null));
            } catch (Exception var10) {
                var10.printStackTrace();
            }
        } else {

            //充值失败,转入人工处理
            try {
                mapOrder = this.automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
                orderModel = (OrderModel)TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
                orderModel.setState(4);
                orderModel.setPaygo_remark(desc + "-处理时间：" + newTime);
                orderModel.setTop_up_num(top_up_num);

                //更新订单表的状态
                this.currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", (List)null));
                orderLogModel = new OrderLogModel();
                orderLogModel.setLog_order_number(early.getOrder_num());
                orderLogModel.setLog_type(4);
                orderLogModel.setTime(newTime);
                orderLogModel.setLog_content("充值失败,转入人工处理-" + desc);
                //添加订单日志
                this.currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", (List)null));
            } catch (Exception var9) {
                var9.printStackTrace();
            }
        }

        //移除自动充值队列中
        this.currencyMapper.DeleteDataById(NameValue.Table_automatic_queue, early.getId());
    }

    @Override
    public int artificialToAutomatic(Integer autoId, String phone, BigDecimal money) {
        return 0;
    }
}
