/*
 * @Author: DB
 * 
 * @Date: 2023-10-26 18:22:22
 * 
 * @Description: 请填写简介
 */
package com.cpop.system.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cpop.api.cloudDb.core.dto.CloudStoreDto;
import com.cpop.api.cloudDb.handler.CloudStoreHandler;
import com.cpop.api.tencent.location.handler.TencentLocationHandler;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.base.entity.PageDomain;
import com.cpop.core.base.enums.SourceType;
import com.cpop.core.utils.SecurityUtils;
import com.cpop.core.utils.SpringUtils;
import com.cpop.core.utils.sql.SqlUtils;
import com.cpop.system.business.bo.StoreBo;
import com.cpop.system.business.bo.StorePageBo;
import com.cpop.system.business.bo.SyncBrandAndStoreBo;
import com.cpop.system.business.entity.Brand;
import com.cpop.system.business.entity.Store;
import com.cpop.system.business.entity.StoreLicense;
import com.cpop.system.business.mapper.StoreMapper;
import com.cpop.system.business.service.BrandService;
import com.cpop.system.business.service.StoreLicenseService;
import com.cpop.system.business.service.StoreService;
import com.cpop.system.business.vo.StorePageVo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowKey;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import static com.cpop.system.business.entity.table.BrandTableDef.BRAND;
import static com.cpop.system.business.entity.table.StoreSignTableDef.STORE_SIGN;
import static com.cpop.system.business.entity.table.StoreTableDef.STORE;

/**
 * 系统-店铺/校区表 服务层实现。
 *
 * @author DB
 * @since 2023-10-26
 */
@Service("storeService")
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

	/**
	 * @Author: DB
	 * @description: 获取校区分页列表
	 * @Date: 2023-11-23 15:35:05
	 * @return {*}
	 */
	@Override
	public Page<StorePageVo> getStorePage(StorePageBo bo) {
		PageDomain pageDomain = SqlUtils.getInstance().getPageDomain();
		return this.getMapper().paginateAs(Page.of(pageDomain.getPageNum(), pageDomain.getPageSize()),
				QueryWrapper.create().select(STORE.ID, STORE.STORE_NAME, STORE.SOURCE_TYPE, STORE.CREATE_TIME, STORE.STORE_ADDR, STORE.PERSON_CHARGE, STORE.PHONE, STORE.HAVE_ACTIVE,
								STORE.HAVE_COUNSELOR, STORE.WX_MCH_ID)
						.select(STORE_SIGN.EXPIRE_DATE)
						.select(BRAND.BRAND_NAME, BRAND.ID.as(StorePageVo::getBrandId))
						.select("cp_j_store_extend.store_cloud_id as storeCloudId")
						.from(STORE)
						.leftJoin(STORE_SIGN).on(STORE_SIGN.STORE_ID.eq(STORE.ID))
						.leftJoin(BRAND).on(BRAND.ID.eq(STORE.BRAND_ID))
						.leftJoin("cp_j_store_extend").on("`cp_j_store_extend`.`store_id` = `cp_sys_store`.`id`")
						.and(STORE.STORE_NAME.like(bo.getName()))
						.orderBy(BRAND.CREATE_TIME.desc()),
				StorePageVo.class);
	}

	/**
	 * 小程序同步品牌和校区
	 * @author DB
	 * @since 2023/12/21
	 * @param bo 请求参数
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void miniSyncBrandAndStore(SyncBrandAndStoreBo bo) {
		SyncBrandAndStoreBo.BrandInfo brandInfo = bo.getBrandInfo();
		//查询品牌
		Row brandExtend = DbChain.table("cp_j_brand_extend").where("brand_cloud_id = ?", brandInfo.getBrandCloudId()).one();
		Brand brand;
		LocalDateTime now = LocalDateTime.now();
		LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
		BrandService brandService = SpringUtils.getBean(BrandService.class);
		if (brandExtend == null || brandExtend.isEmpty()) {
			brand = new Brand();
			brand.setBrandName(brandInfo.getBrandName()).setSourceType(SourceType.JAMBOX.toString());
			brandService.save(brand);
			//保存拓展
			RowKey brandKey = RowKey.SNOW_FLAKE_ID;
			DbChain.table("cp_j_brand_extend")
					.setId(brandKey)
					.set("brand_id", brand.getId())
					.set("brand_cloud_id", brandInfo.getBrandCloudId())
					.set("create_time", now)
					.set("update_time", now)
					.set("create_user_id", loginUser == null ? "1" : loginUser.getUserId())
					.set("update_user_id", loginUser == null ? "1" : loginUser.getUserId())
					.save();
		} else {
			brand = brandService.getById(brandExtend.getString("brandId"));
		}
		Store store = BeanUtils.mapToClass(bo.getStoreInfo(), Store.class);
		store.setBrandId(brand.getId()).setSourceType(SourceType.JAMBOX.toString());
		this.save(store);
		//拓展
		SyncBrandAndStoreBo.StoreInfo storeInfo = bo.getStoreInfo();
		Row row = Row.ofKey(RowKey.SNOW_FLAKE_ID);
		row.set("store_cloud_id", storeInfo.getStoreCloudId());
		row.set("store_id", store.getId());
		row.set("create_time", now);
		row.set("update_time", now);
		row.set("create_user_id", loginUser == null ? "1" : loginUser.getUserId());
		row.set("update_user_id", loginUser == null ? "1" : loginUser.getUserId());
		Db.insert("cp_j_store_extend",row);
		//营业执照
		StoreLicense storeLicense = BeanUtils.mapToClass(bo.getStoreInfo(), StoreLicense.class);
		storeLicense.setStoreId(store.getId());
		SpringUtils.getBean(StoreLicenseService.class).save(storeLicense);
		//添加线索以及
		Row clue = Row.ofKey(RowKey.SNOW_FLAKE_ID);
		clue.set("store_id",store.getId());
		//校区城市
		JSONObject geocoder = SpringUtils.getBean(TencentLocationHandler.class).geocoder(bo.getStoreInfo().getLongitude(), bo.getStoreInfo().getLatitude(), "UGLBZ-LBF3I-ETCGO-UUH5X-QDV45-3LFKA");
		if (geocoder.getInteger("status") == 0){
			clue.set("city",geocoder.getJSONObject("result").getJSONObject("ad_info").getString("city"));
		}
		clue.set("clue_status",0);
		clue.set("create_time", now);
		clue.set("update_time", now);
		clue.set("create_user_id", loginUser == null ? "1" : loginUser.getUserId());
		clue.set("update_user_id", loginUser == null ? "1" : loginUser.getUserId());
		Db.insert("cp_oam_clue",clue);
		//录入记录
		Row clueRecord = Row.ofKey(RowKey.SNOW_FLAKE_ID);
		clueRecord.set("clue_id",clue.getString("id"));
		clueRecord.set("record_type",0);
		clueRecord.set("record_content", "机构负责人" + store.getPersonCharge() + "创建线索");
		clueRecord.set("record_staff_id", "1");
		clueRecord.set("create_time", now);
		clueRecord.set("update_time", now);
		clueRecord.set("create_user_id", loginUser == null ? "1" : loginUser.getUserId());
		clueRecord.set("update_user_id", loginUser == null ? "1" : loginUser.getUserId());
		Db.insert("cp_oam_clue_record",clueRecord);
	}

	/**
	 * 更新校区
	 * @author DB
	 * @since 2024/1/15
	 * @param bo 请求参数
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateStore(StoreBo bo) {
		Store store = BeanUtils.mapToClass(bo, Store.class);
		this.updateById(store);
		//获取云信息
		Row row = Db.selectOneByQuery("cp_j_store_extend", QueryWrapper.create()
				.select("cjse.store_cloud_id", "cjbe.brand_cloud_id")
				.from("cp_j_store_extend").as("cjse")
				.leftJoin("cp_sys_store").as("css").on("css.id = cjse.store_id")
				.leftJoin("cp_j_brand_extend").as("cjbe").on("cjbe.brand_id = css.brand_id")
				.where("cjse.store_id = ?", store.getId()));
		CloudStoreDto cloudStoreDto = BeanUtils.mapToClass(store, CloudStoreDto.class);
		cloudStoreDto.setBrandCloudId(row.getString("brandCloudId"));
		cloudStoreDto.setStoreCloudId(row.getString("storeCloudId"));
		//云更新
		SpringUtils.getBean(CloudStoreHandler.class).updateStore(cloudStoreDto);
	}
}
