package com.yami.shop.service.hb.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.hb.HBBaseReq;
import com.yami.shop.bean.dto.hb.HBStoreBaseInfoReq;
import com.yami.shop.bean.dto.hb.StoreRegister;
import com.yami.shop.bean.model.RefundAddr;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.Transport2;
import com.yami.shop.common.util.HttpUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.HBTransport2Mapper;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.service.RefundAddrService;
import com.yami.shop.service.hb.IStoreManagementService;
import com.yami.shop.utils.HBSignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

import static com.yami.shop.common.util.HttpUtil.post;


/**
 * 门店管理服务实现
 *
 * @author fubojin
 * @version 1.0.0
 * @since 2025-09-1
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class StoreManagementService implements IStoreManagementService {
    private final ShopDetailMapper shopDetailMapper;
    private final HBSignUtil hbSignUtil;
    private final HBTransport2Mapper transport2Mapper;
    private final RefundAddrService refundAddrService;

    /**
     * 市民请集合门店修改和新增调用
     */
    private static String smqjhMdUrlAddAndUpdate="http://192.168.1.242:8080/smqjh-pms/api/v1/shopDetail/save";
    /**
     * 市民请集合门店状态修改调用
     */
    private static String smqjhMdUrlUpdateStatus="http://192.168.1.242:8080/smqjh-pms/api/v1/shopDetail/updateStatus";

    /**
     * 获取海博门店基础信息
     */
    public String doGetStation(String outStationNo) {
        HBBaseReq build = new HBBaseReq();
        build.setAppId(hbSignUtil.getAppId());
        HBStoreBaseInfoReq hbStoreBaseInfoReq = HBStoreBaseInfoReq.builder()
                .outStationNo(outStationNo)
                .build();
        build.setBody(JSON.toJSONString(hbStoreBaseInfoReq));
        build.setSign(hbSignUtil.signMd5(build));
        String post = post(hbSignUtil.getHBHost() + "/api/station/get", build);
        log.info("post 请求参数：{}", JSON.toJSONString(build));
        log.info("post 结果：{}", post);
        return post;
    }

    @Override
    public void shippingTemplate() {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deliveryFeeTemplateId", 5);
        build.setBody(JSON.toJSONString(jsonObject));
        build.setSign(hbSignUtil.signMd5(build));
        String post = post(hbSignUtil.getHBHost() + "/api/base/deliveryFee/template", build);
        log.info("post 请求参数：{}", JSON.toJSONString(build));
        log.info("post 结果：{}", post);
    }


    @Override
    @Transactional
    public HBR registerStore(JSONObject registerRequest) {
        try {
            String bodyStr = registerRequest.getString("body");
            log.info("开始门店注册，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr); // 使用Fastjson的解析方法
            String outStationNo = bodyJson.getString("outStationNo");

            String hb = doGetStation(outStationNo);
            JSONObject goodsInfoJson = JSON.parseObject(hb);
            // 2. 逐层解析获取productHostInfoDTOS数组
            JSONObject result = goodsInfoJson.getJSONObject("result");


            // 1. 验证门店编码是否已存在

            // 2. 构建门店实体
            ShopDetail store = new ShopDetail();
            store.setShopName(outStationNo);
            store.setShopName(outStationNo);
            store.setCategory(bodyJson.getString("stationId"));

            // 3. 保存门店信息
            log.info("门店注册信息{}", store);
            shopDetailMapper.insert(store);
            log.info("门店注册成功，门店ID：{}", store.getShopId());

            // 4. 构建响应
            return HBR.success();

        } catch (Exception e) {
            log.error("门店注册失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");
        }
    }

    @Override
    @Transactional
    public HBR updateRegisterStore(JSONObject registerRequest) {
        try {
            String bodyStr = registerRequest.getString("body");
            log.info("开始门店变更，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr);
            String outStationNo = bodyJson.getString("outStationNo");

            String hb = doGetStation(outStationNo);

            JSONObject goodsInfoJson = JSON.parseObject(hb);
            // 2. 逐层解析获取result
            JSONObject result = goodsInfoJson.getJSONObject("result");
            JSONObject resultData = result.getJSONObject("result");

            ShopDetail shopDetailInfo = new ShopDetail();
            shopDetailInfo.setShopName(resultData.getString("stationName"));
            shopDetailInfo.setShopAddress(resultData.getString("address"));
            shopDetailInfo.setProvince(resultData.getString("province"));
            shopDetailInfo.setCity(resultData.getString("city"));
            shopDetailInfo.setArea(resultData.getString("district"));
            shopDetailInfo.setShopOwner(resultData.getString("contacts"));
            shopDetailInfo.setShopLat(resultData.getString("latitude"));
            shopDetailInfo.setShopLng(resultData.getString("longitude"));
            shopDetailInfo.setThirdPartyCode(resultData.getString("stationId"));
            shopDetailInfo.setNotice(resultData.getString("notice"));
            shopDetailInfo.setTel(resultData.getString("phone"));
            //海博门店ID
            shopDetailInfo.setHbStationId(resultData.getString("stationId"));
            //商家门店编码
            shopDetailInfo.setOutStationNo(resultData.getString("outStationNo"));
            //海博门店编码
            shopDetailInfo.setHbStationNo(resultData.getString("outStationNo"));
            //经营状态
            shopDetailInfo.setRunStatus(resultData.getInteger("runStatus"));
            //营业状态
            shopDetailInfo.setShopStatus(resultData.getInteger("businessStatus"));

            shopDetailInfo.setBusinessTime(resultData.getString("businessTime"));
            //配送范围经纬度
            JSONArray coordinates = resultData.getJSONArray("coordinates");
            //营业时间
            JSONArray businessTimes = resultData.getJSONArray("businessTime");
            String businessTime = "";
            for (Object businessTimeInfo : businessTimes) {
                JSONObject coordinateJson = JSON.parseObject(businessTimeInfo.toString());
                String end = coordinateJson.getString("end");
                String start = coordinateJson.getString("start");
                businessTime = ("".equals(businessTime) ? "" : (businessTime + ";")) + start + "-" + end;
            }
            shopDetailInfo.setBusinessTime(businessTime);

            ShopDetail shopDetail = shopDetailMapper.selectByHbStationId(resultData.getString("stationId"));
            if (shopDetail != null) {
                log.info("存在门店不需要新增，直接修改{}", outStationNo);
                shopDetailInfo.setShopId(shopDetail.getShopId());
                shopDetailMapper.updateById(shopDetailInfo);
                log.info("门店变更成功{}", shopDetailInfo);
            }else {
                shopDetailMapper.insert(shopDetailInfo);
                log.info("门店新增成功{}", shopDetailInfo);
                //添加默认配送模板
                Transport2 transport2 = new Transport2();
                //所有数据设置默认值
                transport2.setTransName("默认配送模板");
                transport2.setDistance(100.0);
                transport2.setAmount(1.0);
                transport2.setPiece(5.0);
                transport2.setCreateTime(new Date());
                transport2.setShopId(shopDetailInfo.getShopId());
                transport2Mapper.insert(transport2);
            }


            //添加商家退货地址
            int count = refundAddrService.count(new LambdaQueryWrapper<RefundAddr>()
                    .eq(RefundAddr::getShopId, shopDetailInfo.getShopId())
                    .eq(RefundAddr::getStatus, 1));
            if (count>0){
                log.info("门店存在退货地址无需添加!");
            }else {
                log.info("门店不存在退货地址，添加默认地址!");
                RefundAddr refundAddr = new RefundAddr();
                refundAddr.setShopId(shopDetailInfo.getShopId());
                refundAddr.setReceiverName(shopDetail.getShopOwner());
                refundAddr.setReceiverMobile(shopDetail.getTel());
                refundAddr.setProvince(shopDetail.getProvince());
                refundAddr.setCity(shopDetail.getCity());
                refundAddr.setArea(shopDetail.getArea());
                refundAddr.setAddr(shopDetail.getShopAddress());
                refundAddr.setDefaultAddr(1);
                refundAddr.setStatus(1);
                refundAddr.setCreateTime(new Date());
                refundAddr.setUpdateTime(new Date());
                refundAddrService.save(refundAddr);
            }
//            String post =null;
//            try {
//                 post = HttpUtil.post(smqjhMdUrlAddAndUpdate, registerRequest);
//                JSONObject jsonObject = JSONObject.parseObject(post);
//                Object code = jsonObject.get("code");
//                if (!ObjectUtils.isEmpty(code)&&"00000".equals(code.toString())){
//                    log.info("市民请集合推送门店成功");
//                }else {
//                    log.error("市民请集合推送门店失败返回"+post);
//                }
//            } catch (Exception e) {
//                log.error("市民请集合推送门店失败异常"+e.getMessage());
//                log.error("市民请集合推送门店失败1"+post);
//            }
            return HBR.success();
        } catch (Exception e) {
            log.error("门店变更失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");
        }
    }


    @Override
    public List<ShopDetail> list(ShopDetail shopDetail) {
        List<ShopDetail> list = shopDetailMapper.selectList(new LambdaQueryWrapper<ShopDetail>()
                .eq(shopDetail.getThirdPartyCode() != null, ShopDetail::getThirdPartyCode, shopDetail.getThirdPartyCode())
                .eq(shopDetail.getOutStationNo() != null, ShopDetail::getOutStationNo, shopDetail.getOutStationNo())
                .eq(shopDetail.getCategory() != null, ShopDetail::getCategory, shopDetail.getCategory())
                .eq(shopDetail.getShopAddress() != null, ShopDetail::getShopAddress, shopDetail.getShopAddress())
                .like(shopDetail.getShopName() != null, ShopDetail::getShopName, shopDetail.getShopName()));
        return list;
    }

    @Override
    public ShopDetail detail(Long id) {
        return shopDetailMapper.selectById(id);
    }

    @Override
    public IPage<ShopDetail> page(ShopDetail shopDetail, PageParam<ShopDetail> page) {
        return shopDetailMapper.selectPage(page, new LambdaQueryWrapper<ShopDetail>()
                .like(shopDetail.getShopName() != null, ShopDetail::getShopName, shopDetail.getShopName())
                .like(shopDetail.getOutStationNo() != null, ShopDetail::getOutStationNo, shopDetail.getOutStationNo())
                .like(shopDetail.getCategory() != null, ShopDetail::getCategory, shopDetail.getCategory())
                .like(shopDetail.getShopAddress() != null, ShopDetail::getShopAddress, shopDetail.getShopAddress())
                .like(shopDetail.getThirdPartyCode() != null, ShopDetail::getThirdPartyCode, shopDetail.getThirdPartyCode())
                .like(shopDetail.getShopOwner() != null, ShopDetail::getShopOwner, shopDetail.getShopOwner())
                .like(shopDetail.getMobile() != null, ShopDetail::getMobile, shopDetail.getMobile())
                .like(shopDetail.getTel() != null, ShopDetail::getTel, shopDetail.getTel())
                .eq(shopDetail.getShopLogo() != null, ShopDetail::getShopLogo, shopDetail.getShopLogo())
                .eq(shopDetail.getShopStatus() != null, ShopDetail::getShopStatus, shopDetail.getShopStatus())
                .eq(shopDetail.getHbStationId() != null, ShopDetail::getHbStationId, shopDetail.getHbStationId())
        );
    }

    @Override
    public void updateStatus(JSONObject HBRequest) {
        log.info("海博修改门店状态{}", HBRequest);
        JSONObject body = HBRequest.getJSONObject("body");

        String outStationNo = body.getString("outStationNo");
        String stationId = body.getString("stationId");


        String hb = doGetStation(outStationNo);
        JSONObject goodsInfoJson = JSON.parseObject(hb);
        // 2. 逐层解析获取result
        JSONObject result = goodsInfoJson.getJSONObject("result");
        JSONObject resultData = result.getJSONObject("result");
        Integer businessStatus = resultData.getInteger("businessStatus");
        Integer runStatus = resultData.getInteger("runStatus");
        ShopDetail shopDetail = shopDetailMapper.selectByHbStationId(stationId);
        if (shopDetail != null) {
            shopDetailMapper.hbUpdateStatus(shopDetail.getShopId(), businessStatus, runStatus);
        }else {
            log.error("不存在门店{}", stationId);
        }
//        String post =null;
//        try {
//            post = HttpUtil.post(smqjhMdUrlUpdateStatus, HBRequest);
//            JSONObject jsonObject = JSONObject.parseObject(post);
//            Object code = jsonObject.get("code");
//            if (!ObjectUtils.isEmpty(code)&&"00000".equals(code.toString())){
//                log.info("市民请集合推送门店成功");
//            }else {
//                log.error("市民请集合推送门店失败返回"+post);
//            }
//        } catch (Exception e) {
//            log.error("市民请集合推送门店失败异常"+e.getMessage());
//            log.error("市民请集合推送门店失败1"+post);
//        }

    }
}
