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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.common.utils.http.HttpUtils;
import com.cpop.core.base.entity.PageDomain;
import com.cpop.core.base.exception.ServiceException;
import com.cpop.core.utils.SpringUtils;
import com.cpop.core.utils.sql.SqlUtils;
import com.cpop.jambox.business.entity.BrandExtend;
import com.cpop.jambox.business.entity.StoreExtend;
import com.cpop.jambox.business.entity.table.BrandExtendTableDef;
import com.cpop.jambox.business.entity.table.StoreExtendTableDef;
import com.cpop.jambox.business.service.BrandExtendService;
import com.cpop.jambox.business.service.StoreExtendService;
import com.cpop.jambox.framework.constant.JamboxCloudUrl;
import com.cpop.oam.business.bo.BrandManagerBo;
import com.cpop.oam.business.bo.BrandManagerPageBo;
import com.cpop.oam.business.entity.BrandManagerStore;
import com.cpop.oam.business.entity.BrandManager;
import com.cpop.oam.business.mapper.BrandManagerMapper;
import com.cpop.oam.business.service.BrandManagerStoreService;
import com.cpop.oam.business.service.BrandManagerService;
import com.cpop.oam.business.vo.BrandManagePageVo;
import com.cpop.system.business.entity.table.BrandTableDef;
import com.cpop.system.business.entity.table.StoreTableDef;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.cpop.oam.business.entity.table.BrandManagerStoreTableDef.BRAND_MANAGER_STORE;
import static com.cpop.oam.business.entity.table.BrandManagerTableDef.BRAND_MANAGER;
import static com.cpop.system.business.entity.table.BrandTableDef.BRAND;
import static com.cpop.system.business.entity.table.StoreTableDef.STORE;
import static com.mybatisflex.core.query.QueryMethods.distinct;
import static com.mybatisflex.core.query.QueryMethods.groupConcat;

/**
 * 品牌管理员表 服务层实现。
 *
 * @author DB
 * @since 2023-12-07
 */
@Slf4j
@Service("brandManageService")
public class BrandManagerServiceImpl extends ServiceImpl<BrandManagerMapper, BrandManager> implements BrandManagerService {

    /**
     * 查询品牌管理员分页
     * @author DB
     * @since 2023/12/07
     * @param bo 请求参数
     * @return Page<BrandManagePageVo>
     */
    @Override
    public Page<BrandManagePageVo> getBrandManagerPage(BrandManagerPageBo bo) {
        PageDomain pageDomain = SqlUtils.getInstance().getPageDomain();
        return this.pageAs(Page.of(pageDomain.getPageNum(),pageDomain.getPageSize()),
                QueryWrapper.create()
                        //品管
                        .select(distinct(BRAND_MANAGER.ID, BRAND_MANAGER.NAME, BRAND_MANAGER.PHONE, BRAND_MANAGER.CREATE_TIME))
                        //品牌
                        .select(BRAND.BRAND_NAME)
                        //校区
                        .select(groupConcat(STORE.STORE_NAME).as(BrandManagePageVo::getStoreName))
                        //中间表
                        .leftJoin(BRAND_MANAGER_STORE).on(BRAND_MANAGER_STORE.BRAND_MANAGER_ID.eq(BRAND_MANAGER.ID))
                        //品牌
                        .leftJoin(BRAND).on(BRAND.ID.eq(BRAND_MANAGER_STORE.BRAND_ID))
                        //校区
                        .leftJoin(STORE).on(STORE.ID.eq(BRAND_MANAGER_STORE.STORE_ID))
                        .and(BRAND_MANAGER.PHONE.like(bo.getPhoneNumber()))
                        .and(BRAND_MANAGER.NAME.like(bo.getName()))
                        .and(BRAND.BRAND_NAME.like(bo.getBrandName()))
                        .groupBy(BRAND_MANAGER.ID)
                        .orderBy(BRAND_MANAGER.CREATE_TIME.desc()),
                BrandManagePageVo.class);
    }

    /**
     * 删除品牌管理员
     * @author DB
     * @since 2023/12/07
     * @param id 主键
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeBrandManagerById(String id) {
        BrandManager brandManage = this.getById(id);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("_type","brandManagerDel");
        jsonBody.put("brandManagerId", brandManage.getBrandManagerCloudId());
        SpringUtils.getBean(RestTemplate.class).postForObject(JamboxCloudUrl.COMMON_CARD_URL, jsonBody, JSONObject.class);
        this.removeById(id);
        //删除中间表
        SpringUtils.getBean(BrandManagerStoreService.class).updateChain().where(BRAND_MANAGER_STORE.BRAND_MANAGER_ID.eq(id)).remove();
    }

    /**
     * 新增品牌管理员
     * @author DB
     * @since 2023/12/08
     * @param bo 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBrandManager(BrandManagerBo bo) {
        //查询此管理员是否已存在
        if (this.count(QueryWrapper.create().leftJoin(BRAND_MANAGER_STORE).on(BRAND_MANAGER_STORE.BRAND_MANAGER_ID.eq(BRAND_MANAGER.ID))
                .where(BRAND_MANAGER.NAME.eq(bo.getName()))
                .and(BRAND_MANAGER.PHONE.eq(bo.getPhone()))
                .and(BRAND_MANAGER_STORE.BRAND_ID.eq(bo.getBrandId()))) > 0) {
            throw new ServiceException("当前管理员已存在");
        }
        //获取云品牌id
        BrandExtend brandExtend = SpringUtils.getBean(BrandExtendService.class).queryChain().where(BrandExtendTableDef.BRAND_EXTEND.BRAND_ID.eq(bo.getBrandId())).one();
        //获取用户信息
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("_type", "brandManagerAdd");
        jsonBody.put("brandId", brandExtend.getBrandCloudId());
        jsonBody.put("name", bo.getName());
        jsonBody.put("phone", bo.getPhone());
        jsonBody.put("position", "OAM添加");
        if (bo.getStoreIds() != null) {
            //获取云校区id
            List<String> cloudStoreIds = SpringUtils.getBean(StoreExtendService.class).queryChain().where(StoreExtendTableDef.STORE_EXTEND.STORE_ID.in(bo.getStoreIds())).list()
                    .stream().map(StoreExtend::getStoreCloudId).collect(Collectors.toList());
            jsonBody.put("store", cloudStoreIds);
        }
        //本地新增
        BrandManager brandManage = BeanUtils.mapToClass(bo, BrandManager.class);
        JSONObject result = SpringUtils.getBean(RestTemplate.class).postForObject(JamboxCloudUrl.COMMON_CARD_URL, jsonBody, JSONObject.class);
        assert result != null;
        brandManage.setBrandManagerCloudId(result.getString("data"));
        this.save(brandManage);
        List<BrandManagerStore> brandManagerStores = new ArrayList<>();
        //添加中间表
        if (bo.getStoreIds() != null) {
            bo.getStoreIds().forEach(item -> {
                BrandManagerStore brandManageStore = new BrandManagerStore();
                brandManageStore.setStoreId(item).setBrandId(bo.getBrandId()).setBrandManagerId(brandManage.getId());
                brandManagerStores.add(brandManageStore);
            });
        } else {
            BrandManagerStore brandManageStore = new BrandManagerStore();
            brandManageStore.setBrandId(bo.getBrandId()).setBrandManagerId(brandManage.getId());
            brandManagerStores.add(brandManageStore);
        }
        SpringUtils.getBean(BrandManagerStoreService.class).saveBatch(brandManagerStores);
    }
}
