package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.dao.*;
import com.cool.store.entity.*;
import com.cool.store.enums.*;
import com.cool.store.enums.point.PaymentMethodEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.FranchiseFeeMapper;
import com.cool.store.mapper.SignFranchiseMapper;
import com.cool.store.mq.producer.SimpleMessageService;
import com.cool.store.request.StoreMasterDTO;
import com.cool.store.request.StoreRequestBody;
import com.cool.store.service.OperationLogService;
import com.cool.store.service.SyncMainSysServer;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.utils.poi.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.cool.store.enums.AuditExecuteEnum.FRANCHISEES;
import static com.cool.store.enums.ExtendFieldTypeEnum.*;

/**
 * @Author: WangShuo
 * @Date: 2025/07/10/17:14
 * @Version 1.0
 * @注释:
 */
@Service
@Slf4j
public class SyncMainSysServerImpl implements SyncMainSysServer {
    @Resource
    private BigRegionDAO bigRegionDAO;
    @Value("${spring.profiles.active}")
    private String active;
    @Resource
    private SimpleMessageService simpleMessageService;
    @Resource
    private SignFranchiseMapper signFranchiseMapper;
    @Resource
    private BuildInformationDAO buildInformationDAO;
    @Resource
    private PointInfoDAO pointInfoDAO;
    @Resource
    FranchiseFeeMapper franchiseFeeMapper;
    @Resource
    private OperationLogDAO operationLogDAO;
    @Resource
    private OrderSysInfoDAO orderSysInfoDAO;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private PreparationServiceImpl preparationService;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private CommonService commonService;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Value("${mybatis.configuration.variables.enterpriseId}")
    private String eid;
    @Resource
    private StoreDao storeDao;
    @Resource
    SignFranchiseDAO signFranchiseDAO;
    @Resource
    PointDetailInfoDAO pointDetailDAO;
    @Resource
    QualificationsInfoDAO qualificationsInfoDAO;

    @Override
    @Async
    public void syncStore(Long shopId) {
        log.info("开始同步门店 syncStore:{}", shopId);
        addStore(shopId);
    }


    /**
     * 添加门店
     * @param shopId
     */
    public void addStore(Long shopId) {
        try {
            StoreMasterDTO storeMasterDTO = new StoreMasterDTO();
            ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
            if (shopInfo == null){
                log.info("门店不存在:{}", shopId);
                return;
            }
            storeMasterDTO.setEnterpriseId(eid);
            storeMasterDTO.setStoreStatus("not_open");
            storeMasterDTO.setStoreName(shopInfo.getShopName());
            storeMasterDTO.setStoreNum(shopInfo.getShopCode());
            storeMasterDTO.setJoinBrand(StringUtils.isNotEmpty(shopInfo.getFranchiseBrand())?Integer.valueOf(shopInfo.getFranchiseBrand()):null);
            storeMasterDTO.setJoinModel(shopInfo.getJoinMode());
            storeMasterDTO.setStoreType(shopInfo.getStoreType());

            SignFranchiseDO signFranchiseDO = signFranchiseDAO.selectByShopId(shopId);
            storeMasterDTO.setManageModel(signFranchiseDO.getBusinessModel());
            storeMasterDTO.setSignType(signFranchiseDO.getSignType());
            storeMasterDTO.setProtectiveDistance(signFranchiseDO.getProtectiveDistance());
            storeMasterDTO.setUnifiedManagement(signFranchiseDO.getUnifiedManagement());

            BigRegionDO region = bigRegionDAO.getByRegionId(shopInfo.getRegionId());
            storeMasterDTO.setBloc(region.getGroupName());
            storeMasterDTO.setBranch(region.getRegionId());
            storeMasterDTO.setRegionId(shopInfo.getManagerRegionId());
            storeMasterDTO.setJoinSupervision(shopInfo.getInvestmentManager());

            BuildInformationDO buildInformationDO = buildInformationDAO.selectOneByShopId(shopId);
            if (buildInformationDO != null){
                storeMasterDTO.setMiniProgramOrderStoreName(buildInformationDO.getCShopName());
                if (StringUtils.isNotBlank(buildInformationDO.getBusinessHours())) {
                    try {
                        String[] times = buildInformationDO.getBusinessHours().split("~");
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                        LocalTime startTime = LocalTime.parse(times[0], formatter);
                        LocalTime endTime = LocalTime.parse(times[1], formatter);
                        String startMillis = String.valueOf(startTime.toSecondOfDay() * 1000L);
                        String endMillis = String.valueOf(endTime.toSecondOfDay() * 1000L);
                        storeMasterDTO.setBusinessHours(startMillis + "," + endMillis);
                    } catch (Exception e) {
                        log.info("时间转换异常:{},shopId:{},time:{}", e.getMessage(), shopId.toString(), buildInformationDO.getBusinessHours());
                    }
                }
                StoreMasterDTO.SettlerInfo settlerInfo = new StoreMasterDTO.SettlerInfo();
                settlerInfo.setSettlerName(buildInformationDO.getSettlerName());
                settlerInfo.setSettlerIdCardNo(buildInformationDO.getSettlerIdCardNo());
                settlerInfo.setSettlerIdCardFront(buildInformationDO.getSettlerIdCardFront());
                settlerInfo.setSettlerIdCardReverse(buildInformationDO.getSettlerIdCardReverse());
                settlerInfo.setSettlerInHandFrontPicture(buildInformationDO.getSettlerInHandFrontPicture());
                settlerInfo.setSettlerInHandBackPicture(buildInformationDO.getSettlerInHandBackPicture());
                settlerInfo.setSettlerBankName(buildInformationDO.getSettlerBankName());
                settlerInfo.setSettlerBankBranchName(buildInformationDO.getSettlerBankName());
                settlerInfo.setSettlerBankNumber(buildInformationDO.getSettlerBankNumber());
                settlerInfo.setSettlerBankMobile(buildInformationDO.getSettlerBankMobile());
                settlerInfo.setSettlerBankPhotoUrl(buildInformationDO.getSettlerBankPhotoUrl());
                settlerInfo.setSettlerBankBackPhotoUrl(buildInformationDO.getSettlerBankBackPhotoUrl());
                storeMasterDTO.setSettlerInfo(settlerInfo);
            }


            if (shopInfo.getPointId()!=null){
                PointInfoDO info = pointInfoDAO.getPointInfoById(shopInfo.getPointId());
                PointDetailInfoDO pointDetail = pointDetailDAO.getPointDetailInfoByPointId(shopInfo.getPointId());
                if (info != null){
                    storeMasterDTO.setArea(info.getProvince()+info.getCity()+info.getDistrict());
                    storeMasterDTO.setProvince(info.getProvince());
                    storeMasterDTO.setCity(info.getCity());
                    storeMasterDTO.setDistrict(info.getDistrict());
                    storeMasterDTO.setTown(info.getTownship());
                    storeMasterDTO.setStoreAddress(info.getAddress());
                    storeMasterDTO.setLocationAddress(info.getAddress());
                    storeMasterDTO.setPointCode(info.getPointCode());
                    storeMasterDTO.setLongitude(info.getLongitude());
                    storeMasterDTO.setLatitude(info.getLatitude());
                    try {
                        if (StringUtils.isNotEmpty(pointDetail.getMonthRent())&&pointDetail.getPaymentMethod()!=null){
                            //获取支付方式
                            PaymentMethodEnum paymentMethodEnum = PaymentMethodEnum.getByCode(pointDetail.getPaymentMethod());
                            BigDecimal monthlyRent = new BigDecimal(pointDetail.getMonthRent()).divide(new BigDecimal(paymentMethodEnum.getTotalMonth()));
                            storeMasterDTO.setMonthlyRent(monthlyRent);
                        }
                    } catch (Exception e) {
                        log.info("月租转换异常:{},shopId:{},time:{}", e.getMessage(), shopId.toString(), pointDetail.getMonthRent());
                    }
                }
            }
            OrderSysInfoDO orderSysInfoDO = orderSysInfoDAO.selectByShopId(shopId);
            if (orderSysInfoDO != null){
                storeMasterDTO.setAddresseeName(orderSysInfoDO.getAddresseeName());
                storeMasterDTO.setAddresseeMobile(orderSysInfoDO.getAddresseeMobile());
                storeMasterDTO.setAddresseeArea(orderSysInfoDO.getAddresseeProvince()+orderSysInfoDO.getAddresseeCity()+orderSysInfoDO.getAddresseeDistrict());
                storeMasterDTO.setAddresseeAddress(orderSysInfoDO.getAddresseeAddress());
                storeMasterDTO.setDeclareGoodsLogisticsWarehouse(orderSysInfoDO.getDeclareGoodsLogisticsWarehouse());
                storeMasterDTO.setDeclareGoodsType(Integer.valueOf(orderSysInfoDO.getDeclareGoodsType()));
                storeMasterDTO.setDeclareGoodsDate(orderSysInfoDO.getDeclareGoodsDate());
            }
            LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfo.getLineId());
            StoreMasterDTO.SignerInfo signerInfo = new StoreMasterDTO.SignerInfo();
            if (lineInfoDO != null){
                signerInfo.setSigner1Name(lineInfoDO.getUsername());
                signerInfo.setSigner1Mobile(lineInfoDO.getMobile());
                signerInfo.setPartnerRoleId(UserRoleEnum.FRANCHISEES.getCode());
            }
            QualificationsInfoDO infoDO = qualificationsInfoDAO.getByLineId(shopInfo.getLineId());
            if (infoDO != null){
                signerInfo.setSigner1IdCard(infoDO.getIdCardNo());
                signerInfo.setSigner1IdCardPhoto(infoDO.getFrontOfIdCard());
                signerInfo.setSigner1IdCardPhotoBack(infoDO.getBackOfIdCard());
            }
            storeMasterDTO.setSignerInfo(signerInfo);
            simpleMessageService.send(JSONObject.toJSONString(storeMasterDTO), RocketMqTagEnum.ZXJP_CREATE_STORE);
        } catch (Exception e) {
            log.info("asdStore_error:{},shopId:{}", e.getMessage(), shopId.toString());
        }
    }


}
