package com.engine.htsc.cube.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.engine.core.impl.Service;
import com.engine.htsc.cube.service.PortalFavoriteService;
import com.engine.htsc.cube.task.FavoriteTask;
import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import com.engine.htsc.payment.util.AssertUtil;
import com.engine.htsc.payment.util.CommonAPI;
import org.joda.time.DateTime;
import weaver.conn.RecordSetTrans;
import weaver.hrm.resource.ResourceComInfo;

import java.util.Map;

public class PortalFavoriteServiceImpl extends Service implements PortalFavoriteService {

  private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(PortalFavoriteServiceImpl.class);
  private final FavoriteTask favoriteTask = new FavoriteTask();

  /**
   * @param params
   * @param operateType
   * @return
   * @see FavoriteTask#syncFavorite(java.lang.String, java.lang.Integer, java.lang.Integer)
   */
  @Override
  public String favouriteOperate(Map<String, String> params, String operateType) throws Exception {
    AssertUtil.isEmpty(params.get("workCode"), "工号workCode必填");
    AssertUtil.isEmpty(params.get("ids"), "收藏id必填");
    logger.info(String.format("operateType:%s, params:%s", operateType, JSON.toJSONString(params)));
    String uid = CommonAPI.querySingleFieldWithPlaceholder(
        "select id from hrmresource where accounttype = 0 and workcode = ?",
        "id", params.get("workCode"));
    if ("add".equals(operateType)) {
      updateDB(uid, params.get("ids"), 1);
    }
    if ("cancel".equals(operateType)) {
      updateDB(uid, params.get("ids"), 0);
    }
    return "success";
  }

  private void updateDB(String uid, String billid, Integer isCancelCollect) throws Exception {
    RecordSetTrans rst = new RecordSetTrans();
    //1.插入数据前删除该条数据
    String deleteData = "delete from uf_gwky_dt6 where ry = ? and mainid = ?";
    rst.executeUpdate(deleteData, uid, billid);
    //2.根据isCancelCollect更新数据
    String insertDatas = "";
    if (isCancelCollect == 0) { //是
      insertDatas = "insert into uf_gwky_dt6(mainid,ry,sfqxsc,qxsj) values(?,?,?,?)";
    } else {
      insertDatas = "insert into uf_gwky_dt6(mainid,ry,sfqxsc,scsj) values(?,?,?,?)";
    }
    rst.executeUpdate(insertDatas, billid, uid, isCancelCollect, DateUtil.now());
  }
}
