package com.cool.store.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.*;
import com.cool.store.dto.DeclareGoodsDateDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.DownSystemTypeEnum;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.FranchiseBrandEnum;
import com.cool.store.enums.PlatformBuildEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.ApplyLicenseMapper;
import com.cool.store.mapper.SignFranchiseMapper;
import com.cool.store.mapper.WarehouseInfoMapper;
import com.cool.store.request.ZxjpApiRequest;
import com.cool.store.service.SyncDataService;
import com.cool.store.utils.JSONUtils;
import com.cool.store.utils.JsonUtils;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.utils.poi.constant.Constants;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: WangShuo
 * @Date: 2025/04/07/15:12
 * @Version 1.0
 * @注释:
 */
@Slf4j
@Service
public class SyncDataServiceImpl implements SyncDataService {

    @Resource
    private WarehouseInfoMapper warehouseInfoMapper;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private SignFranchiseMapper signFranchiseMapper;
    @Resource
    private HyPartnerUserInfoDAO hyPartnerUserInfoDAO;
    @Resource
    private OrderSysInfoDAO orderSysInfoDAO;
    @Resource
    private BuildInformationDAO buildInformationDAO;
    @Resource
    private AcceptanceInfoDAO acceptanceInfoDAO;
    @Resource
    private ApplyLicenseMapper applyLicenseMapper;
    @Resource
    private QualificationsInfoDAO qualificationsInfoDAO;
    @Resource
    private PointInfoDAO pointInfoDAO;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private PlatformBuildDAO platformBuildDAO;

    @Override
    public ZxjpApiRequest getData(Long shopId, DownSystemTypeEnum systemType) {
        ZxjpApiRequest request = new ZxjpApiRequest();
        request.setShopId(shopId);
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (shopInfo == null) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        Long lineId = shopInfo.getLineId();
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(lineId);
        if (lineInfoDO == null) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(shopInfo.getPartnerId());
        if (hyPartnerUserInfoDO == null) {
            throw new ServiceException(ErrorCodeEnum.PARTNER_USER_NOT_EXIST);
        }
        //加盟合同
        SignFranchiseDO signFranchiseDO = signFranchiseMapper.selectByShopId(shopId);
        //加盟商所有门店的门店编码
        List<String> shopCodeList = shopInfoDAO.getShopCodeList(lineId);
        //订货信息 & 总部订货收款账户
        OrderSysInfoDO orderSysInfoDO = orderSysInfoDAO.selectByShopId(shopId);
        //建店资料
        BuildInformationDO buildInformationDO = buildInformationDAO.selectOneByShopId(shopId);
        //铺位
        PointInfoDO pointInfo = pointInfoDAO.getPointInfoById(shopInfo.getPointId());
        //营业执照
        LicenseTransactDO licenseTransactDO = applyLicenseMapper.selectByShopId(shopId);
        //验收信息
        AcceptanceInfoDO acceptanceInfoDO = acceptanceInfoDAO.selectByShopId(shopId);
        //督导
        String investmentManager = enterpriseUserDAO.getUserName(shopInfo.getInvestmentManager());

        QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(lineId);
        //抖音
        PlatformBuildDO dyPlatformBuildDO = platformBuildDAO.selectOneByShopId(shopId, PlatformBuildEnum.DOU_YIN.getCode());
        //快手
        PlatformBuildDO ksPlatformBuildDO = platformBuildDAO.selectOneByShopId(shopId, PlatformBuildEnum.KUAI_SHOU.getCode());

        request.setPartnerIdCardNo(qualificationsInfoDO.getIdCardNo());
        request.setShopAddress(shopInfo.getDetailAddress());
        request.setStoreType(shopInfo.getStoreType());
        if (signFranchiseDO != null) {
            List<String> partnershipSignatory = new ArrayList<>();
            partnershipSignatory.add(signFranchiseDO.getPartnershipSignatoryFirst());
            if (StringUtils.isNotBlank(signFranchiseDO.getPartnershipSignatorySecond())) {
                partnershipSignatory.add(signFranchiseDO.getPartnershipSignatorySecond());
            }
            request.setPartnershipSignatory(partnershipSignatory);
            request.setBusinessModel(signFranchiseDO.getBusinessModel());
            request.setContractCode(signFranchiseDO.getContractCode());
        }
        request.setPartnerMobile(lineInfoDO.getMobile());
        request.setShopCode(shopInfo.getShopCode());
        request.setShopCodeList(shopCodeList);
        request.setCrmAccount(lineInfoDO.getMobile());
        request.setDownstreamSystemPassword(hyPartnerUserInfoDO.getDownstreamSystemPassword());
        request.setDownstreamSystemSalt(hyPartnerUserInfoDO.getDownstreamSystemSalting());
        request.setDownstreamSystemSecondaryPassword(hyPartnerUserInfoDO.getDownstreamSystemSecondaryPassword());
        if (StringUtils.isNotBlank(shopInfo.getFranchiseBrand())) {
            String[] split = shopInfo.getFranchiseBrand().split(Constants.COMMA);
            request.setFranchiseBrand(split[0]);
        }
        request.setFxyAccount(lineInfoDO.getMobile());
        request.setXzgAccount(shopInfo.getShopCode());

        request.setYlsAccount(shopInfo.getShopCode());
        request.setWqfAccount(shopInfo.getShopCode());
        request.setDownstreamSystemShopName(shopInfo.getShopName());
        if (DownSystemTypeEnum.XGJ.equals(systemType)) {
            request.setDownstreamSystemShopName(getXgjShopName(lineInfoDO, shopInfo,signFranchiseDO));
        }
        if (DownSystemTypeEnum.POS.equals(systemType)) {
            if (buildInformationDO != null) {
                String brand = FranchiseBrandEnum.getDescByCode(shopInfo.getFranchiseBrand());
                request.setDownstreamSystemShopName(brand + "(" + buildInformationDO.getCShopName() + ")");
            }
        }
        if (orderSysInfoDO != null) {
            request.setXgjRegionId(orderSysInfoDO.getXgjRegionId());
            request.setXgjRegionName(orderSysInfoDO.getXgjRegionName());
            request.setXgjVicePresident(orderSysInfoDO.getXgjVicePresident());
            request.setAddresseeName(orderSysInfoDO.getAddresseeName());
            request.setAddresseeMobile(orderSysInfoDO.getAddresseeMobile());
            request.setAddresseeProvince(orderSysInfoDO.getAddresseeProvince());
            request.setAddresseeCity(orderSysInfoDO.getAddresseeCity());
            request.setAddresseeDistrict(orderSysInfoDO.getAddresseeDistrict());
            request.setAddresseeAddress(orderSysInfoDO.getAddresseeAddress());
            request.setDeclareGoodsLogisticsWarehouse(orderSysInfoDO.getDeclareGoodsLogisticsWarehouse());
            WarehouseInfoDO warehouseInfoDO = warehouseInfoMapper.getByCode(orderSysInfoDO.getDeclareGoodsLogisticsWarehouse());
            if (Objects.nonNull(warehouseInfoDO)) {
                request.setDeclareGoodsLogisticsWarehouseName(warehouseInfoDO.getWarehouseName());
            }
            request.setDeclareGoodsType(orderSysInfoDO.getDeclareGoodsType());
            request.setDeclareGoodsDate(JSONUtils.parseToListOrMap(orderSysInfoDO.getDeclareGoodsDate(), new TypeReference<List<DeclareGoodsDateDTO>>() {
            }));
            request.setReceivingFirmName(orderSysInfoDO.getReceivingFirmName());
            request.setReceivingMSBankAccount(orderSysInfoDO.getReceivingMsBankAccount());
            request.setReceivingMSBankBranch(orderSysInfoDO.getReceivingMsBankBranch());
            request.setBankUnionPayAccount(orderSysInfoDO.getBankUnionPayAccount());
        }
        request.setShopSupervisorUserName(investmentManager);
        request.setJoinMode(shopInfo.getJoinMode());
        if (acceptanceInfoDO != null) {
            request.setShopDoorwayPhoto(getUrlList(acceptanceInfoDO.getShopDoorwayPhoto()));
            request.setShopInteriorPhoto(getUrlList(acceptanceInfoDO.getShopInteriorPhoto()));

            request.setShopLocationScreenshots(getUrl(acceptanceInfoDO.getShopLocationScreenshots()));
        }
        if (dyPlatformBuildDO != null) {
            request.setVerificationMobile(dyPlatformBuildDO.getDyMobile());
        }
        if (ksPlatformBuildDO != null) {
            request.setKsAccount(ksPlatformBuildDO.getKsAccount());
        }
        if (buildInformationDO != null) {
            request.setBusinessHours(buildInformationDO.getBusinessHours());
            request.setShopContactName(buildInformationDO.getShopContactName());
            request.setBusinessMobile(buildInformationDO.getBusinessMobile());
            request.setSettlerName(buildInformationDO.getSettlerName());
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerBankPhotoUrl())) {
                request.setSettlerBankPhotoUrl(getUrl(buildInformationDO.getSettlerBankPhotoUrl()));
            }
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerBankBackPhotoUrl())) {
                request.setSettlerBankBackPhotoUrl(getUrl(buildInformationDO.getSettlerBankBackPhotoUrl()));
            }
            request.setSettlerBankBranchName(buildInformationDO.getSettlerBankName());
            request.setSettlerBankNumber(buildInformationDO.getSettlerBankNumber());
            request.setSettlerBankMobile(buildInformationDO.getSettlerBankMobile());
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerIdCardFront())) {
                request.setSettlerIdCardFront(getUrl(buildInformationDO.getSettlerIdCardFront()));
            }
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerIdCardReverse())) {
                request.setSettlerIdCardReverse(getUrl(buildInformationDO.getSettlerIdCardReverse()));
            }
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerInHandBackPicture())) {
                request.setSettlerInHandBackPicture(getUrl(buildInformationDO.getSettlerInHandBackPicture()));
            }
            if (StringUtils.isNotBlank(buildInformationDO.getSettlerInHandFrontPicture())) {
                request.setSettlerInHandFrontPicture(getUrl(buildInformationDO.getSettlerInHandFrontPicture()));
            }
            request.setSettlerIdCardNo(buildInformationDO.getSettlerIdCardNo());

        }
        if (licenseTransactDO != null) {
            request.setCreditUrl(licenseTransactDO.getCreditUrl());
            request.setLegalName(licenseTransactDO.getLicenseLegalPerson());
            request.setLegalIdCardFront(licenseTransactDO.getLicenseLegalIdCardFront());
            request.setLegalIdCardBack(licenseTransactDO.getLicenseLegalIdCardBack());
            request.setLegalMobile(licenseTransactDO.getLicenseLegalMobile());
            //二证合一标识；0否 1 是
            if (Objects.equals(licenseTransactDO.getTwoCertificatesOne(), Constants.ONE_INTEGER)) {
                request.setFoodBusinessLicenseUrl(licenseTransactDO.getCreditUrl());
            } else {
                request.setFoodBusinessLicenseUrl(licenseTransactDO.getFoodBusinessLicenseUrl());
            }
        }
        if (pointInfo != null) {
            request.setShopProvinceCityDistrict(pointInfo.getProvince() + pointInfo.getCity() + pointInfo.getDistrict());
            request.setShopLongitude(pointInfo.getLongitude());
            request.setShopLatitude(pointInfo.getLatitude());
            request.setShopProvince(pointInfo.getProvince());
            request.setShopCity(pointInfo.getCity());
        }
        log.info("/pushData 数据 ：{}", JSONObject.toJSONString(request));
        return request;
    }

    private static String getUrl(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        try {
            // 将 JSON 字符串解析为 JSONArray
            JSONArray jsonArray = JSONArray.parseArray(json);

            // 获取第一个对象
            JSONObject jsonObject = jsonArray.getJSONObject(0);

            // 提取 "url" 的值
            return jsonObject.getString("url");
        } catch (Exception e) {
            log.info("getUrl error:{},JSON:{}", e.getMessage(), json);
        }
        return null;
    }

    private static List<String> getUrlList(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        try {
            // 将 JSON 字符串解析为 JSONArray
            List<String> result = new ArrayList<>();
            JSONArray jsonArray = JSONArray.parseArray(json);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                result.add(jsonObject.getString("url"));
            }

            return result;
        } catch (Exception e) {
            log.info("getUrl error:{},JSON:{}", e.getMessage(), json);
        }
        return getUrlListByComma(json);
    }

    private static List<String> getUrlListByComma(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return Arrays.asList(str.split(","));
        } catch (Exception e) {
            log.info("getUrlListByComma error:{},str:{}", e.getMessage(), str);
        }
        return null;
    }

    public String getXgjShopName(LineInfoDO lineInfoDO, ShopInfoDO shopInfoDO,SignFranchiseDO signFranchiseDO) {
        if (StringUtils.isBlank(shopInfoDO.getShopCode())||signFranchiseDO==null) {
            return null;
        }
        String shopCode = shopInfoDO.getShopCode().trim();
        if (Objects.isNull(signFranchiseDO)){
            log.info("合同阶段暂未完成");
            return "";
        }
        Boolean partnershipSignatorySecondIsNull = StringUtils.isBlank(signFranchiseDO.getPartnershipSignatorySecond());
        if (String.valueOf(FranchiseBrandEnum.ZXJP.getCode()).equals(shopInfoDO.getFranchiseBrand())) {
            //M10001
            if (shopCode.matches("M\\d*")) {
                return "MX" + shopInfoDO.getShopName();
            }
            //FS10001
            if (shopCode.matches("FS\\d*")) {
                return "FS" + shopInfoDO.getShopName();
            }
            // MS10001
            if (shopCode.matches("MS\\d*")) {
                return "MS" + shopInfoDO.getShopName();
            }
            // S10001
            if (shopCode.matches("S\\d*")) {
                return "S" + shopInfoDO.getShopName();
            }
            // ZX0001
            if (shopCode.matches("ZX\\d*")) {
                return "ZX" + shopInfoDO.getShopName();
            }
            if(shopCode.matches("HL\\d*")){
                return "HL" + shopInfoDO.getShopName();
            }
        }
        if (String.valueOf(FranchiseBrandEnum.MZG.getCode()).equals(shopInfoDO.getFranchiseBrand())) {
            if (shopCode.matches("MZGM\\d*")) {
                return "MZGM" + shopInfoDO.getShopName();
            }
            if (shopCode.matches("MZGS\\d*")) {
                return FranchiseBrandEnum.MZG.getDesc() + shopInfoDO.getShopName();
            }
        }
        if (String.valueOf(FranchiseBrandEnum.ZJS.getCode()).equals(shopInfoDO.getFranchiseBrand())) {
            if (shopCode.matches("LX\\d*")) {
                return "LX" + shopInfoDO.getShopName();
            }
            if (shopCode.matches("X\\d*")) {
                return "X" + shopInfoDO.getShopName();
            }
            if (shopCode.matches("Q\\d*")) {
                return "Q" + shopInfoDO.getShopName();
            }
            if (shopCode.matches("Z\\d*")) {
                return FranchiseBrandEnum.ZJS.getDesc() + shopInfoDO.getShopName();
            }
        }
        return null;
    }
}
