package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.StringUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.ShunfengSignUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinTableStatusConst;
import com.liquidnet.service.kylin.dao.*;
import com.liquidnet.service.kylin.dto.param.*;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.IKylinOrderExpress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 演出 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-05
 */
@Service
@Slf4j
public class PerformancesExpressServiceImpl extends ServiceImpl<KylinOrderExpressMapper, KylinOrderExpress> implements IKylinOrderExpress {

    @Value("${liquidnet.shunfeng.custid}")
    private String custid;
    @Value("${liquidnet.shunfeng.jCompany}")
    private String jCompany;
    @Value("${liquidnet.shunfeng.jContact}")
    private String jContact;
    @Value("${liquidnet.shunfeng.jMobile}")
    private String jMobile;
    @Value("${liquidnet.shunfeng.jProvince}")
    private String jProvince;
    @Value("${liquidnet.shunfeng.jCity}")
    private String jCity;
    @Value("${liquidnet.shunfeng.jAddress}")
    private String jAddress;
    @Value("${liquidnet.shunfeng.payMethod}")
    private Integer payMethod;
    @Value("${liquidnet.shunfeng.expressType}")
    private Integer expressType;
    @Value("${liquidnet.shunfeng.depositumInfo}")
    private String depositumInfo;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private ShunfengSignUtils shunfengSignUtils;

    @Autowired
    private KylinPerformancesMapper performancesMapper;

    @Autowired
    private KylinOrderTicketsMapper kylinOrderTicketsMapper;

    @Autowired
    private KylinOrderExpressMapper kylinOrderExpressMapper;

    public List<PerformanceExpressPerformanceListAdminDao> getPerformancesList(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<PerformanceExpressPerformanceListAdminDao> voList = new ArrayList();
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(performanceExpressSearchAdminParam);
            voList = performancesMapper.performanceExpressPerformanceList(map);
        } catch (Exception e) {
        }
        return voList;
    }

    public List<PerformanceExpressPerformanceOrderListAdminDao> getPerformancesOrderList(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<PerformanceExpressPerformanceOrderListAdminDao> voList = new ArrayList();
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(performanceExpressSearchAdminParam);
            voList = kylinOrderTicketsMapper.performanceExpressPerformanceOrderList(map);
        } catch (Exception e) {
        }
        return voList;
    }

    public ResponseDto placeOrder(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        for (String orderTicketsId : ids) {
            KylinOrderTickets orderInfo = kylinOrderTicketsMapper.selectOne(
                    new QueryWrapper<KylinOrderTickets>().eq("order_tickets_id", orderTicketsId)
            );
            HashMap<String, Object> hBody = new HashMap<>();

            hBody.put("custid", custid);
            hBody.put("jCompany", jCompany);
            hBody.put("jContact", jContact);
            // hBody.put("jTel", "010");
            hBody.put("jMobile", jMobile);
            hBody.put("jProvince", jProvince);
            hBody.put("jCity", jCity);
            hBody.put("jAddress", jAddress);

            hBody.put("payMethod", payMethod);// 运费付款方式：0-寄付月结；1-寄付现结；2-收方付；3-第三方付；
            hBody.put("expressType", expressType);// 顺丰特快

            hBody.put("depositumInfo", depositumInfo);

            Integer placeCount = kylinOrderExpressMapper.selectCount(
                    new QueryWrapper<KylinOrderExpress>()
                            .eq("order_tickets_id", orderTicketsId)
            );
            String codeNum = StringUtils.leftPad(String.valueOf(placeCount), 3, "0");
            String OrderExpressCode = "NEW"+orderInfo.getOrderCode().concat(codeNum);
            hBody.put("orderId", OrderExpressCode);

            hBody.put("depositumNo", orderInfo.getNumber());
            hBody.put("dContact", orderInfo.getExpressContacts());
            hBody.put("dMobile", orderInfo.getExpressPhone());
//            hBody.put("dProvince", "北京");
//            hBody.put("dCity", "北京市");
            hBody.put("dAddress", orderInfo.getExpressAddress());

            // 时间戳
            long currentTimeMillis = System.currentTimeMillis();

            // 生成签名并请求
            String result = shunfengSignUtils.generateSignatureAndRequest(currentTimeMillis + "", hBody, "/public/order/v1/placeOrder");
            HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
            System.out.println(result);
            if (hashMap.get("succ").equals("fail")) {
                String msg = (String) hashMap.get("msg");
                return ResponseDto.failure(msg);
            } else {
                HashMap hashMapResult = (HashMap) hashMap.get("result");
                KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                String orderExpressId = IDGenerator.nextSnowId();
                kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS1);
                kylinOrderExpress.setOrderExpressId(orderExpressId);
                kylinOrderExpress.setOrderTicketsId(orderTicketsId);
                kylinOrderExpress.setOrderExpressCode(OrderExpressCode);
                kylinOrderExpress.setMailno((String) hashMapResult.get("mailno"));
                kylinOrderExpress.setExpressType(expressType);
                kylinOrderExpress.setFilterResult(hashMapResult.get("filter_result").toString());
                kylinOrderExpress.setRemark((String) hashMapResult.get("remark"));
                kylinOrderExpress.setOrigincode((String) hashMapResult.get("origincode"));
                kylinOrderExpress.setDestcode((String) hashMapResult.get("destcode"));
                kylinOrderExpress.setPrintIcon((String) hashMapResult.get("printIcon"));
                kylinOrderExpress.setPrintFlag((String) hashMapResult.get("printFlag"));
                kylinOrderExpress.setTwoDimensionCode((String) hashMapResult.get("twoDimensionCode"));
                kylinOrderExpress.setCreatedAt(DateUtil.getNowTime());
                kylinOrderExpressMapper.insert(kylinOrderExpress);
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto cancelOrder(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .ne("express_status", KylinTableStatusConst.ORDER_EXPRESS_STATUS2)
            );
            if (null != orderExpressInfo) {
                HashMap<String, Object> hBody = new HashMap<>();
                hBody.put("orderId", orderExpressInfo.getOrderExpressCode());

                // 时间戳
                long currentTimeMillis = System.currentTimeMillis();

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequest(currentTimeMillis + "", hBody, "/public/order/v1/cancelOrder");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                    kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS2);
                    kylinOrderExpress.setUpdatedAt(DateUtil.getNowTime());
                    kylinOrderExpressMapper.update(
                            kylinOrderExpress
                            , new UpdateWrapper<KylinOrderExpress>().in("order_express_id", orderExpressInfo.getOrderExpressId())
                    );
                }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto getResult(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .ne("express_status", KylinTableStatusConst.ORDER_EXPRESS_STATUS2)
            );
            if (null != orderExpressInfo) {
                KylinOrderTickets orderInfo = kylinOrderTicketsMapper.selectOne(
                        new QueryWrapper<KylinOrderTickets>().eq("order_tickets_id", orderTicketsId)
                );
                Integer placeCount = kylinOrderExpressMapper.selectCount(
                        new QueryWrapper<KylinOrderExpress>()
                                .eq("order_tickets_id", orderTicketsId)
                );
                String codeNum = StringUtils.leftPad(String.valueOf(placeCount), 3, "0");
                String OrderExpressCode = "NEW"+orderInfo.getOrderCode().concat(codeNum);

                HashMap<String, Object> hBody = new HashMap<>();
                hBody.put("orderId", OrderExpressCode);
                hBody.put("searchType", 1); //查询类型：1,正向单查询，传入的orderid为正向定单号，2，退货单查询，传入的orderid为退货原始订单号

                // 时间戳
                long currentTimeMillis = System.currentTimeMillis();

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequest(currentTimeMillis + "", hBody, "/public/order/v1/getResult");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    HashMap hashMapResult = (HashMap) hashMap.get("result");
                    KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                    String orderExpressId = IDGenerator.nextSnowId();
                    kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS1);
                    kylinOrderExpress.setOrderExpressId(orderExpressId);
                    kylinOrderExpress.setOrderTicketsId(orderTicketsId);
                    kylinOrderExpress.setOrderExpressCode(OrderExpressCode);
                    kylinOrderExpress.setMailno((String) hashMapResult.get("mailno"));
                    kylinOrderExpress.setExpressType(expressType);
                    kylinOrderExpress.setFilterResult(hashMapResult.get("filter_result").toString());
                    kylinOrderExpress.setRemark((String) hashMapResult.get("remark"));
                    kylinOrderExpress.setOrigincode((String) hashMapResult.get("origincode"));
                    kylinOrderExpress.setDestcode((String) hashMapResult.get("destcode"));
                    kylinOrderExpress.setPrintIcon((String) hashMapResult.get("printIcon"));
                    kylinOrderExpress.setPrintFlag((String) hashMapResult.get("printFlag"));
                    kylinOrderExpress.setTwoDimensionCode((String) hashMapResult.get("twoDimensionCode"));
                    kylinOrderExpress.setCreatedAt(DateUtil.getNowTime());
                    kylinOrderExpressMapper.insert(kylinOrderExpress);
                }
            }
        }
        return ResponseDto.success();
    }
}
