package com.cpop.system.business.service.impl;

import com.cpop.common.utils.StringUtils;
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.base.exception.ServiceException;
import com.cpop.core.utils.SecurityUtils;
import com.cpop.core.utils.SpringUtils;
import com.cpop.core.utils.sql.SqlUtils;
import com.cpop.system.business.entity.Store;
import com.cpop.system.business.entity.StoreLicense;
import com.cpop.system.business.service.StoreLicenseService;
import com.cpop.system.business.service.StoreService;
import com.cpop.system.business.vo.BrandPageVo;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.*;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.cpop.system.business.entity.Brand;
import com.cpop.system.business.mapper.BrandMapper;
import com.cpop.system.business.service.BrandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

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

/**
 * 系统-品牌表 服务层实现。
 *
 * @author DB
 * @since 2023-10-25
 */
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    /**
     * @descriptions 导入果酱品牌
     * @author DB
     * @date 2023/10/25 15:54
     * @param jamboxBrandId 果酱品牌id
     * @return: void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importJamboxBrand(String jamboxBrandId) {
        //获取果酱品牌信息
        Row brand;
        try {
            DataSourceKey.use("jambox");
            brand = Db.selectOneByQuery(QueryWrapper.create()
                    .select()
                    .from("t_brand_info")
                    .where("id = ?", jamboxBrandId));
            if (brand == null) {
                throw new ServiceException("获取果酱品牌失败,请联系相关人员");
            }
        } finally {
            DataSourceKey.clear();
        }
        //查询品牌是否已经录入
        long count = DbChain.table("cp_j_brand_extend")
                .where("brand_cloud_id = ?", brand.getString("brandId"))
                .and("is_delete = 0")
                .count();
        if (count > 0) {
            throw new ServiceException("当前品牌已导入,请勿重复导入");
        }
        Brand sysBrand = new Brand();
        sysBrand.setBrandName(brand.getString("name"))
                .setWxMchId(brand.getString("wxMchId"))
                .setSourceType(SourceType.JAMBOX.toString());
        this.save(sysBrand);
        //果酱拓展表信息
        LocalDateTime now = LocalDateTime.now();
        LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
        RowKey brandKey = RowKey.SNOW_FLAKE_ID;
        DbChain.table("cp_j_brand_extend")
                .setId(brandKey)
                .set("brand_id", sysBrand.getId())
                .set("brand_cloud_id", brand.getString("brandId"))
                .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();
        //导入果酱品牌关联校区
        importJamboxStore(jamboxBrandId,sysBrand.getId());
    }

    /**
     * @descriptions 导入果酱校区id
     * @author DB
     * @date 2023/10/26 18:30
     * @param jamboxBrandId 果酱品牌id
     * @param brandId 品牌id
     * @return: void
     */
    private void importJamboxStore(String jamboxBrandId, String brandId) {
        //获取果酱校区信息
        List<Row> storeList;
        try {
            DataSourceKey.use("jambox");
            storeList = Db.selectListByQuery(QueryWrapper.create()
                    .select("store_id as storeCloudId", "mechanism as storeName", "address as storeAddr", "charge_name as personCharge", "charge_phone as phone", "X as longitude", "Y as latitude")
                    .from("t_mechanism_info")
                    .where("brand_id = ?", jamboxBrandId));
        } finally {
            DataSourceKey.clear();
        }
        //导入数据
        if (storeList != null) {
            List<Store> stores = RowUtil.toEntityList(storeList, Store.class);
            stores.forEach(item->{
                item.setBrandId(brandId);
                item.setSourceType(SourceType.JAMBOX.toString());
            });
            SpringUtils.getBean(StoreService.class).saveBatch(stores);
            //保存拓展表
            List<Row> storeExtends = new ArrayList<>();
            //果酱拓展表信息
            LocalDateTime now = LocalDateTime.now();
            LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
            for (int i = 0; i < storeList.size(); i++) {
                Row row = Row.ofKey(RowKey.SNOW_FLAKE_ID);
                row.set("store_cloud_id", storeList.get(i).getString("storeCloudId"));
                row.set("store_id", stores.get(i).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());
                storeExtends.add(row);
            }
            Db.insertBatch("cp_j_store_extend", storeExtends);
            //导入证书信息
            List<Row> rowList;
            try {
                DataSourceKey.use("jambox");
                rowList = DbChain.table("t_mechanism_info").select("store_id as storeCloudId", "reg_addr as licenseAddr", "str_to_date(reg_date,'%Y年%m月%d') as licenseDate", "reg_Name as licenseName",
                                "ness_license_id as licenseCode", "corp_name as licenseUserName", "reg_pic as licensePicUrl")
                        .where("reg_addr is not null")
                        .in("store_id", storeList.stream().map(item -> item.getString("storeCloudId")).collect(Collectors.toList()))
                        .list();
            } finally {
                DataSourceKey.clear();
            }
            //获取校区信息
            Map<String, String> storeMap = storeExtends.stream().collect(Collectors.toMap(item->item.getString("store_cloud_id"),item->item.getString("store_id")));
            rowList.forEach(item -> {
                item.set("storeId", storeMap.get(item.getString("storeCloudId")));
            });
            List<StoreLicense> licenseList = RowUtil.toEntityList(rowList, StoreLicense.class).stream().filter(item->item.getStoreId() != null).collect(Collectors.toList());
            SpringUtils.getBean(StoreLicenseService.class).saveBatch(licenseList);
        }
    }

    /**
     * @descriptions 查询品牌分页列表
     * @author DB
     * @date 2023/10/25 17:32
     * @param brandName 品牌名
     * @return: com.mybatisflex.core.paginate.Page<com.cpop.system.business.vo.BrandPageVo>
     */
    @Override
    public Page<BrandPageVo> getBrandPage(String brandName) {
        PageDomain pageDomain = SqlUtils.getInstance().getPageDomain();
        return this.mapper.paginateAs(pageDomain.getPageNum(), pageDomain.getPageSize(),
                QueryWrapper.create()
                        .select(BRAND.ID, BRAND.BRAND_NAME, BRAND.WX_MCH_ID, BRAND.CREATE_TIME, BRAND.IS_OPEN_SHARING)
                        .and(BRAND.BRAND_NAME.like(brandName))
                        .orderBy(BRAND.CREATE_TIME.desc()),
                BrandPageVo.class);
    }

    /**
     * @descriptions 根据品牌id删除品牌
     * @author DB
     * @date 2023/11/09 10:34
     * @param id 主键
     * @return: void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeBrandById(String id) {
        Brand brand = this.getById(id);
        StoreService storeService = SpringUtils.getBean(StoreService.class);
        if (StringUtils.equals(brand.getSourceType(),SourceType.JAMBOX.toString())){
            //果酱处导入,先删除拓展校区
            List<Store> storeList = storeService.queryChain().where(STORE.BRAND_ID.eq(id)).list();
            if (!storeList.isEmpty()){
                DbChain.table("cp_j_store_extend")
                        .set("is_delete", 1)
                        .where("store_id in ?", storeList.stream().map(Store::getId).collect(Collectors.toSet()))
                        .update();
            }
        }
        //删除校区
        storeService.updateChain().where(STORE.BRAND_ID.eq(brand.getId())).remove();
        //逻辑删除品牌拓展
        DbChain.table("cp_j_brand_extend")
                .set("is_delete", 1)
                .where("brand_id = ?", id)
                .update();
        //删除品牌
        this.removeById(id);
    }
}
