package com.liquidnet.service.adam.service.processor;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.ServletUtils;
import com.liquidnet.service.adam.dto.vo.AdamMemberOrderVo;
import com.liquidnet.service.adam.entity.AdamMemberOrder;
import com.liquidnet.service.adam.mapper.AdamMemberOrderMapper;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DMMemberOrderProcessor extends DataMigrationProcessorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AdamMemberOrderMapper memberOrderMapper;

    public static final String MEMBER_NAME = "摩登天空会员";
    public static final String MEMBER_ID = "1";

    // APPWEPAY|APPALIPAY|WAPWEPAY|WAPALIPAY|JSWEPAY|GIFT_CODE|VIP_CODE|APPLETWEPAY
    public static final Map<String, String> dfMap = new HashMap<>();
    public static final Map<String, String> ptMap = new HashMap<>();
    static {
        dfMap.put("APPWEPAY", "app");
        dfMap.put("APPALIPAY", "app");
        dfMap.put("WAPWEPAY", "wap");
        dfMap.put("WAPALIPAY", "wap");
        dfMap.put("JSWEPAY", "js");
        dfMap.put("APPLETWEPAY", "applet");
        dfMap.put("APPLETALIPAY", "applet");

        ptMap.put("APPWEPAY", "wepay");
        ptMap.put("APPALIPAY", "alipay");
        ptMap.put("WAPWEPAY", "wepay");
        ptMap.put("WAPALIPAY", "alipay");
        ptMap.put("JSWEPAY", "wepay");
        ptMap.put("APPLETWEPAY", "wepay");
        ptMap.put("APPLETALIPAY", "alipay");
    }

    @SneakyThrows
    @Override
    protected void dataProcessing() {
        HttpServletRequest request = ServletUtils.getRequest();
        String flg = StringUtils.defaultIfBlank(request.getParameter(DM_FLG), "");
        if (StringUtils.isNotEmpty(request.getParameter(DM_FLUSH))) {
            log.info("DM.flush.user_member:{}", userMapper.executeForDM("adam_member_order"));

            log.info("DM.flush.AdamUserMemberVo:{}", mongoTemplate.remove(Query.query(Criteria.where("_id").exists(true)), AdamMemberOrder.class.getSimpleName()).getDeletedCount());
        }

        String sqlCount = "select count(1) from user_vip_card_orders where status in (1,5)";
        String field = "order_code,uid,order_sub_type,vip_card_price,price,status,card_number,birthday,pay_type,pay_code,pay_at,created_at,updated_at,client_ip,source,version";
//      1-order_code,2-uid,3-order_sub_type,4-vip_card_price,5-price,6-status,7-card_number,8-birthday,
//      9-pay_type,10-pay_code,11-pay_at,12-created_at,13-updated_at,14-client_ip,15-source,16-version
        String sql = sqlCount.replace("count(1)", field);

        if ("1".equals(flg)) {
            sqlCount += " and uid in ('2026628','544327','1997335','773650','809406')";
            sql += " and uid in ('2026628','544327','1997335','773650','809406')";
        }

        sql += " limit ?,?";

        statement = connection.prepareStatement(sqlCount);
        row = (ResultSetImpl) statement.executeQuery();
        row.first();
        int ct = row.getInt(1), pSize = 1000, num = 0;
        log.info("DM数据迁移总数:{}", ct);


        while (ct > 0) {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, pSize * num);
            statement.setInt(2, pSize);
            row = (ResultSetImpl) statement.executeQuery();
            log.info("DM.execute.limit:[pNo:{},pSize:{}]", pSize * num, pSize);
            while (row.next()) {
                String uid = row.getString(1);

                if (!reUidList.contains(uid)) {
                    AdamMemberOrder memberOrder = new AdamMemberOrder();
                    memberOrder.setOrderNo(row.getString(1));
                    memberOrder.setUid(row.getString(2));
                    memberOrder.setMode(row.getInt(3));
                    memberOrder.setPrice(row.getBigDecimal(4));
                    memberOrder.setPricePaid(row.getBigDecimal(5));
                    memberOrder.setMemberName(MEMBER_NAME);
                    memberOrder.setMemberId(MEMBER_ID);
                    memberOrder.setMemberPriceId(MEMBER_ID);
                    memberOrder.setDays(365);
                    memberOrder.setState(row.getInt(6));
                    memberOrder.setMemberNo(row.getString(7));
                    memberOrder.setBirthday(row.getString(8));
                    String payType = row.getString(9);
                    memberOrder.setDeviceFrom(dfMap.get(payType));
                    memberOrder.setPayType(ptMap.get(payType));
                    memberOrder.setPayNo(row.getString(10));
                    memberOrder.setPaymentAt(row.getLocalDateTime(11));
                    memberOrder.setCreatedAt(row.getLocalDateTime(12));
                    memberOrder.setUpdatedAt(row.getLocalDateTime(13));
                    memberOrder.setClientIp(row.getString(14));
                    memberOrder.setSource(row.getString(15));
                    memberOrder.setVersion(row.getString(16));

                    AdamMemberOrderVo vo = AdamMemberOrderVo.getNew().copy(memberOrder);

                    memberOrderMapper.insert(memberOrder);

                    mongoTemplate.insert(vo, AdamMemberOrderVo.class.getSimpleName());
                }
            }


            num++;
            ct -= pSize;
        }
    }
}
