package com.library.service.Impl;

import com.library.TopUp.Statel.SeatelSentUtils;
import com.library.TopUp.cellcard.CellcardSentUtils;
import com.library.TopUp.mefont.MetfoneSentUtils;
import com.library.TopUp.model.ResultsModel;
import com.library.TopUp.smart.SmartSentUtils;
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.model.SegmentModel;
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.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018\11\22 0022.
 */
@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}$";

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

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

    //开始自动充值
    @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 e) {
                e.printStackTrace();
                desc = "System error.";
            }

            // 自动处理结果
            this.automaticForTackResult(automaticQueueModel, success, desc, top_up_num);
        }
    }

    private final static String SegmentType_Cellcard = "Cellcard";
    private final static String SegmentType_Metfone = "Metfone";
    private final static String SegmentType_Smart = "Smart";
    private final static String SegmentType_Seatel = "Seatel";

    private ResultsModel sentTopup(AutomaticQueueModel automaticQueueModel, String top_up_num) {

        ResultsModel resultsModel = null;
        try {
            //充值订单编号
            String orderNumId = top_up_num;

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

            //1.先判断这是哪个公司的充值订单,然后发起充值
            SegmentModel segmentModel = (SegmentModel) TransformationTools.ToObjectOne(SegmentModel.class, map);
            if (segmentModel.getOperator().equals(SegmentType_Cellcard)) {
                //Cellcard的手机号，则选择Cellcard公司的api发起充值
                resultsModel = CellcardSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), orderNumId, automaticQueueModel.getOrder_money().intValue());
                resultsModel.setTopUpNum(orderNumId);
            } else if (segmentModel.getOperator().equals(SegmentType_Metfone)) {
                resultsModel = MetfoneSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), orderNumId);
                resultsModel.setTopUpNum(orderNumId);
            } else if (segmentModel.getOperator().equals(SegmentType_Smart)) {
                resultsModel = SmartSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), orderNumId);
                resultsModel.setTopUpNum(orderNumId);
            } else if (segmentModel.getOperator().equals(SegmentType_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(Paygo24Utils.SUCCESS)) {
                    resultsModel.setSuccessful(true);
                } else {
                    resultsModel.setSuccessful(false);
                }

                resultsModel.setTopUpNum(orderNumId);
            }

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


    //自动处理结果
    @Override
    public void automaticForTackResult(AutomaticQueueModel early, boolean success, String desc, String top_up_num) {
        Timestamp newTime = new Timestamp(System.currentTimeMillis());
        if (success) {//充值成功
            try {
                Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
                OrderModel 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);
                //更新订单表的状态
                currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", null));

                //发送短信通知用户


                //添加订单日志
                OrderLogModel orderLogModel = new OrderLogModel();
                orderLogModel.setLog_order_number(early.getOrder_num());
                orderLogModel.setLog_type(3);
                orderLogModel.setTime(newTime);
                orderLogModel.setLog_content("自动充值-充值成功");
                //添加订单操作日志
                currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {//充值失败,转入人工处理

            try {
                Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
                OrderModel orderModel = (OrderModel) TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
                orderModel.setState(4);
                orderModel.setPaygo_remark(desc + "-处理时间：" + newTime);
                orderModel.setTop_up_num(top_up_num);
                //更新订单表的状态
                currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", null));

                //添加订单日志
                OrderLogModel orderLogModel = new OrderLogModel();
                orderLogModel.setLog_order_number(early.getOrder_num());
                orderLogModel.setLog_type(4);
                orderLogModel.setTime(newTime);
                orderLogModel.setLog_content("充值失败,转入人工处理-" + desc);
                //添加订单操作日志
                currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));

//                early.setStatus(-1);
//                currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(early,NameValue.Table_automatic_queue,"id",null));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

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

    }

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