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

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.cpop.common.constant.Constants;
import com.cpop.common.utils.StringUtils;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.core.service.RedisService;
import com.cpop.core.service.impl.RedisServiceImpl;
import com.cpop.core.utils.SecurityUtils;
import com.cpop.core.utils.SpringUtils;
import com.cpop.system.business.bo.StoreRenewBo;
import com.cpop.system.business.service.StoreService;
import com.cpop.system.business.service.StoreSignService;
import com.cpop.system.framework.constant.SystemRedisKey;
import com.mybatisflex.core.datasource.DataSourceKey;
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 com.cpop.system.business.entity.StoreRenew;
import com.cpop.system.business.mapper.StoreRenewMapper;
import com.cpop.system.business.service.StoreRenewService;
import org.bouncycastle.util.StoreException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClientConfig;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

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-12-14
 */
@Service("storeRenewService")
public class StoreRenewServiceImpl extends ServiceImpl<StoreRenewMapper, StoreRenew> implements StoreRenewService {

    /**
     * 校区续费
     * @author DB
     * @since 2024/1/11
     * @param bo 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void storeRenew(StoreRenewBo bo) {
        StoreRenew storeRenew = BeanUtils.mapToClass(bo, StoreRenew.class);
        if (bo.getRenewType() == 2){
            storeRenew.setRenewDate(LocalDate.now().plusYears(1));
        }
        JSONObject loginUserInfo = SecurityUtils.getInstance().getLoginUserInfo();
        storeRenew.setRenewStaffId(loginUserInfo.getString("id"));
        this.save(storeRenew);
        SpringUtils.getBean(StoreService.class).updateChain()
                .set(STORE.HAVE_ACTIVE, true)
                .where(STORE.ID.eq(bo.getStoreId()))
                .update();
        //修改校区签约到期时间
        SpringUtils.getBean(StoreSignService.class).updateChain()
                .set(STORE_SIGN.EXPIRE_DATE, storeRenew.getRenewDate())
                .where(STORE_SIGN.STORE_ID.eq(bo.getStoreId()))
                .update();
        //修改缓存
        SpringUtils.getBean(RedisService.class).setCacheObject(SystemRedisKey.STORE_SIGN_EXPIRE_DATE + bo.getStoreId(),
                storeRenew.getRenewDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                , 24, TimeUnit.HOURS);
        storeRenewOld(storeRenew,loginUserInfo);
    }

    /**
     * 同步更新旧校区数据
     * @author DB
     * @since 2024/1/11
     * @param bo 请求参数
     */
    @Deprecated
    private void storeRenewOld(StoreRenew storeRenew,JSONObject loginUserInfo) {
        //线上
        if (StringUtils.equals(SpringUtils.getActiveProfile(), "prod")) {
            //获取云校区
            Row storeExtend = DbChain.table("cp_j_store_extend").select("store_cloud_id").where("store_id = ?", storeRenew.getStoreId()).one();
            try {
                DataSourceKey.use("jambox");
                //修改数据库
                DbChain.table("t_signContract_mechanism")
                        .set("end_time", storeRenew.getRenewDate())
                        .set("last_modified", loginUserInfo.getString("id"))
                        .where("deleted = 1")
                        .and("store_id = ?", storeExtend.getString("storeCloudId"))
                        .update();
                //添加到旧库`t_signContract_mechanism_reason`
                LocalDateTime now = LocalDateTime.now();
                Row row = Row.ofKey("reason_id", RowKey.AUTO);
                row.set("store_id", storeExtend.getString("storeCloudId"));
                row.set("reason", storeRenew.getRenewDesc());
                row.set("pic_url", storeRenew.getAnnexUrl());
                row.set("end_time", storeRenew.getRenewDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                row.set("deleted", 1);
                row.set("creation_time", now);
                row.set("creation_by", loginUserInfo.getString("id"));
                row.set("last_modification_date", now);
                row.set("last_modified", loginUserInfo.getString("id"));
            } finally {
                DataSourceKey.clear();
            }
            Jedis jedis = new Jedis("106.52.49.102", 6333);
            jedis.auth("Jambox.123*");
            jedis.select(1);
            jedis.set("endTime" + storeExtend.getString("storeCloudId"), storeRenew.getRenewDate().toString());
            jedis.expire("endTime" + storeRenew.getStoreId(), TimeoutUtils.toMillis(24, TimeUnit.MINUTES));
        }
    }
}
