package com.engine.htsc.cube.task;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.cube.entity.Favorite;
import com.engine.htsc.cube.service.impl.PortalFavoriteServiceImpl;
import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import com.engine.htsc.payment.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.util.Arrays;
import java.util.Map;

public class FavoriteTask {

  private static final PaymentLogger log = PaymentLoggerFactory.getLogger(FavoriteTask.class);
  private static final String SOURCE_TYPE_CDOE = "oadocandnotice";
  private final PropBean propBean = new PropBean();

  /**
   * 批量同步
   *
   * @param user            工号
   * @param billids         以,分割的建模表id
   * @param isCancelCollect 1收藏，0取消
   */
  public void batchSyncFavorite(String user, String billids, Integer isCancelCollect) {
    try {
      log.info(String.format("batchSyncFavorite user:%s, billids:%s, isCancelCollect:%s", user,
          billids, isCancelCollect));
      if (StringUtils.isBlank(billids)) {
        return;
      }
      Arrays.stream(billids.split(",")).forEach(b -> syncFavorite(user, Integer.parseInt(b), isCancelCollect));
    } catch (Exception e) {
      //为了不影响原来公文收藏接口，故吞掉异常
      log.error(e.getMessage());
      e.printStackTrace();
    }
  }

  public void syncFavorite(String user, Integer billid, Integer isCancelCollect) {
    log.info(String.format("同步门户收藏，use：%s，billid：%s，isCancelCollect：%s", user, billid, isCancelCollect));
    try {
      Favorite favorite = getFavorite(user, billid, isCancelCollect);
      validateFavorite(favorite);
      //收藏
      if (isCancelCollect == 1) {
        createFavorite(favorite);
      }
      //取消
      if (isCancelCollect == 0) {
        cancelFavorite(favorite);
      }
    } catch (Exception e) {
      //为了不影响原来公文收藏接口，故吞掉异常
      log.error(e.getMessage());
      e.printStackTrace();
    }
  }


  /**
   * 收藏
   *
   * @param favorite 收藏
   * @throws Exception
   */
  public void createFavorite(Favorite favorite) throws Exception {
    String url = new PropBean().getPropName("XPFavoriteBaseUrl") + "/addFavourite";
    HTUtil htUtil = new HTUtil();
    Map<String, String> appHeader = htUtil.getAppHeader();
    HttpUtil.postApplicationJson(url, JSON.toJSONString(favorite), appHeader);
  }

  /**
   * 取消收藏
   *
   * @param favorite 收藏
   * @throws Exception
   */
  public void cancelFavorite(Favorite favorite) throws Exception {
    String url = new PropBean().getPropName("XPFavoriteBaseUrl") + "/cancelFavourite";
    HTUtil htUtil = new HTUtil();
    Map<String, String> appHeader = htUtil.getAppHeader();
    HttpUtil.postApplicationJson(url, JSON.toJSONString(favorite), appHeader);
  }


  /**
   * 校验
   *
   * @param favorite 收藏
   */
  private void validateFavorite(Favorite favorite) {
    Validate.notBlank(favorite.getSourceId(), "资源主键为空");
//        Validate.notBlank(favorite.getSourceSystemCode(), "资源来源系统标识为空");
    Validate.notBlank(favorite.getSourceAuthor(), "作者姓名为空");
    Validate.notBlank(favorite.getUserId(), "收藏人工号为空");
    Validate.notBlank(favorite.getSourceTitle(), "标题为空");
    Validate.notBlank(favorite.getSourceTypeCode(), "来源类型");
    Validate.notBlank(favorite.getSourcePCUrl(), "pc端url链接");
    Validate.notBlank(favorite.getSourceMobileUrl(), "mobile端url链接");
  }


  /**
   * 获取收藏
   *
   * @param user            用户信息
   * @param billid          主表id
   * @param isCancelCollect 1收藏，0取消
   * @return 收藏
   * @throws Exception
   */
  private Favorite getFavorite(String user, Integer billid, Integer isCancelCollect) throws Exception {
    Favorite favorite = new Favorite();
    favorite.setUserId(user); //处理人工号
    favorite.setSourceId(String.valueOf(billid)); //来源唯一编号
    //获取拟稿人、类型、标题, formmodeid
    RecordSet rs = new RecordSet();
    String getGWInfoSql = "select ngr, gwgg, bt, formmodeid from uf_gwky where id = ?";
    rs.executeQuery(getGWInfoSql, billid);
    if (rs.next()) {
      String ngrId = Util.null2String(rs.getString("ngr"));
      ResourceComInfo resourceComInfo = new ResourceComInfo();
      String ngr = resourceComInfo.getLastname(ngrId);//创建人
      String gwgg = Util.null2String(rs.getString("gwgg"));//公文、公告类型
      String bt = Util.null2String(rs.getString("bt"));
      favorite.setSourceAuthor(ngr); //作者
      favorite.setSourceTypeCode(SOURCE_TYPE_CDOE); //类型
      favorite.setSourceSystemCode("WEAVER"); // 来源系统租户id
      favorite.setSourceTitle(bt); //标题
    }

    // 看阅pc和移动端地址
    favorite.setSourcePCUrl(propBean.getPropName("kanyuePcUrl") + billid);
    favorite.setSourceMobileUrl(propBean.getPropName("kanyueMobileUrl") + billid);
    return favorite;
  }

}
