package com.iotechn.unimall.admin;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.openplatform.openapi.sdk.ApiException;
import com.dangdang.openplatform.openapi.sdk.SdkClient;
import com.dangdang.openplatform.openapi.sdk.internal.util.FileItem;
import com.dangdang.openplatform.openapi.sdk.request.order.OrderDetailsGetRequest;
import com.dangdang.openplatform.openapi.sdk.request.order.OrderGoodsSendRequest;
import com.dangdang.openplatform.openapi.sdk.request.order.OrdersContentDecryptRequest;
import com.dangdang.openplatform.openapi.sdk.requestmodel.order.EncryptDTO;
import com.dangdang.openplatform.openapi.sdk.requestmodel.order.OrderDetailsGet;
import com.dangdang.openplatform.openapi.sdk.response.order.OrderDetailsGetResponse;
import com.dangdang.openplatform.openapi.sdk.response.order.OrderGoodsSendResponse;
import com.dangdang.openplatform.openapi.sdk.response.order.OrdersContentDecryptResponse;
import com.dangdang.openplatform.openapi.sdk.responsemodel.order.CryptUserInfo;
import com.dangdang.openplatform.openapi.sdk.responsemodel.order.OrdersContentDecryptDTO;
import com.iotechn.unimall.biz.service.order.OrderBizService;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.data.component.LockComponent;
import com.iotechn.unimall.data.domain.GroupShopDO;
import com.iotechn.unimall.data.domain.OrderDO;
import com.iotechn.unimall.data.domain.SpuDO;
import com.iotechn.unimall.data.domain.shop.ShopAccount;
import com.iotechn.unimall.data.domain.shop.ShopOrder;
import com.iotechn.unimall.data.domain.shop.ShopTran;
import com.iotechn.unimall.data.dto.shop.XmlObject.OrderDetail;
import com.iotechn.unimall.data.dto.shop.XmlObject.SendGood;
import com.iotechn.unimall.data.dto.shop.XmlObject.SendGoodsInfo;
import com.iotechn.unimall.data.enums.GroupShopAutomaticRefundType;
import com.iotechn.unimall.data.enums.OrderStatusType;
import com.iotechn.unimall.data.enums.StatusType;
import com.iotechn.unimall.data.mapper.GroupShopMapper;
import com.iotechn.unimall.data.mapper.OrderMapper;
import com.iotechn.unimall.data.mapper.SpuMapper;
import com.iotechn.unimall.data.mapper.shop.ShopAccountMapper;
import com.iotechn.unimall.data.mapper.shop.ShopOrderMapper;
import com.iotechn.unimall.data.mapper.shop.ShopTranMapper;
import com.iotechn.unimall.data.util.XMLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by rize on 2019/7/21.
 */
@Component
@EnableScheduling
public class AdminCheckQuartz {

    private static final Logger logger = LoggerFactory.getLogger(AdminCheckQuartz.class);
    private static final String ORDER_STATUS_LOCK = "ORDER_STATUS_QUARTZ_LOCK";
    private static final String GROUP_SHOP_START_LOCK = "GROUP_SHOP_START_LOCK";
    private static final String GROUP_SHOP_END_LOCK = "GROUP_SHOP_END_LOCK";
    private static final String GROUP_SHOP_LOCK_LOCK = "GROUP_SHOP_LOCK_LOCK";
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShopOrderMapper shopOrderMapper;
    @Autowired
    private ShopAccountMapper shopAccountMapper;
    @Autowired
    private ShopTranMapper shopTranMapper;
    @Autowired
    private OrderBizService orderBizService;
    @Autowired
    private GroupShopMapper groupShopMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private LockComponent lockComponent;
    @Autowired
    private TransactionTemplate transactionTemplate;


    /**
     * 订单数据定时轮训处理 每小时执行一次
     */
    @Scheduled(cron = "0 0 7-20 * * ? ")
    @Transactional(rollbackFor = Exception.class)
    public void dealOrder() throws Exception {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_status_name","卖家已发货");
        wrapper.eq("dang_order_status","未发货");
        List<ShopOrder> list = shopOrderMapper.selectList(wrapper);
        for (ShopOrder shopOrder: list
             ) {
            ShopAccount shopAccount = shopAccountMapper.selectById(shopOrder.getAccountId());
            dangOrderDeal(shopAccount,shopOrder);
        }
    }
    public void dangOrderDeal(ShopAccount shopAccount, ShopOrder shopOrder) throws Exception {
        /**
         * 获取一下店铺的所有静态参数
         */
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SdkClient sdkClient = new SdkClient(shopAccount.getDangAppKey(),shopAccount.getDangAppSecret(),shopAccount.getDangSession(),shopAccount.getDangVersion());

        OrderDetailsGetRequest ss = new OrderDetailsGetRequest();
        OrderDetailsGet orderDetailsGet = new OrderDetailsGet();
        orderDetailsGet.setO(shopOrder.getDangOrder());
        ss.setOrderDetailsGet(orderDetailsGet);
        OrderDetailsGetResponse resultt = null;
        try {
            resultt = sdkClient.excute(ss);
        } catch (ApiException e) {
            e.printStackTrace();

        }

        /**
         * 从当当获取订单内应当有的所有图书
         */
        OrderDetailsGetRequest odgr = new OrderDetailsGetRequest();
        OrderDetailsGet ogg = new OrderDetailsGet();
        ogg.setO(shopOrder.getDangOrder());
        odgr.setOrderDetailsGet(ogg);
        OrderDetailsGetResponse odgrp = null;
        try {
            odgrp = sdkClient.excute(odgr);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        SdkClient jiemi = new SdkClient(shopAccount.getDangAppKey(),shopAccount.getDangAppSecret(),shopAccount.getDangSession(),shopAccount.getDangVersion());
        OrdersContentDecryptRequest ordersContentDecryptRequest=new OrdersContentDecryptRequest();

        List<EncryptDTO> encryptVOS = new ArrayList<EncryptDTO>();

        EncryptDTO encryptVO1 = new EncryptDTO();
        encryptVO1.setO(resultt.getOrderID().toString());
        encryptVO1.setEncrypt_content(resultt.getEncrypt_content());
        encryptVOS.add(encryptVO1);

        ordersContentDecryptRequest.setO_cryptStr(JSON.toJSONString(encryptVOS));
        OrdersContentDecryptResponse ordersContentDecryptResponse = null;
        try {
            ordersContentDecryptResponse=jiemi.excute(ordersContentDecryptRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        List<OrdersContentDecryptDTO> data = ordersContentDecryptResponse.getData();
        CryptUserInfo cryptUserInfo = data.get(0).getCryptUserInfo();



        OrderDetail o = (OrderDetail) XMLUtil.convertXmlStrToObject(OrderDetail.class, odgrp.getBody());
        SendGoodsInfo sgi = new SendGoodsInfo();
        sgi.setConsigneeAddr(cryptUserInfo.getConsigneeAddr());
        sgi.setConsigneeMobileTel(cryptUserInfo.getConsigneeMobileTel());
        sgi.setConsigneeTel(cryptUserInfo.getConsigneeTel());
        sgi.setConsigneeName(cryptUserInfo.getConsigneeName());
        o.setSendGoodsInfo(sgi);
        List<com.iotechn.unimall.data.dto.shop.XmlObject.ItemInfo> itemInfo = o.getItemsList().getItemInfo();
        /**
         * 将多个图书拼接XML
         */
        String itemsStr = "";
        for (com.iotechn.unimall.data.dto.shop.XmlObject.ItemInfo ii : itemInfo) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("DANG_DANG_ITEM_ID", ii.getItemID());
            hashMap.put("SHU_LIANG", ii.getOrderCount());
            hashMap.put("PRODUCT_ID", ii.getProductItemId());
            itemsStr += SendGood.processTemplate(SendGood.ONE_ITEM, hashMap);
        }


        /**
         * 组成OrderInfo
         */
        Wrapper wrapper = new EntityWrapper();
        wrapper.like("fuzi_name",shopOrder.getShippingCom());
        List<ShopTran> list = shopTranMapper.selectList(wrapper);
        if(list.size() == 0 ){
            throw new Exception("物流公司不存在");
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("DANG_DANG_ORDER", shopOrder.getDangOrder());
        stringObjectHashMap.put("KUAI_DI_GONG_SI", list.get(0).getName());
        stringObjectHashMap.put("KUAI_DI_BIANMA", list.get(0).getCode1());
        stringObjectHashMap.put("KUAI_DI_GONG_SI_DIAN_HUA", list.get(0).getPhone());
        stringObjectHashMap.put("KUAI_DI_DAN_HAO", shopOrder.getShipmentNum());
        stringObjectHashMap.put("SEND_ITEMS", itemsStr);

        String orderListStr = SendGood.processTemplate(SendGood.ONE_ORDER, stringObjectHashMap);
        HashMap<String, Object> tmplHash = new HashMap<>();
        tmplHash.put("SEND_TIME", dateFormat.format(new Date()));
        tmplHash.put("ORDER_LIST", orderListStr);

        String xmlFileStr = SendGood.processTemplate(SendGood.TMPL, tmplHash);
        System.out.println(xmlFileStr);
        PrintWriter out = null;
        try {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("sendGoodNotPlat.xml"), "GBK")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        out.write(xmlFileStr);
        out.close();
        System.out.println("XML文件创建成功！");


        /**
         * 发货！！
         */
        OrderGoodsSendRequest sendGoodsRequest = new OrderGoodsSendRequest();
        sendGoodsRequest.setSendGoodsFile(new FileItem(new File("sendGoodNotPlat.xml")));
        OrderGoodsSendResponse result = null;
        try {
            result = sdkClient.excute(sendGoodsRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(result.toString());
        if(result.getResult().getOrdersList().get(0).getOrderOperCode() == 0){
            shopOrder.setDangOrderStatus("已发货");
            shopOrderMapper.update(shopOrder,new EntityWrapper<ShopOrder>().eq("order_id",shopOrder.getOrderId()));
        }
    }


}
