package com.jeequan.jeepay.thirdparty.channel.alipay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.jeequan.jeepay.core.entity.MchStore;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.alipaybiz.IAlipayShopService;
import com.jeequan.jeepay.core.model.params.alipay.AlipayIsvParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/*
* 蚂蚁店铺管理接口
*
* @author zx
*
* @date 2023/3/8 15:13
*/
@Slf4j
@Service
public class AlipayShopService implements IAlipayShopService {

    @Override
    public MchStore query(AlipayIsvParams alipayIsvParams, String storeId, String ipRoleId) {
        AntMerchantExpandShopQueryRequest request = new AntMerchantExpandShopQueryRequest();
        AntMerchantExpandShopQueryModel model = new AntMerchantExpandShopQueryModel();

        model.setStoreId(storeId); // 系统门店ID
        model.setIpRoleId(ipRoleId); // 直连开店场景，填写商户pid
        request.setBizModel(model);

        AntMerchantExpandShopQueryResponse response = AlipayKit.getAlipayClientWrapper(alipayIsvParams).getAlipayClient().execute(request);
        if (!response.isSuccess()) {
            throw new BizException(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
        }

        // 转换为商户门店信息
        MchStore mchStore = new MchStore();
        mchStore.setAlipayShopId(response.getShopId());
        mchStore.setStoreName(response.getShopName());
        mchStore.setContactPhone(response.getContactMobile());
        mchStore.addExt("shopCategory", response.getNewShopCategory());
        mchStore.addExt("shopType", response.getShopType());

        AddressInfo businessAddress = response.getBusinessAddress();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(businessAddress.getProvinceCode());
        jsonArray.add(businessAddress.getCityCode());
        jsonArray.add(businessAddress.getDistrictCode());
        mchStore.setAreaCode(jsonArray);
        mchStore.setAddress(businessAddress.getAddress());
        mchStore.setLat(businessAddress.getLatitude());
        mchStore.setLng(businessAddress.getLongitude());

        return mchStore;
    }

    @Override
    public MchStore create(AlipayIsvParams alipayIsvParams, MchStore mchStore, String ipRoleId){
        AntMerchantExpandShopCreateRequest request = new AntMerchantExpandShopCreateRequest();
        AntMerchantExpandShopCreateModel model = new AntMerchantExpandShopCreateModel();

        // 经营地址
        AddressInfo businessAddress = new AddressInfo();
        businessAddress.setProvinceCode(mchStore.getAreaCode().getString(0));
        businessAddress.setCityCode(mchStore.getAreaCode().getString(1));
        businessAddress.setDistrictCode(mchStore.getAreaCode().getString(2));
        businessAddress.setAddress(mchStore.getAddress());
        model.setBusinessAddress(businessAddress);

        if (mchStore.getExt() != null) {
            if (StringUtils.isNotBlank(mchStore.getExt().getString("shopCategory"))) {
                model.setShopCategory(mchStore.getExt().getString("shopCategory").split("_")[1]); // 新版门店类目标准二级类目code
            }
            model.setShopType(mchStore.getExt().getString("shopType")); // 店铺经营类型，01表示直营，02表示加盟
        }

        model.setStoreId(mchStore.getStoreId() + ""); // 外部门店ID
        model.setIpRoleId(ipRoleId);
        model.setShopName(mchStore.getStoreName());
        model.setContactMobile(mchStore.getContactPhone());
        request.setBizModel(model);

        AntMerchantExpandShopCreateResponse response = AlipayKit.getAlipayClientWrapper(alipayIsvParams).getAlipayClient().execute(request);
        log.info("蚂蚁店铺创建响应，storeId={}，response={}", mchStore.getStoreId(), JSONObject.toJSONString(response));
        if (!response.isSuccess()) {
            throw new BizException(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
        }

        MchStore result = new MchStore();
        result.setAlipayShopCreateId(response.getOrderId());

        return result;
    }

    @Override
    public MchStore update(AlipayIsvParams alipayIsvParams, MchStore mchStore){
        AntMerchantExpandShopModifyRequest request = new AntMerchantExpandShopModifyRequest();
        AntMerchantExpandShopModifyModel model = new AntMerchantExpandShopModifyModel();

        model.setShopId(mchStore.getAlipayShopId());

        // 经营地址
        AddressInfo businessAddress = new AddressInfo();
        businessAddress.setProvinceCode(mchStore.getAreaCode().getString(0));
        businessAddress.setCityCode(mchStore.getAreaCode().getString(1));
        businessAddress.setDistrictCode(mchStore.getAreaCode().getString(2));
        businessAddress.setAddress(mchStore.getAddress());
        model.setBusinessAddress(businessAddress);

        if (mchStore.getExt() != null) {
            if (StringUtils.isNotBlank(mchStore.getExt().getString("shopCategory")) && mchStore.getExt().getString("shopCategory").contains("_")) {
                model.setShopCategory(mchStore.getExt().getString("shopCategory").split("_")[1]); // 新版门店类目标准二级类目code
            }else {
                model.setShopCategory(mchStore.getExt().getString("shopCategory")); // 新版门店类目标准二级类目code
            }
        }

        model.setShopName(mchStore.getStoreName());
        model.setContactMobile(mchStore.getContactPhone());
        request.setBizModel(model);

        AntMerchantExpandShopModifyResponse response = AlipayKit.getAlipayClientWrapper(alipayIsvParams).getAlipayClient().execute(request);
        log.info("蚂蚁店铺修改响应，storeId={}，response={}", mchStore.getStoreId(), JSONObject.toJSONString(response));
        if (!response.isSuccess()) {
            throw new BizException(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
        }

        MchStore result = new MchStore();
        result.setAlipayShopCreateId(response.getOrderId());

        return result;
    }

    @Override
    public void close(AlipayIsvParams alipayIsvParams, String alipayShopId) {
        AntMerchantExpandShopCloseRequest request = new AntMerchantExpandShopCloseRequest();
        AntMerchantExpandShopCloseModel model = new AntMerchantExpandShopCloseModel();
        model.setShopId(alipayShopId);

        request.setBizModel(model);

        AntMerchantExpandShopCloseResponse response = AlipayKit.getAlipayClientWrapper(alipayIsvParams).getAlipayClient().execute(request);
        if (!response.isSuccess()) {
            throw new BizException(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
        }
    }

    @Override
    public MchStore createResultQuery(AlipayIsvParams alipayIsvParams, String orderId){
        AntMerchantExpandOrderQueryRequest request = new AntMerchantExpandOrderQueryRequest();
        AntMerchantExpandOrderQueryModel model = new AntMerchantExpandOrderQueryModel();
        model.setOrderId(orderId);
        request.setBizModel(model);

        AntMerchantExpandOrderQueryResponse response = AlipayKit.getAlipayClientWrapper(alipayIsvParams).getAlipayClient().execute(request);
        log.info("蚂蚁店铺申请单查询接口响应，orderId={}，response={}", orderId, JSONObject.toJSONString(response));
        if (!response.isSuccess()) {
            throw new BizException(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
        }

        MchStore result = new MchStore();
        if (StringUtils.isNotBlank(response.getExtInfo())) {
            JSONObject extInfo = JSONObject.parseObject(response.getExtInfo());
            result.setAlipayShopId(extInfo.getString("SHOP_ID"));
        }
        result.setAlipayShopStatus(response.getStatus());

        return result;
    }

}
