Browse Source

账户清理提交

zhouzeyu@c-top.com.cn 3 years ago
parent
commit
5b818df0f8

+ 1 - 1
module-job-kuaishou/src/main/java/cn/com/ctop/job/kuaishou/handler/KuaiShouAccountCleanJob.java

@@ -22,7 +22,7 @@ public class KuaiShouAccountCleanJob {
      * @throws
      * @author ZZY
      */
-    @XxlJob("AccountClean")
+    @XxlJob("accountClean")
     public void execute() throws Exception {
         try {
             kuaiShouAccountCleanService.cleanAccount();

+ 21 - 9
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/controller/KuaiShouAccountCleanController.java

@@ -18,6 +18,7 @@ import javax.annotation.Resource;
 @RequestMapping("/accountClean")
 public class KuaiShouAccountCleanController {
 
+
     @Resource
     KuaiShouAccountCleanService kuaiShouAccountCleanService;
 
@@ -33,15 +34,26 @@ public class KuaiShouAccountCleanController {
     }
 
     /**
+     * 根据模板名称查询
+     *
+     * @param templateName
+     * @return
+     */
+    @GetMapping("/getTemplateNameSize")
+    public Result getTemplateName(@Param("templateName")String templateName){
+        return   kuaiShouAccountCleanService.getTemplateName(templateName);
+    }
+
+    /**
      * 查询模板列表
      *
-     * @param templateId 模板id  createUser创建人  userId当前登录人id
+     * @param templateName 模板名称  createUser创建人  userId当前登录人id
      * @return
      */
     @GetMapping("/getTemplateList")
-    public Result getTemplateList(@Param("templateId")String templateId,@Param("createUser")String createUser,@Param("userId")String userId,
+    public Result getTemplateList(@Param("templateName")String templateName,@Param("createUser")String createUser,@Param("userId")String userId,
                                   @Param("pageNum")String pageNum,@Param("pageSize")String pageSize  ){
-        return   kuaiShouAccountCleanService.getTemplateList(templateId,createUser,userId,pageNum,pageSize);
+        return   kuaiShouAccountCleanService.getTemplateList(templateName,createUser,userId,pageNum,pageSize);
     }
 
     /**
@@ -86,7 +98,7 @@ public class KuaiShouAccountCleanController {
      */
     @GetMapping("/getMyselfTemplateList")
     public Result getMyselfTemplateList(@Param("accountId")String accountId,@Param("userName")String userName,@Param("userId")String userId,
-                                  @Param("pageNum")String pageNum,@Param("pageSize")String pageSize  ){
+                                        @Param("pageNum")String pageNum,@Param("pageSize")String pageSize  ){
         return   kuaiShouAccountCleanService.getMyselfTemplateList(accountId,userName,userId,pageNum,pageSize);
     }
 
@@ -117,17 +129,17 @@ public class KuaiShouAccountCleanController {
     /**
      * 查询清理记录
      *
-     * @param userName 运营名称  accountId 账户id
+     * @param templateId 模板名称  userId 账户id
      * @return
      */
     @GetMapping("/getCleanUpLog")
-    public Result getCleanUpLog(@Param("userName")String userName,@Param("accountId")String accountId,
-                                  @Param("pageNum")String pageNum,@Param("pageSize")String pageSize  ){
-        return   kuaiShouAccountCleanService.getCleanUpLog(userName,accountId,pageNum,pageSize);
+    public Result getCleanUpLog(@Param("templateId")String templateId,@Param("userId")String userId,
+                                @Param("pageNum")String pageNum,@Param("pageSize")String pageSize  ){
+        return   kuaiShouAccountCleanService.getCleanUpLog(templateId,userId,pageNum,pageSize);
     }
 
     /**
-     * 查询清理记录
+     * 执行清理计划
      *
      * @param
      * @return

+ 4 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/entity/KuaiShouAccountCleanLogInfo.java

@@ -8,6 +8,10 @@ public class KuaiShouAccountCleanLogInfo {
     private  String id;
     //账户id
     private  String accountId;
+    //账户id
+    private  String templateId;
+    //账户id
+    private  String createTemplateId;
     //运营
     private  String userName;
     //操作类型  1-投放、2-暂停、3-删除

+ 11 - 4
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/mapper/KuaishouAccountCleanTemplateMapper.java

@@ -17,9 +17,9 @@ import java.util.Map;
 @Mapper
 public interface KuaishouAccountCleanTemplateMapper {
     //创建模板
-     void saveAccountCleanTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo);
+    void saveAccountCleanTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo);
     //根据id 创建人查询模板列表
-    List<KuaiShouAccountCleanTemplateInfo> getTemplateList(@Param("templateId")String templateId, @Param("createUser")String createUser, @Param("createId")String createId);
+    List<KuaiShouAccountCleanTemplateInfo> getTemplateList(@Param("templateName")String templateName, @Param("createUser")String createUser, @Param("createId")String createId);
     //根据id查询数据
     KuaiShouAccountCleanTemplateInfo getInfoById(@Param("templateId")String templateId);
     //查询账户关联模板个数
@@ -33,7 +33,7 @@ public interface KuaishouAccountCleanTemplateMapper {
     //根据id和accountId 删除关联表信息
     void removeBinding(@Param("templateId")String templateId,@Param("accountId")String accountId);
     //查询清理日志记录
-    List<KuaiShouAccountCleanLogInfo> getCleanUpLog(@Param("userName")String userName, @Param("accountId")String accountId);
+    List<KuaiShouAccountCleanLogInfo> getCleanUpLog(@Param("templateId")String templateId, @Param("userId")String userId);
 
     //根据账户id 运营名称 查询个人模板信息
     List<KuaiShouAccountCleanTemplateInfo> getMyselfTemplateList(@Param("accountId")String accountId, @Param("userName")String userName, @Param("createId")String createId);
@@ -41,10 +41,17 @@ public interface KuaishouAccountCleanTemplateMapper {
     //查询所有启用的模板
     List<KuaiShouAccountCleanTemplateInfo> getTemplateListBystatus();
     //根据规则模板查询相应组信息
-    List<String> getGroupMessage(@Param("template")KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo,@Param("list")List list, @Param("startDate")String startDate);
+    String getGroupMessage(@Param("template")KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo,@Param("optimizationObjective")String optimizationObjective, @Param("startDate")String startDate, @Param("unitId")String unitId);
+    List<Map> getGroupByAccount( @Param("accountId")String accountId);
+
     //保存操作日志
     void saveCleamLog(KuaiShouAccountCleanLogInfo kuaiShouAccountCleanLogInfo);
 
     Map<String,String> getUserNameByAccountId(@Param("accountId")String accountId);
 
+    String getUserRealName(@Param("userId")String userId);
+    /**
+     * 根据模板名称查询
+     */
+    int getTemplateName(@Param("templateName")String templateName);
 }

+ 146 - 165
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/mapper/xml/KuaishouAccountCleanTemplateMapper.xml

@@ -2,71 +2,75 @@
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="cn.com.ctop.kuaishou.modules.clean.mapper.KuaishouAccountCleanTemplateMapper">
 
-  <resultMap id="templateResultMap" type="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanTemplateInfo">
-    <id column="id" property="id"/>
-    <result column="template_name" property="templateName"/>
-    <result column="applied_media" property="appliedMedia"/>
-    <result column="clean_time" property="cleanTime"/>
-    <result column="optimization_objective" property="optimizationObjective"/>
-    <result column="charge" property="charge"/>
-    <result column="conversion" property="conversion"/>
-    <result column="promotion_group_status" property="promotionGroupStatus"/>
-    <result column="perform_operations" property="performOperations"/>
-    <result column="status" property="status"/>
-    <result column="create_user" property="createUser"/>
-    <result column="create_id" property="createId"/>
-    <result column="create_time" property="createTime"/>
-    <result column="account_id" property="accountId"/>
-    <result column="user_name" property="userName"/>
-    <result column="account_status" property="accountStatus"/>
-    <result column="account_name" property="accountName"/>
-  </resultMap>
-
-  <resultMap id="logResultMap" type="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanLogInfo">
-    <id column="id" property="id"/>
-    <result column="account_id" property="accountId"/>
-    <result column="user_name" property="userName"/>
-    <result column="operation_type" property="operationType"/>
-    <result column="create_time" property="createTime"/>
-    <result column="executive_information" property="executiveInformation"/>
-  </resultMap>
-  <!--保存清理模板-->
-  <insert id="saveAccountCleanTemplate" parameterType="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanTemplateInfo">
+
+    <resultMap id="templateResultMap" type="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanTemplateInfo">
+        <id column="id" property="id"/>
+        <result column="template_name" property="templateName"/>
+        <result column="applied_media" property="appliedMedia"/>
+        <result column="clean_time" property="cleanTime"/>
+        <result column="optimization_objective" property="optimizationObjective"/>
+        <result column="charge" property="charge"/>
+        <result column="conversion" property="conversion"/>
+        <result column="promotion_group_status" property="promotionGroupStatus"/>
+        <result column="perform_operations" property="performOperations"/>
+        <result column="status" property="status"/>
+        <result column="create_user" property="createUser"/>
+        <result column="create_id" property="createId"/>
+        <result column="create_time" property="createTime"/>
+        <result column="account_id" property="accountId"/>
+        <result column="user_name" property="userName"/>
+        <result column="account_status" property="accountStatus"/>
+        <result column="account_name" property="accountName"/>
+    </resultMap>
+
+    <resultMap id="logResultMap" type="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanLogInfo">
+        <id column="id" property="id"/>
+        <result column="account_id" property="accountId"/>
+        <result column="template_id" property="templateId"/>
+        <result column="create_template_id" property="createTemplateId"/>
+        <result column="user_name" property="userName"/>
+        <result column="operation_type" property="operationType"/>
+        <result column="create_time" property="createTime"/>
+        <result column="executive_information" property="executiveInformation"/>
+    </resultMap>
+    <!--保存清理模板-->
+    <insert id="saveAccountCleanTemplate" parameterType="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanTemplateInfo">
     insert into ctop_kuaishou_account_clean_template values (#{id},#{templateName},#{appliedMedia},#{cleanTime},#{optimizationObjective},#{charge},
-    #{conversion},#{performOperations},#{promotionGroupStatus},#{status},#{createUser},#{createId},#{createTime})
+    #{conversion},#{promotionGroupStatus},#{performOperations},#{status},#{createUser},#{createId},#{createTime})
   </insert>
 
-  <!--根据创建人查询模板-->
-  <select id="getTemplateList" resultMap="templateResultMap" >
-    select t.id,t.template_name,t.applied_media,t.create_user  from ctop_kuaishou_account_clean_template t
-    <where>
-      <if test="templateId!=null and templateId!=''">
-         t.id=#{templateId}
-      </if >
-
-      <if test="createUser!=null and createUser!=''">
-        and t.create_user=#{createUser}
-      </if >
-      <if test="createId!=null and createId!=''">
-        and t.create_id=#{createId}
-      </if >
-    </where>
-  </select>
-
-   <select id="getInfoById" parameterType="String" resultMap="templateResultMap">
+    <!--根据创建人查询模板-->
+    <select id="getTemplateList" resultMap="templateResultMap">
+        select t.id,t.template_name,t.applied_media,t.create_user,t.status from ctop_kuaishou_account_clean_template t
+        <where>
+            <if test="templateName!=null and templateName!=''">
+                t.template_name like CONCAT(CONCAT('%', #{templateName}), '%')
+            </if>
+
+            <if test="createUser!=null and createUser!=''">
+                and t.create_user=#{createUser}
+            </if>
+            <if test="createId!=null and createId!=''">
+                and t.create_id=#{createId}
+            </if>
+        </where>
+        order by create_time desc
+    </select>
+
+    <select id="getInfoById" parameterType="String" resultMap="templateResultMap">
       select  t.id,t.template_name,t.clean_time,t.optimization_objective,t.charge,t.conversion,t.promotion_group_status,t.perform_operations  from ctop_kuaishou_account_clean_template t
       where t.id=#{templateId}
    </select>
 
-  <select id="getAccountAssociatedSize" resultType="int">
+    <select id="getAccountAssociatedSize" resultType="int">
         select count(*) from ctop_kuaishou_account_clean_center where account_id=#{accountId}
   </select>
 
-  <insert id="savePushTemplateAssociated" >
+    <insert id="savePushTemplateAssociated">
     insert into ctop_kuaishou_account_clean_center (account_id,template_id,create_time)values (#{accountId},#{templateId},#{createTime})
   </insert>
 
-  <update id="updateTemplate" >
+    <update id="updateTemplate">
     update ctop_kuaishou_account_clean_template set
     template_name=#{templateName},clean_time=#{cleanTime},
     optimization_objective=#{optimizationObjective},charge=#{charge},
@@ -74,139 +78,116 @@
     perform_operations=#{performOperations}
     where id=#{id}
   </update>
-  <update id="updateTemplateStatus" >
+    <update id="updateTemplateStatus">
     update ctop_kuaishou_account_clean_template set status=#{status}
     where id=#{templateId}
   </update>
 
-  <delete id="removeBinding">
+    <delete id="removeBinding">
     delete  from ctop_kuaishou_account_clean_center where account_id=#{accountId} and template_id=#{templateId}
   </delete>
 
-  <select id="getCleanUpLog" parameterType="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanLogInfo" resultMap="logResultMap">
-    select *  from  ctop_kuaishou_account_clean_logs t
-    <where>
-      <if test="accountId!=null and accountId!=''">
-        t.account_id=#{accountId}
-      </if >
-
-      <if test="userName!=null and userName!=''">
-        and t.user_name like concat('%',#{userName},'%')
-      </if >
-    </where>
-  </select>
-
-
-
-
-  <!--根据账户id 运营名称 查询个人模板信息-->
-  <select id="getMyselfTemplateList" resultMap="templateResultMap" >
-    select t.status,t.id,t.template_name,t.applied_media,t2.account_id,t3.auth_name as account_name,t3.account_status,t3.user_name from ctop_kuaishou_account_clean_template t
-    LEFT JOIN ctop_kuaishou_account_clean_center t2 on t.id=t2.template_id
-    LEFT JOIN ctop_user_allocation t3 on t2.account_id=t3.account_id
-    <where>
-        t2.account_id is not null
-      <if test="accountId!=null and accountId!=''">
-        and t2.account_id=#{accountId}
-      </if >
-
-      <if test="userName!=null and userName!=''">
-        and t3.user_name like concat('%',#{userName},'%')
-      </if >
-      <if test="createId!=null and createId!=''">
-        and t.create_id=#{createId}
-      </if >
-    </where>
-
-  </select>
-
-  <select id="getTemplateListBystatus" resultMap="templateResultMap">
-       select  t.id,t.template_name,t.clean_time,t.optimization_objective,t.charge,t.conversion,t.promotion_group_status,t.perform_operations,t2.account_id  from ctop_kuaishou_account_clean_template t
+    <select id="getCleanUpLog" parameterType="cn.com.ctop.kuaishou.modules.clean.entity.KuaiShouAccountCleanLogInfo"
+            resultMap="logResultMap">
+        select * from ctop_kuaishou_account_clean_logs t
+        <where>
+            <if test="templateId!=null and templateId!=''">
+                t.template_id=#{templateId}
+            </if>
+
+            <if test="userId!=null and userId!=''">
+                and t.create_template_id =#{userId}
+            </if>
+        </where>
+    </select>
+
+
+    <!--根据账户id 运营名称 查询个人模板信息-->
+    <select id="getMyselfTemplateList" resultMap="templateResultMap">
+        select t.status,t.id,t.template_name,t.applied_media,t2.account_id,t3.auth_name as
+        account_name,t3.account_status,t.create_user as 'user_name' from ctop_kuaishou_account_clean_template t
+        LEFT JOIN ctop_kuaishou_account_clean_center t2 on t.id=t2.template_id
+        LEFT JOIN ctop_user_allocation t3 on t2.account_id=t3.account_id
+        <where>
+            t2.account_id is not null
+            <if test="accountId!=null and accountId!=''">
+                and t2.account_id=#{accountId}
+            </if>
+
+            <if test="userName!=null and userName!=''">
+                and t.create_user like concat('%',#{userName},'%')
+            </if>
+            <if test="createId!=null and createId!=''">
+                and t.create_id=#{createId}
+            </if>
+        </where>
+
+    </select>
+
+    <select id="getTemplateListBystatus" resultMap="templateResultMap">
+       select  t.id,t.template_name,t.clean_time,t.optimization_objective,t.charge,t.conversion,t.promotion_group_status,t.perform_operations,t2.account_id,t.create_id,t.create_user  from ctop_kuaishou_account_clean_template t
        left join  ctop_kuaishou_account_clean_center t2 on t.id=t2.template_id where t.status='0'
   </select>
 
-  <select id="getGroupMessage" resultType="java.lang.String">
+    <select id="getGroupMessage" resultType="String">
 
-      SELECT t.unit_id from ctop_kuaishou_group  t  LEFT JOIN ctop_kuaishou_report_daily_group  t2
+        SELECT t.unit_id from ctop_kuaishou_group t LEFT JOIN ctop_kuaishou_report_daily_group t2
         on t.unit_id=t2.unit_id
         where t.account_id=#{template.accountId}
         and t.group_create_time &lt;= #{startDate}
         and t2.stat_date &gt;= #{startDate}
-       <if test="template.promotionGroupStatus!=null and template.promotionGroupStatus!='' and template.promotionGroupStatus!='3'">
-          and t.put_status=#{template.promotionGroupStatus}
-       </if >
-         group by t.unit_id
+        and t.unit_id=#{unitId}
+        <if test='template.promotionGroupStatus!=null and template.promotionGroupStatus!="" and template.promotionGroupStatus!="3"'>
+            and t.put_status=#{template.promotionGroupStatus}
+        </if>
+        group by t.unit_id
         having sum(t2.charge) &lt;= #{template.charge}
-      <foreach item="item" index="index" collection="list"  open="and (" separator="or" close=")">
-
-          <if test='item=="activation"'>
-              /* 激活数*/
-              sum(t2.activation) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="bclick"'>
-              /*行为数*/
-              sum(t2.bclick) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="formSize"'>
-              /*表单数*/
-              sum(t2.form_count) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="pay"'>
-              /*付费数*/
-              sum(t2.event_pay) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="roi"'>
-              /*首日roi*/
-              sum(t2.event_pay_first_day_roi) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="evocativeApplication"'>
-              /*唤起应用*/
-              sum(t2.event_app_invoked) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="effectiveClues"'>
-              /*落地页有效线索*/
-              sum(t2.event_valid_clues) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="creditApp"'>
-              /*授信数APP*/
-              sum(t2.event_credit_grant_app) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="creditGrant"'>
-              /*落地页授信数*/
-              sum(t2.event_credit_grant_landing_page) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="finishedPieceApp"'>
-              /*完件数App*/
-              sum(t2.event_jin_jian_app) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="finishedPieceGrant"'>
-              /*落地页完件数*/
-              sum(t2.event_jin_jian_landing_page) &lt; #{template.conversion}
-          </if >
-
-          <if test='item=="registered"'>
-              /*注册*/
-              sum(t2.event_register) &lt; #{template.conversion}
-          </if >
-      </foreach>
+        <if test='optimizationObjective=="activation"'>
+            /* 激活数*/
+            and sum(t2.activation) &lt; #{template.conversion}
+        </if>
 
-  </select>
 
-  <select id="getUserNameByAccountId" resultType="Map">
+        <if test='optimizationObjective=="formSize"'>
+            /*表单数*/
+            and  sum(t2.form_count) &lt; #{template.conversion}
+        </if>
+
+        <if test='optimizationObjective=="pay"'>
+            /*付费数*/
+            and  sum(t2.event_pay) &lt; #{template.conversion}
+        </if>
+
+
+        <if test='optimizationObjective=="evocativeApplication"'>
+            /*唤起应用*/
+            and sum(t2.event_app_invoked) &lt; #{template.conversion}
+        </if>
+
+        <if test='optimizationObjective=="registered"'>
+            /*注册*/
+            and sum(t2.event_register) &lt; #{template.conversion}
+        </if>
+
+    </select>
+
+    <select id="getUserNameByAccountId" resultType="Map">
        select t.user_name as userName,t.auth_name as authName from ctop_user_allocation t where t.account_id=#{accountId}
   </select>
 
-  <insert id="saveCleamLog" >
-    insert into ctop_kuaishou_account_clean_logs (account_id,user_name,operation_type,create_time,executive_information) values (#{accountId},#{userName},#{operationType},#{createTime},#{executiveInformation})
+    <insert id="saveCleamLog">
+    insert into ctop_kuaishou_account_clean_logs (template_id,account_id,create_template_id,user_name,operation_type,create_time,executive_information) values (#{templateId},#{accountId},#{createTemplateId},#{userName},#{operationType},#{createTime},#{executiveInformation})
   </insert>
+
+    <select id="getUserRealName" resultType="String">
+        select t.realname from sys_user t where t.id=#{userId}
+    </select>
+
+    <select id="getTemplateName" parameterType="String" resultType="int">
+         select count(*) from ctop_kuaishou_account_clean_template t  where t.template_name=#{templateName}
+    </select>
+
+    <select id="getGroupByAccount" resultType="Map">
+        select  t.unit_id as 'unitId',t.ocpx_action_type  as 'type' from ctop_kuaishou_group t  where t.account_id=#{accountId}
+    </select>
 </mapper>

+ 9 - 2
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/service/KuaiShouAccountCleanService.java

@@ -61,10 +61,10 @@ public interface KuaiShouAccountCleanService {
     /**
      * 查询清理记录
      *
-     * @param userName 运营名称  accountId 账户id
+     * @param templateId 模板名称  userId 账户id
      * @return
      */
-    Result getCleanUpLog(String userName, String accountId, String pageNum, String pageSize);
+    Result getCleanUpLog(String templateId, String userId, String pageNum, String pageSize);
     /**
      * 查询个人清理模板列表
      *
@@ -81,4 +81,11 @@ public interface KuaiShouAccountCleanService {
      * @return
      */
     Result cleanAccount();
+    /**
+     * 根据模板名称查询
+     *
+     * @param templateName
+     * @return
+     */
+    Result getTemplateName(String templateName);
 }

+ 135 - 68
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/clean/service/impl/KuaiShouAccountCleanServiceImpl.java

@@ -11,6 +11,7 @@ import cn.com.ctop.kuaishou.modules.clean.service.KuaiShouAccountCleanService;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.jeecg.common.api.vo.Result;
 import org.jsoup.helper.StringUtil;
 import org.springframework.stereotype.Service;
@@ -18,6 +19,7 @@ import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 import java.text.SimpleDateFormat;
 import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 
 /**
@@ -29,6 +31,7 @@ import java.util.concurrent.atomic.AtomicReference;
 @Service
 @Slf4j
 public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanService {
+
     @Resource
     KuaishouAccountCleanTemplateMapper kuaishouAccountCleanTemplateMapper;
 
@@ -50,18 +53,21 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
     @Override
     public Result createCleanTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo) {
         Result result = new Result();
-        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
+        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Random rand = new Random();
         int id = 100000 + rand.nextInt(99900000);
+
         //设置6-8位数字
         kuaiShouAccountCleanTemplateInfo.setId(String.valueOf(id));
         //设置应用媒体 固定写死
         kuaiShouAccountCleanTemplateInfo.setAppliedMedia("快手");
         //未绑定账户  设置暂停状态
-        kuaiShouAccountCleanTemplateInfo.setStatus(String.valueOf(1));
+        kuaiShouAccountCleanTemplateInfo.setStatus(String.valueOf(0));
         //设置创建日期
         kuaiShouAccountCleanTemplateInfo.setCreateTime(sd.format(new Date()));
         try {
+            String userRealName = kuaishouAccountCleanTemplateMapper.getUserRealName(kuaiShouAccountCleanTemplateInfo.getCreateId());
+            kuaiShouAccountCleanTemplateInfo.setCreateUser(userRealName);
             kuaishouAccountCleanTemplateMapper.saveAccountCleanTemplate(kuaiShouAccountCleanTemplateInfo);
             result.success("创建模板成功");
         } catch (Exception e) {
@@ -74,11 +80,11 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
     /**
      * 查询模板列表
      *
-     * @param templateId 模板id  createUser创建人
+     * @param templateName 模板名称  createUser创建人
      * @return
      */
     @Override
-    public Result getTemplateList(String templateId, String createUser, String userId, String pageNum, String pageSize) {
+    public Result getTemplateList(String templateName, String createUser, String userId, String pageNum, String pageSize) {
         Result result = new Result();
         PageHelper pageHelper = new PageHelper();
         List<KuaiShouAccountCleanTemplateInfo> templateList = new ArrayList<>();
@@ -88,10 +94,10 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
             PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
             if (roleCode != null && roleCode.equals("admin")) {
                 //管理员查询全部
-                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateId, createUser, null);
+                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateName, createUser, null);
             } else {
                 //其他角色查询自己拥有的
-                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateId, createUser, userId);
+                templateList = kuaishouAccountCleanTemplateMapper.getTemplateList(templateName, createUser, userId);
             }
             PageInfo pageInfo = new PageInfo(templateList);
             result.success("查询成功");
@@ -162,7 +168,7 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
     public Result updateTemplate(KuaiShouAccountCleanTemplateInfo kuaiShouAccountCleanTemplateInfo) {
         Result result = new Result();
         try {
-            if (!StringUtil.isBlank(kuaiShouAccountCleanTemplateInfo.getId())) {
+            if (!StringUtils.isBlank(kuaiShouAccountCleanTemplateInfo.getId())) {
                 kuaishouAccountCleanTemplateMapper.updateTemplate(kuaiShouAccountCleanTemplateInfo);
                 result.success("修改成功");
             } else {
@@ -222,11 +228,20 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
     }
 
     @Override
-    public Result getCleanUpLog(String userName, String accountId, String pageNum, String pageSize) {
+    public Result getCleanUpLog(String templateId, String userId, String pageNum, String pageSize) {
         Result result = new Result();
+        List<KuaiShouAccountCleanLogInfo> cleanUpLog = new ArrayList<>();
         try {
+            //查询当前登录人角色
+            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
+            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
+            if (roleCode != null && roleCode.equals("admin")) {
+                cleanUpLog = kuaishouAccountCleanTemplateMapper.getCleanUpLog(templateId, null);
+            } else {
+                cleanUpLog = kuaishouAccountCleanTemplateMapper.getCleanUpLog(templateId, userId);
+            }
             PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
-            List<KuaiShouAccountCleanLogInfo> cleanUpLog = kuaishouAccountCleanTemplateMapper.getCleanUpLog(userName, accountId);
+
             PageInfo pageInfo = new PageInfo(cleanUpLog);
             result.success("查询成功");
             result.setResult(pageInfo);
@@ -279,81 +294,133 @@ public class KuaiShouAccountCleanServiceImpl implements KuaiShouAccountCleanServ
     public Result cleanAccount() {
         Result result = new Result();
         SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Map optimizationObjectiveMap = new HashMap();
+        //优化目标 activation:激活数 bclick:行为数  formSize :表单数 pay:付费  roi:首日roi   evocativeApplication:唤起应用
+        // effectiveClues:有效线索 creditApp:授信-APP creditGrant:授信-落地页  finishedPieceApp:完件数-APP  finishedPieceGrant:完件数-落地页  registered:注册
+        optimizationObjectiveMap.put("180", "activation");
+        optimizationObjectiveMap.put("53", "formSize");
+        optimizationObjectiveMap.put("190", "pay");
+        optimizationObjectiveMap.put("324", "evocativeApplication");
+        optimizationObjectiveMap.put("396", "registered");
         try {
             //查询需要执行的规则模板
             List<KuaiShouAccountCleanTemplateInfo> templateListBystatus = kuaishouAccountCleanTemplateMapper.getTemplateListBystatus();
             if (!templateListBystatus.isEmpty()) {
                 templateListBystatus.stream().forEach(ob -> {
-                    //获取各项优化目标
-                    List<String> optimizationObjectiveList = Arrays.asList(ob.getOptimizationObjective().split(";"));
-                    //获取清理时间范围
-                    String cleanTime = ob.getCleanTime();
-                    //计算最早清理时间
-                    Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
-                    calendar.add(Calendar.DATE, -Integer.parseInt(cleanTime));
-                    String startDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
-                    //查询符合模板规则的组
-                    List<String> groupMessage = kuaishouAccountCleanTemplateMapper.getGroupMessage(ob, optimizationObjectiveList, startDate);
-                    AtomicReference<Boolean> falg = new AtomicReference<>(true);
-                    if (!groupMessage.isEmpty()) {
-                        //获取Token
-                        CtopOauthToken ctopOauthToken = ctopOauthTokenMapper.selectByAccountId(Long.parseLong(ob.getAccountId()));
-                        if (ctopOauthToken != null) {
-                            groupMessage.stream().forEach(item -> {
-                                //修改广告组状态
-                                Map<String, Object> resultMap = iKuaiShouUpdateService.updateUnitStatus(ctopOauthToken.getAccessToken(), Long.parseLong(ob.getAccountId()), Long.parseLong(item), Integer.parseInt(ob.getPerformOperations()), null);
-                                Boolean resultFlag = (Boolean) resultMap.get("success");
-                                //判断有没有失败
-                                if (!resultFlag) {
-                                    falg.set(false);
+                    AtomicInteger count= new AtomicInteger();
+                    if (ob.getAccountId() != null) {
+                        StringBuilder unitIds = new StringBuilder();
+                        //获取各项优化目标
+                        List<String> optimizationObjectiveList = Arrays.asList(ob.getOptimizationObjective().split(","));
+                        //获取清理时间范围
+                        String cleanTime = ob.getCleanTime();
+                        //计算最早清理时间
+                        Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
+                        calendar.add(Calendar.DATE, -Integer.parseInt(cleanTime));
+                        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
+                        AtomicReference<Boolean> falg = new AtomicReference<>(true);
+                        //查询改账户下所有组
+                        List<Map> groupByAccount = kuaishouAccountCleanTemplateMapper.getGroupByAccount(ob.getAccountId());
+                        if (!groupByAccount.isEmpty()) {
+                            groupByAccount.stream().forEach(obj -> {
+                                if (obj.get("unitId") != null && obj.get("type") != null) {
+                                    String unitId = Long.toString((Long) obj.get("unitId")) ;
+                                    //OCPM
+                                    String type = Integer.toString((Integer) obj.get("type")) ;
+                                    if(optimizationObjectiveMap.get(type)!=null){
+                                        String optimizationObjective= (String) optimizationObjectiveMap.get(type);
+                                        //查询组是否符合清理规则
+                                        String groupMessage = kuaishouAccountCleanTemplateMapper.getGroupMessage(ob, optimizationObjective, startDate,unitId);
+                                        if(groupMessage!=null){
+                                            count.getAndIncrement();
+                                            //符合清理规则清理
+                                            //获取Token
+                                            CtopOauthToken ctopOauthToken = ctopOauthTokenMapper.selectByAccountId(Long.parseLong(ob.getAccountId()));
+                                            if (ctopOauthToken != null) {
+                                                //修改广告组状态
+                                                Map<String, Object> resultMap = iKuaiShouUpdateService.updateUnitStatus(ctopOauthToken.getAccessToken(), Long.parseLong(ob.getAccountId()), Long.parseLong(unitId), Integer.parseInt(ob.getPerformOperations()), null);
+                                                Boolean resultFlag = (Boolean) resultMap.get("success");
+                                                //判断有没有失败
+                                                if (resultFlag) {
+                                                    //清理成功
+                                                    unitIds.append(unitId).append(",");
+                                                    log.info("组"+unitId+"已被清理");
+                                                }else {
+                                                    //清理失败
+                                                    log.info("组"+unitId+"清理失败:{}",resultMap.get("message"));
+                                                    falg.set(false);
+                                                }
+                                            }
+                                        }
+                                    }
+
                                 }
                             });
-
                         }
-                    }
-                    if (!groupMessage.isEmpty() && falg.get()) {
-                        //修改成功插入日志记录
-                        KuaiShouAccountCleanLogInfo kuaiShouAccountCleanLogInfo = new KuaiShouAccountCleanLogInfo();
-                        //设置账户id
-                        kuaiShouAccountCleanLogInfo.setAccountId(ob.getAccountId());
-                        // 1-投放、2-暂停、3-删除
-                        kuaiShouAccountCleanLogInfo.setOperationType(ob.getPerformOperations());
-                        //设置运营
-                        Map<String, String> map = kuaishouAccountCleanTemplateMapper.getUserNameByAccountId(ob.getAccountId());
-                        String authName = "";
-                        if (map != null) {
-                            kuaiShouAccountCleanLogInfo.setUserName(map.get("userName"));
-                            authName = map.get("authName");
-                        }
-                        //设置时间
-                        kuaiShouAccountCleanLogInfo.setCreateTime(sd.format(new Date()));
-                        StringBuilder unitIds = new StringBuilder();
-                        groupMessage.stream().forEach(unid -> {
-                            unitIds.append(unid).append(",");
-                        });
-                        //操作类型
-                        String operationType = null;
-                        if (ob.getPerformOperations().equals("2")) {
-                            operationType = "暂停";
-                        }
-                        if (ob.getPerformOperations().equals("3")) {
-                            operationType = "删除";
+
+
+                        if (count.get()>0 && falg.get()) {
+                            //修改成功插入日志记录
+                            KuaiShouAccountCleanLogInfo kuaiShouAccountCleanLogInfo = new KuaiShouAccountCleanLogInfo();
+                            //设置账户id
+                            kuaiShouAccountCleanLogInfo.setAccountId(ob.getAccountId());
+                            // 1-投放、2-暂停、3-删除
+                            kuaiShouAccountCleanLogInfo.setOperationType(ob.getPerformOperations());
+                            //设置运营
+//                            Map<String, String> map = kuaishouAccountCleanTemplateMapper.getUserNameByAccountId(ob.getAccountId());
+//                            String authName = "";
+//                            if (map != null) {
+//                                kuaiShouAccountCleanLogInfo.setUserName(map.get("userName"));
+//                                authName = map.get("authName");
+//                            }
+                            //设置时间
+                            kuaiShouAccountCleanLogInfo.setCreateTime(sd.format(new Date()));
+                            //操作类型
+                            String operationType = null;
+                            if (ob.getPerformOperations().equals("2")) {
+                                operationType = "暂停";
+                            }
+                            if (ob.getPerformOperations().equals("3")) {
+                                operationType = "删除";
+                            }
+                            //执行信息
+                            String textMessage = "清理规则执行:  账户:" + ob.getAccountId() + ", 授权名称: " + ob.getCreateUser() + ",推广组:" + unitIds + "已经被清理规则" + operationType;
+                            kuaiShouAccountCleanLogInfo.setExecutiveInformation(textMessage);
+                            kuaiShouAccountCleanLogInfo.setTemplateId(ob.getId());
+                            kuaiShouAccountCleanLogInfo.setCreateTemplateId(ob.getCreateId());
+                            kuaiShouAccountCleanLogInfo.setUserName(ob.getCreateUser());
+                            kuaishouAccountCleanTemplateMapper.saveCleamLog(kuaiShouAccountCleanLogInfo);
                         }
-                        //执行信息
-                        String textMessage = "清理规则执行:  账户:" + ob.getAccountId() + ", 授权名称: " + authName + ",推广组:" + unitIds + "已经被清理规则" + operationType;
-                        kuaiShouAccountCleanLogInfo.setExecutiveInformation(textMessage);
-                        kuaishouAccountCleanTemplateMapper.saveCleamLog(kuaiShouAccountCleanLogInfo);
                     }
-
                 });
             }
 
-            result.success("修改成功");
+            result.success("执行计划成功");
         } catch (Exception e) {
-            log.info("修改失败:{}", e.toString());
-            result.error500("修改失败");
+            log.info("执行计划失败:{}", e.toString());
+            result.error500("执行计划失败");
         }
         return result;
     }
 
+    /**
+     * 根据模板名称查询
+     *
+     * @param templateName
+     * @return
+     */
+    @Override
+    public Result getTemplateName(String templateName) {
+        Result result = new Result();
+        try {
+            int number = kuaishouAccountCleanTemplateMapper.getTemplateName(templateName.trim());
+            result.setResult(number);
+        } catch (Exception e) {
+            log.info("查询失败:{}", e.toString());
+            result.error500("查询失败");
+        }
+        return result;
+    }
+
+
 }