package com.reptileclient.jlifeapp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.dao.hm.HmBookOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmBookTradeOrderMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsItemMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsShopMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsShopOriginMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsSuppliersMapper;
import com.reptileclient.jlifeapp.dto.*;
import com.reptileclient.jlifeapp.entity.hm.HmBookOrder;
import com.reptileclient.jlifeapp.entity.jz.HmRightsItems;
import com.reptileclient.jlifeapp.entity.jz.HmRightsShop;
import com.reptileclient.jlifeapp.entity.jz.HmRightsShopOrigin;
import com.reptileclient.jlifeapp.entity.jz.HmRightsSuppliers;
import com.reptileclient.jlifeapp.service.HmRightService;
import com.reptileclient.jlifeapp.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
@Slf4j
public class HmRightServiceImpl implements HmRightService {

    @Autowired
    private HmRightsShopMapper rightsShopMapper;

    @Autowired
    private HmRightsShopOriginMapper rightsShopOriginMapper;

    @Autowired
    private HmRightsSuppliersMapper suppliersMapper;

    @Autowired
    private HmRightsItemMapper itemMapper;


    @Override
    public String createHmRightOrder(HmCreateRightRequestDTO dto) {
        String createResult = OkHttpUtil.createHmRightOrder(dto);
        log.info("调用盒马创建权益单接口返回结果:" + createResult);
//        {
//            "data":2022031715397120,
//                "message":"ok",
//                "success":true
//        }
        JSONObject object = JSONObject.parseObject(createResult);
        if (object.getBoolean("success")) {
            return object.getLong("data").toString();
        } else {
            throw new RuntimeException(object.getString("message"));
        }
    }

    @Override
    public List<HmrightInfoRespDTO> queryHmRightOrder(String rightOrderNo) {
        String queryResult = OkHttpUtil.getHmRightOrderInfo(rightOrderNo);
        log.info("查询盒马权益单,盒马返回结果:" + queryResult);
        JSONObject result = JSONObject.parseObject(queryResult);
        if (result.getInteger("code") != 200) {
            throw new RuntimeException(result.getString("message"));
        } else {
            return parseResult(result);
        }


    }

    @Override
    @Transactional
    public List<HmrightDetailRespDTO> queryHmRightOrderDetail(String rightOrderNo) {
        String detail = OkHttpUtil.getHmRightDetail(rightOrderNo);
        JSONObject jsonObject = JSONObject.parseObject(detail);
        if (!jsonObject.getBoolean("success")) {
            throw new RuntimeException(jsonObject.getString("message"));
        } else {
            return JSONArray.parseArray(jsonObject.getString("data"), HmrightDetailRespDTO.class);
        }


    }

    @Override
    public void cancelHmRight(String rightOrderNo) {
        HmrightInfoRespDTO respDTO = queryHmRightOrder(rightOrderNo).get(0);
        if(!respDTO.getCancelFlag()){
            throw  new RuntimeException("服务已使用，不可取消！");
        }
        String result =  OkHttpUtil.cancelHmRight(rightOrderNo);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!jsonObject.getBoolean("success")) {
            throw  new RuntimeException(jsonObject.getString("message"));
        }
    }

    @Override
    public void syncRightBaseInfo() {
        syncShop();
        syncItem();
    }

    private void syncItem() {
        List<HmRightsSuppliers> suppliers = suppliersMapper.selectAll();
        List<HmRightsShop> shops = rightsShopMapper.selectAll();
        String regEx_special = "[`~!@#$%^&*()=|{}':;,\\[\\].<>/?！￥…（）—【】‘；：”“’。，、？]";
        Pattern compile = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
        for (HmRightsSuppliers supplier : suppliers) {
            for (HmRightsShop shop : shops) {
                String hmRightServiceItem = OkHttpUtil.getHmRightServiceItem(supplier.getSupplyCode(), shop.getShopCode());
                HmRightResultDTO resultDTO = JSONObject.parseObject(hmRightServiceItem, HmRightResultDTO.class);
                if (resultDTO.getSuccess()) {
                    List<HmRightsItems> hmRightsItems = JSONArray.parseArray(resultDTO.getData(), HmRightsItems.class);
                    if (null != hmRightsItems && !hmRightsItems.isEmpty()) {
                        HmRightsItems items = hmRightsItems.get(0);
                        System.out.println("items = " + items);
                        if (null != items.getItems() && !items.getItems().isEmpty()) {
                            items.getItems().forEach(a -> a.setSkuName(compile.matcher(a.getSkuName())
                                    .replaceAll("").replaceAll("\\u00A0", " ")).setShopCode(items.getShopCode()
                            ).setSupplyCode(supplier.getSupplyCode()));
                            itemMapper.batchInsert(items.getItems());
                        }
                    }

                }

            }
        }
    }

    private void syncShop() {
        String info = OkHttpUtil.getHmRightShop();
        try {
            List<HmRightsShopOrigin> shops = JSONArray.parseArray(info, HmRightsShopOrigin.class);
            shops.forEach(a -> a.setCreateTime(new Date()).setUpdateTime(new Date()));
            rightsShopOriginMapper.cleanALl();
            rightsShopOriginMapper.batchInsert(shops);
            String regex = "((废弃|关闭|禁止)+\\S+\\s*\\S+)|\\S+\\s*\\S+放弃+";
            String city = "(上海|深圳|南京|杭州|苏州|北京)+\\S+\\s*\\S+";
            List<HmRightsShop> aliveShops = shops.stream().filter(a -> !a.getShopName().matches(regex))
                    .filter(a -> a.getShopName().matches(city))
                    .map(a -> new HmRightsShop().setShopName(a.getShopName().replaceAll("（\\S+）", ""))
                            .setShopCode(a.getShopCode()).setCreateTime(a.getCreateTime()).setUpdateTime(a.getUpdateTime()))
                    .collect(Collectors.toList());
            rightsShopMapper.cleanAll();
            rightsShopMapper.batchInsert(aliveShops);
        } catch (Exception e) {
            throw new RuntimeException("获取盒马门店信息失败，失败原因：" + e.getMessage());
        }
    }

    private List<HmrightInfoRespDTO> parseResult(JSONObject result) {
        String data = result.getString("data");
        List<HmrightInfoDTO> hmrightInfoDTOS = JSONArray.parseArray(data, HmrightInfoDTO.class);
        List<HmrightInfoRespDTO> collect = hmrightInfoDTOS.stream().map(a -> {
            HmrightInfoRespDTO respDTO = new HmrightInfoRespDTO();
            BeanUtils.copyProperties(a, respDTO);
            respDTO.setCancelFlag();
            return respDTO;
        }).collect(Collectors.toList());
        
        return collect;
    }
}
