Browse Source

定向包~接口开发

zhaoxian 4 năm trước cách đây
mục cha
commit
a44d16c309

+ 69 - 32
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/controller/KuaishouDirectionalPackageController.java

@@ -13,6 +13,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.github.pagehelper.PageHelper;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
@@ -144,19 +145,22 @@ public class KuaishouDirectionalPackageController {
      * @throws
      * @author ZHAOXA
      */
-    @GetMapping(value = "/getHistory")
-    public Result<Object> getHistory(Long projectId, Long templateId,
-                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
-                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
+    @PostMapping(value = "/updatePopulation")
+    public Result<Object> updatePopulation(@RequestBody JSONObject requestJson) {
         try {
-            if (Check.isNull(templateId)) {
+            if (Check.isNull(requestJson.getString("id"))) {
                 return Result.error("请选择人群包");
             }
-            if (Check.isNull(projectId)) {
-                return Result.error("请选择项目");
+            if (Check.isNull(requestJson.getLong("accountId"))) {
+                return Result.error("请选择账户");
             }
-
-            return kuaishouDirectionalPackageService.getHistory(projectId, templateId, pageNo, pageSize);
+            if (Check.isNull(requestJson.getLong("templateId"))) {
+                return Result.error("未获取到定向包ID");
+            }
+            if (Check.isNull(requestJson.getString("templateName"))) {
+                return Result.error("未获取到定向包名称");
+            }
+            return kuaishouDirectionalPackageService.updatePopulation(requestJson);
         } catch (Exception e) {
             log.error("查询异常,", e.getMessage());
             e.printStackTrace();
@@ -173,14 +177,18 @@ public class KuaishouDirectionalPackageController {
      * @author ZHAOXA
      */
     @GetMapping(value = "/getAccountByProjectId")
-    public Result<Object> getAccountByProjectId(Long projectId,
+    public Result<Object> getAccountByProjectId(Long projectId, String id,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
         try {
             if (Check.isNull(projectId)) {
                 return Result.error("请选择项目");
             }
-            return kuaishouDirectionalPackageService.getAccountByProjectId(projectId, pageNo, pageSize);
+            if (Check.isNull(id)) {
+                return Result.error("请选择定向包");
+            }
+            PageHelper.startPage(pageNo, pageSize);
+            return kuaishouDirectionalPackageService.getAccountByProjectId(projectId,id);
         } catch (Exception e) {
             log.error("查询异常,", e.getMessage());
             e.printStackTrace();
@@ -201,15 +209,11 @@ public class KuaishouDirectionalPackageController {
             if (Check.isNull(requestJson.getString("templateName"))) {
                 return Result.error("定向模板名称为必传项");
             }
-            Long accountId = requestJson.getLong("accountId");
+            Long accountId = requestJson.getLong("projectId");
             if (Check.isNull(accountId)) {
                 return Result.error("请选择账户id");
             }
-            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
-            if (Check.isNull(oauthToken)) {
-                return Result.error("未获取到账户信息");
-            }
-            return kuaishouDirectionalPackageService.createDirectionalPackage(oauthToken.getAccessToken(), requestJson);
+            return kuaishouDirectionalPackageService.createDirectionalPackage(requestJson);
         } catch (Exception e) {
             log.error("创建定向包失败", e);
             return Result.error("创建失败" + e.getMessage());
@@ -256,25 +260,53 @@ public class KuaishouDirectionalPackageController {
      */
     @PostMapping(value = "/pushDirectionalPackage")
     public Result<Object> pushDirectionalPackage(@RequestBody JSONObject requestJson) {
-        Result<JSONObject> result = new Result<>();
         try {
             String id = requestJson.getString("id");
-            JSONArray accountIds = requestJson.getJSONArray("accountIds");
+            JSONArray datas = requestJson.getJSONArray("datas");
             if (Check.isNull(id)) {
                 return Result.error("请选择人群包");
             }
-            if (Check.isNull(accountIds)) {
+            if (Check.isNull(datas)) {
                 return Result.error("请选择推送账户");
             }
-            return kuaishouDirectionalPackageService.pushDirectionalPackage(id, accountIds);
+            return kuaishouDirectionalPackageService.pushDirectionalPackage(id, datas);
         } catch (Exception e) {
-            result.setSuccess(false);
-            result.setMessage(e.getMessage());
+            log.error("推送定向包异常", e);
         }
         return Result.error("上传失败");
     }
 
     /**
+     * 查询推送结果
+     *
+     * @param
+     * @return
+     */
+    @PostMapping(value = "/queryPushResults")
+    public Result<Object> queryPushResults(@RequestBody JSONObject requestJson) {
+        try {
+            String id = requestJson.getString("id");
+            JSONArray accountIds = requestJson.getJSONArray("accountIds");
+            if (Check.isNull(id)) {
+                return Result.error("请选择人群包");
+            }
+            Integer pageNo = requestJson.getInteger("pageNo");
+            Integer pageSize = requestJson.getInteger("pageSize");
+            if (Check.isNull(pageNo)) {
+                pageNo = 1;
+            }
+            if (Check.isNull(pageSize)) {
+                pageSize = 10;
+            }
+            PageHelper.startPage(pageNo, pageSize);
+            return kuaishouDirectionalPackageService.queryPushResults(id, accountIds);
+        } catch (Exception e) {
+            log.error("查询推送结果异常", e);
+        }
+        return Result.error("查询失败");
+    }
+
+    /**
      * 删除定向模板
      *
      * @param
@@ -283,12 +315,16 @@ public class KuaishouDirectionalPackageController {
      * @author ZHAOXA
      */
     @GetMapping(value = "/delete")
-    public Result<Object> delete(Long accountId, Long templateId) {
+    public Result<Object> delete(String id) {
         try {
-            return kuaishouDirectionalPackageService.delete(accountId, templateId);
+            boolean b = kuaishouDirectionalPackageService.removeById(id);
+            if (b) {
+                return Result.ok("删除成功");
+            }
         } catch (Exception e) {
-            return Result.error("删除失败!");
+            log.error("删除异常", e);
         }
+        return Result.error("删除失败!");
     }
 
     /**
@@ -365,16 +401,17 @@ public class KuaishouDirectionalPackageController {
     @AutoLog(value = "自动投放-定向包详情-通过id查询")
     @ApiOperation(value = "自动投放-定向包详情-通过id查询", notes = "自动投放-定向包详情-通过id查询")
     @GetMapping(value = "/queryById")
-    public Result<KuaishouDirectionalPackage> queryById(@RequestParam(name = "id", required = true) String id) {
-        Result<KuaishouDirectionalPackage> result = new Result<>();
+    public Result<Object> queryById(@RequestParam(name = "id", required = true) String id) {
         KuaishouDirectionalPackage kuaishouDirectionalPackage = kuaishouDirectionalPackageService.getById(id);
         if (kuaishouDirectionalPackage == null) {
-            result.error500("未找到对应实体");
+            return Result.error("未找到对应实体");
         } else {
-            result.setResult(kuaishouDirectionalPackage);
-            result.setSuccess(true);
+            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(kuaishouDirectionalPackage)).toJavaObject(JSONObject.class);
+            if (!Check.isNull(data.getString("keyword"))) {
+                data.put("keyword", data.getJSONArray("keyword"));
+            }
+            return Result.ok(data);
         }
-        return result;
     }
 
     /**

+ 0 - 19
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/entity/KuaishouDirectionalPackage.java

@@ -38,7 +38,6 @@ public class KuaishouDirectionalPackage {
      */
     private int dataStatus;
 
-    private String message;
     private String templateName;
     /**
      * 地域
@@ -161,24 +160,6 @@ public class KuaishouDirectionalPackage {
     @ApiModelProperty(value = "APP行为-按APP名称")
     private String appIds;
     /**
-     * 定向人群包
-     */
-    @Excel(name = "定向人群包", width = 15)
-    @ApiModelProperty(value = "定向人群包")
-    private String population;
-    /**
-     * 付费人群包
-     */
-    @Excel(name = "付费人群包", width = 15)
-    @ApiModelProperty(value = "付费人群包")
-    private String paidAudience;
-    /**
-     * 排除人群包
-     */
-    @Excel(name = "排除人群包", width = 15)
-    @ApiModelProperty(value = "排除人群包")
-    private String excludePopulation;
-    /**
      * 开启智能扩量 默认为0,为1时打开智能扩量,其他数值报错;关闭智能扩量时,以下三个字段必须为0
      */
     @Excel(name = "开启智能扩量 默认为0,为1时打开智能扩量,其他数值报错;关闭智能扩量时,以下三个字段必须为0", width = 15)

+ 73 - 45
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/entity/KuaishouDirectionalTemplateRel.java

@@ -1,81 +1,109 @@
 package cn.com.ctop.kuaishou.modules.ai.entity;
 
-import java.io.Serializable;
-import java.util.Date;
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
-import com.baomidou.mybatisplus.annotation.TableField;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.experimental.Accessors;
-import com.fasterxml.jackson.annotation.JsonFormat;
-import org.springframework.format.annotation.DateTimeFormat;
 import org.jeecgframework.poi.excel.annotation.Excel;
 
+import java.util.Date;
+
 /**
  * 自动投放-定向包详情关系表
+ *
  * @author jeecg-boot
- * @date   2021-04-25
  * @version V1.0
+ * @date 2021-04-25
  */
 @Data
 @TableName("ctop_kuaishou_directional_template_rel")
 @EqualsAndHashCode(callSuper = false)
 @Accessors(chain = true)
-@ApiModel(value="ctop_kuaishou_directional_template_rel对象", description="自动投放-定向包详情关系表")
+@ApiModel(value = "ctop_kuaishou_directional_template_rel对象", description = "自动投放-定向包详情关系表")
 public class KuaishouDirectionalTemplateRel {
-    
-	/**id*/
-	@TableId(type = IdType.AUTO)
+
+    /**
+     * id
+     */
+    @TableId(type = IdType.AUTO)
     @ApiModelProperty(value = "id")
-	private Long id;
-	/**本地定向模板ID*/
-	@Excel(name = "本地定向模板ID", width = 15)
+    private Long id;
+    /**
+     * 本地定向模板ID
+     */
+    @Excel(name = "本地定向模板ID", width = 15)
     @ApiModelProperty(value = "本地定向模板ID")
-	private String dirId;
-	/**项目ID*/
-	@Excel(name = "项目ID", width = 15)
+    private String dirId;
+    /**
+     * 项目ID
+     */
+    @Excel(name = "项目ID", width = 15)
     @ApiModelProperty(value = "项目ID")
-	private Long projectId;
-	/**定向模板id*/
-	@Excel(name = "定向模板id", width = 15)
+    private Long projectId;
+    /**
+     * 0无效,1有效
+     */
+    private Integer dataStatus;
+    /**
+     * 定向模板id
+     */
+    @Excel(name = "定向模板id", width = 15)
     @ApiModelProperty(value = "定向模板id")
-	private Long templateId;
-	/**人群包名*/
-	@Excel(name = "人群包名", width = 15)
+    private Long templateId;
+    /**
+     * 人群包名
+     */
+    @Excel(name = "人群包名", width = 15)
     @ApiModelProperty(value = "人群包名")
-	private String templateName;
-	/**账户ID*/
-	@Excel(name = "账户ID", width = 15)
+    private String templateName;
+    /**
+     * 账户ID
+     */
+    @Excel(name = "账户ID", width = 15)
     @ApiModelProperty(value = "账户ID")
-	private Long relId;
-	/**绑定类型,account 账户,unit 组*/
-	@Excel(name = "绑定类型,account 账户,unit 组", width = 15)
+    private Long relId;
+    /**
+     * 绑定类型,account 账户,unit 组
+     */
+    @Excel(name = "绑定类型,account 账户,unit 组", width = 15)
     @ApiModelProperty(value = "绑定类型,account 账户,unit 组")
-	private String relType;
-	/**排除人群包*/
-	@Excel(name = "排除人群包", width = 15)
+    private String relType;
+    /**
+     * 排除人群包
+     */
+    @Excel(name = "排除人群包", width = 15)
     @ApiModelProperty(value = "排除人群包")
-	private String excludePopulation;
-	/**付费人群包*/
-	@Excel(name = "付费人群包", width = 15)
+    private String excludePopulation;
+    /**
+     * 付费人群包
+     */
+    @Excel(name = "付费人群包", width = 15)
     @ApiModelProperty(value = "付费人群包")
-	private String paidAudience;
-	/**定向人群包*/
-	@Excel(name = "定向人群包", width = 15)
+    private String paidAudience;
+    /**
+     * 定向人群包
+     */
+    @Excel(name = "定向人群包", width = 15)
     @ApiModelProperty(value = "定向人群包")
-	private String population;
-	/**结果说明*/
-	@Excel(name = "结果说明", width = 15)
+    private String population;
+    /**
+     * 结果说明
+     */
+    @Excel(name = "结果说明", width = 15)
     @ApiModelProperty(value = "结果说明")
-	private String message;
-	/**定向模板创建时间*/
+    private String message;
+    /**
+     * 定向模板创建时间
+     */
     @ApiModelProperty(value = "定向模板创建时间")
-	private Date createTime;
-	/**定向模板修改时间*/
+    private Date createTime;
+    /**
+     * 定向模板修改时间
+     */
     @ApiModelProperty(value = "定向模板修改时间")
-	private Date updateTime;
+    private Date updateTime;
 }

+ 0 - 2
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/mapper/KuaishouDirectionalPackageMapper.java

@@ -24,6 +24,4 @@ public interface KuaishouDirectionalPackageMapper extends BaseMapper<KuaishouDir
 
     List<JSONObject> getRelatedAccountGroup(@Param("id") String id,@Param("type") Integer type);
 
-    int delete(@Param("accountId") Long accountId, @Param("templateId") Long templateId);
-
 }

+ 7 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/mapper/KuaishouDirectionalTemplateRelMapper.java

@@ -3,6 +3,8 @@ package cn.com.ctop.kuaishou.modules.ai.mapper;
 import java.util.List;
 
 import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalTemplateRel;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import org.apache.ibatis.annotations.Param;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 
@@ -14,4 +16,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  */
 public interface KuaishouDirectionalTemplateRelMapper extends BaseMapper<KuaishouDirectionalTemplateRel> {
 
+    void replace(KuaishouDirectionalTemplateRel rel);
+
+    List<JSONObject> queryPushResults(@Param("id")String id, @Param("accountIds")JSONArray accountIds);
+
+    List<JSONObject> getAccountByProjectId(@Param("projectId") Long projectId,@Param("id") String id);
 }

+ 17 - 20
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/mapper/xml/KuaishouDirectionalPackageMapper.xml

@@ -4,19 +4,18 @@
 
     <select id="queryEntity" resultType="cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalPackage">
         SELECT project_id,template_name from ctop_kuaishou_directional_package
-        WHERE  data_status = 1
+        WHERE data_status = 1
         <if test="projectId != null">
-            and  project_id = #{projectId}
+            and project_id = #{projectId}
         </if>
         <if test="templateName != null">
-            and  template_name = #{templateName}
+            and template_name = #{templateName}
         </if>
         limit 1
     </select>
     <select id="queryList" resultType="com.alibaba.fastjson.JSONObject">
         SELECT
         t1.id,
-        t1.template_id 'templateId',
         t1.template_name 'templateName',
         t2.project_name 'projectName',
         CASE WHEN t1.platform_os =1 THEN 'Android' WHEN t1.platform_os =2 THEN 'iOS' ELSE '-' END 'platformOs',
@@ -45,7 +44,7 @@
             AND t1.platform_os = #{platformOs}
         </if>
         <if test="projectId !=null">
-            AND t2.project_id = #{projectId}
+            AND t1.project_id = #{projectId}
         </if>
         order by t1.update_time desc
     </select>
@@ -53,7 +52,6 @@
         SELECT
         IFNULL(count(1),0)
         FROM ctop_kuaishou_directional_package t1
-        LEFT JOIN ctop_project t2 ON t2.id = t1.project_id
         where t1.data_status = 1
         <if test="templateName !=null">
             AND t1.template_name like concat('%',#{templateName},'%')
@@ -62,28 +60,27 @@
             AND t1.platform_os = #{platformOs}
         </if>
         <if test="projectId !=null">
-            AND t2.project_id = #{projectId}
+            AND t1.project_id = #{projectId}
         </if>
     </select>
 
 
     <select id="getRelatedAccountGroup" resultType="com.alibaba.fastjson.JSONObject">
         SELECT
-            IFNULL(t2.auth_name,'') as 'authName',
-            IFNULL(t2.account_id,'') as 'accountId',
-            IFNULL(t1.template_id,'') as 'templateId'
+        t1.dir_id as 'id',
+        IFNULL(t2.auth_name,'') as 'authName',
+        IFNULL(t2.account_id,'') as 'accountId',
+        IFNULL(t1.template_id,'') as 'templateId',
+        IFNULL(t1.template_name,'') as 'templateName'
         FROM ctop_kuaishou_directional_template_rel t1
-            <if test=" type ==1 ">
-        INNER JOIN ctop_user_allocation t2 ON t1.rel_id = t2.account_id
-            </if>
+        <if test=" type ==1 ">
+            INNER JOIN ctop_user_allocation t2 ON t1.rel_id = t2.account_id
+        </if>
         <if test=" type ==2 ">
-            INNER  JOIN ctop_kuaishou_group_template t2 ON t1.rel_id = t2.unit_id
-            INNER JOIN ctop_user_allocation t3 ON t3.account_id = t3.account_id
+            INNER JOIN ctop_kuaishou_group_template t3 ON t1.rel_id = t3.unit_id
+            INNER JOIN ctop_user_allocation t2 ON t2.account_id = t3.account_id
         </if>
-        WHERE t1.dir_id =#{id}
+        WHERE t1.data_status = 1
+        AND t1.dir_id =#{id}
     </select>
-
-    <delete id="delete">
-        DELETE FROM ctop_kuaishou_directional_package where template_id= #{templateId} and account_id = #{accountId}
-    </delete>
 </mapper>

+ 74 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/mapper/xml/KuaishouDirectionalTemplateRelMapper.xml

@@ -2,4 +2,78 @@
 <!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.ai.mapper.KuaishouDirectionalTemplateRelMapper">
 
+    <insert id="replace">
+        replace
+        into ctop_kuaishou_directional_template_rel(
+        id ,
+        dir_id ,
+        project_id ,
+        template_id ,
+        template_name ,
+        data_status,
+        rel_id ,
+        rel_type ,
+        exclude_population ,
+        paid_audience ,
+        population ,
+        message ,
+        create_time ,
+        update_time
+        )
+        values
+            (
+        #{id} ,
+        #{dirId} ,
+        #{projectId} ,
+        #{templateId} ,
+        #{templateName} ,
+        #{dataStatus} ,
+        #{relId} ,
+        #{relType} ,
+        #{excludePopulation} ,
+        #{paidAudience} ,
+        #{population} ,
+        #{message} ,
+        #{createTime} ,
+        #{updateTime}
+        )
+
+    </insert>
+
+    <select id="queryPushResults" resultType="com.alibaba.fastjson.JSONObject">
+        SELECT
+        dir_id,
+        IFNULL(t2.auth_name,'') as 'authName',
+        IFNULL(t2.account_id,'') as 'accountId',
+        IFNULL(t1.template_id,'') as 'templateId',
+        IFNULL(t1.message,'-') as 'message',
+        CASE WHEN t1.data_status =1 THEN '推送成功' ELSE '推送失败' end as 'result'
+        FROM ctop_kuaishou_directional_template_rel t1
+        LEFT JOIN ctop_user_allocation t2 ON t1.rel_id = t2.account_id
+        where dir_id = #{id}
+        AND rel_type = 'account'
+        <if test="accountIds!=null">
+            AND rel_id IN
+            <foreach item="item" index="index" collection="accountIds"
+                     open="(" separator="," close=")">
+                #{item}
+            </foreach>
+        </if>
+    </select>
+
+    <select id="getAccountByProjectId" resultType="com.alibaba.fastjson.JSONObject">
+        SELECT
+            t1.account_id as 'accountId',
+            CONCAT(t1.auth_name,'(',t1.account_id,')') as 'authName',
+            IFNULL(t2.data_status,0) as 'state'
+            FROM ctop_user_allocation t1
+            LEFT JOIN (
+            SELECT rel_id,data_status FROM ctop_kuaishou_directional_template_rel
+            WHERE  project_id = #{projectId}
+              AND rel_type = 'account'
+              AND dir_id = #{id}
+            ) t2 ON t1.account_id = t2.rel_id
+        where t1.account_status = 0
+          AND t1.project_id = #{projectId}
+    </select>
 </mapper>

+ 6 - 5
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/service/IKuaishouDirectionalPackageService.java

@@ -14,7 +14,7 @@ import org.jeecg.common.api.vo.Result;
  */
 public interface IKuaishouDirectionalPackageService extends IService<KuaishouDirectionalPackage> {
 
-    Result<Object> createDirectionalPackage(String accessToken, JSONObject requestJson);
+    Result<Object> createDirectionalPackage(JSONObject requestJson);
 
     Result<Object> updateDirectionalPackage(String accessToken, JSONObject requestJson);
 
@@ -22,11 +22,12 @@ public interface IKuaishouDirectionalPackageService extends IService<KuaishouDir
 
     Result<Object> getRelatedAccountGroup(String id, Integer type, Integer pageNo, Integer pageSize);
 
-    Result<Object> pushDirectionalPackage(String id, JSONArray accountIds);
+    Result<Object> pushDirectionalPackage(String id, JSONArray datas);
 
-    Result<Object> getHistory(Long projectId, Long templateId, Integer pageNo, Integer pageSize);
+    Result<Object> queryPushResults(String id, JSONArray accountIds);
 
-    Result<Object> getAccountByProjectId(Long projectId, Integer pageNo, Integer pageSize);
+    Result<Object> updatePopulation(JSONObject requestJson);
+
+    Result<Object> getAccountByProjectId(Long projectId, String id);
 
-    Result<Object> delete(Long accountId, Long templateId);
 }

+ 177 - 130
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/ai/service/impl/KuaishouDirectionalPackageServiceImpl.java

@@ -9,11 +9,14 @@ import cn.com.ctop.common.module.utils.PropertiesUtils;
 import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalPackage;
 import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalTemplateRel;
 import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouDirectionalPackageMapper;
+import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouDirectionalTemplateRelMapper;
 import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
 import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalTemplateRelService;
 import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateService;
+import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
@@ -25,8 +28,6 @@ import org.springframework.stereotype.Service;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 
 /**
  * 自动投放-定向包详情
@@ -44,18 +45,20 @@ public class KuaishouDirectionalPackageServiceImpl extends ServiceImpl<KuaishouD
     @Autowired
     private KuaishouDirectionalPackageMapper packageMapper;
     @Autowired
+    private KuaishouDirectionalTemplateRelMapper relMapper;
+    @Autowired
     private IKuaishouDirectionalTemplateRelService relService;
     @Autowired
     private ICtopOauthTokenService oauthTokenService;
-    static ExecutorService executorService = null;
 
     @Override
-    public Result<Object> createDirectionalPackage(String accessToken, JSONObject requestJson) {
+    public Result<Object> createDirectionalPackage(JSONObject requestJson) {
         KuaishouDirectionalPackage entity = packageMapper.queryEntity(requestJson);
         if (!Check.isNull(entity)) {
-            return Result.error("该账户下人群包名已存在");
+            return Result.error("该账户下定向包名已存在");
         }
         KuaishouDirectionalPackage kuaishouDirectionalPackage = JSONObject.toJavaObject(requestJson, KuaishouDirectionalPackage.class);
+        kuaishouDirectionalPackage.setKeyword(JSONObject.toJSONString(requestJson.getJSONArray("keyword")));
         kuaishouDirectionalPackage.setDataStatus(1);
         boolean save = this.save(kuaishouDirectionalPackage);
         if (save) {
@@ -248,132 +251,125 @@ public class KuaishouDirectionalPackageServiceImpl extends ServiceImpl<KuaishouD
     }
 
     @Override
-    public Result<Object> pushDirectionalPackage(String id, JSONArray accountIds) {
+    public Result<Object> pushDirectionalPackage(String id, JSONArray datas) {
         KuaishouDirectionalPackage directionalPackage = packageMapper.selectById(id);
-        if (Check.isNull(directionalPackage)) {
+        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(directionalPackage)).toJavaObject(JSONObject.class);
+        if (Check.isNull(data)) {
             return Result.error("未找到定向包");
         }
-        Thread thread = new Thread() {
-            @Override
-            public void run() {
-                try {
-                    executorService = Executors.newFixedThreadPool(3);
-                    for (int i = 0; i < accountIds.size(); i++) {
-                        Long accountId = accountIds.getLong(i);
-                        executorService.submit(new Runnable() {
-                            @Override
-                            public void run() {
-                                createDirectionalPackage(directionalPackage, accountId);
-                            }
-                        });
-                    }
-                } catch (Exception e) {
-                    e.printStackTrace();
-                }
-            }
-        };
-        thread.start();
-        return Result.ok("推送成功");
+        for (int i = 0; i < datas.size(); i++) {
+            JSONObject request = datas.getJSONObject(i);
+            createDirectionalPackage(data, request);
+        }
+        return Result.ok("推送完成");
     }
 
-    private void createDirectionalPackage(KuaishouDirectionalPackage directionalPackage, Long accountId) {
+    private void createDirectionalPackage(JSONObject data, JSONObject request) {
+        Long accountId = request.getLong("accountId");
         CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
         String message = "";
+        KuaishouDirectionalTemplateRel rel = new KuaishouDirectionalTemplateRel();
+        rel.setDirId(data.getString("id"));
+        rel.setRelId(accountId);
+        rel.setRelType("account");
+        rel.setProjectId(data.getLong("projectId"));
+        rel.setTemplateName(data.getString("templateName"));
+        rel.setDataStatus(0);
         try {
             JSONObject param = new JSONObject();
             param.put("advertiser_id", accountId);
-            param.put("template_name", directionalPackage.getTemplateName());
+            param.put("template_name", data.getString("templateName"));
             JSONObject targetJson = new JSONObject();
-            if (!Check.isNull(directionalPackage.getRegion())) {
-                targetJson.put("region", directionalPackage.getRegion());
+            if (!Check.isNull(data.getJSONArray("region"))) {
+                targetJson.put("region", data.getJSONArray("region"));
             }
-            if (!Check.isNull(directionalPackage.getDistrictIds())) {
-                targetJson.put("district_ids", directionalPackage.getDistrictIds());
+            if (!Check.isNull(data.getJSONArray("districtIds"))) {
+                targetJson.put("district_ids", data.getJSONArray("districtIds"));
             }
-            if (!Check.isNull(directionalPackage.getUserType())) {
-                targetJson.put("user_type", directionalPackage.getUserType());
+            if (!Check.isNull(data.getInteger("userType"))) {
+                targetJson.put("user_type", data.getInteger("userType"));
             }
-            if (!Check.isNull(directionalPackage.getAgesRange())) {
-                targetJson.put("ages_range", directionalPackage.getAgesRange());
+            if (!Check.isNull(data.getJSONArray("agesRange"))) {
+                targetJson.put("ages_range", data.getJSONArray("agesRange"));
             }
 
-            JSONObject ageJson = new JSONObject();
-            if (!Check.isNull(directionalPackage.getMin())) {
-                ageJson.put("min", directionalPackage.getMin());
-            }
-            if (!Check.isNull(directionalPackage.getMax())) {
-                ageJson.put("max", directionalPackage.getMax());
-            }
-            if (!Check.isNull(ageJson)) {
+            if (!Check.isNull(data.getInteger("min")) && !Check.isNull(data.getInteger("max"))) {
+                JSONObject ageJson = new JSONObject();
+                ageJson.put("min", data.getInteger("min"));
+                ageJson.put("max", data.getInteger("max"));
                 targetJson.put("age", ageJson);
             }
-            if (!Check.isNull(directionalPackage.getGender())) {
-                targetJson.put("gender", directionalPackage.getGender());
+
+            if (!Check.isNull(data.getInteger("gender"))) {
+                targetJson.put("gender", data.getInteger("gender"));
             }
-            if (!Check.isNull(directionalPackage.getPlatformOs())) {
-                targetJson.put("platform_os", directionalPackage.getPlatformOs());
+            if (!Check.isNull(data.getInteger("platformOs"))) {
+                targetJson.put("platform_os", data.getInteger("platformOs"));
             }
-            if (!Check.isNull(directionalPackage.getAndroidOsv())) {
-                targetJson.put("android_osv", directionalPackage.getAndroidOsv());
+            if (!Check.isNull(data.getInteger("androidOsv"))) {
+                targetJson.put("android_osv", data.getInteger("androidOsv"));
             }
-            if (!Check.isNull(directionalPackage.getIosOsv())) {
-                targetJson.put("ios_osv", directionalPackage.getIosOsv());
+            if (!Check.isNull(data.getInteger("iosOsv"))) {
+                targetJson.put("ios_osv", data.getInteger("iosOsv"));
             }
-            if (!Check.isNull(directionalPackage.getNetwork())) {
-                targetJson.put("network", directionalPackage.getNetwork());
+            if (!Check.isNull(data.getInteger("network"))) {
+                targetJson.put("network", data.getInteger("network"));
             }
-            if (!Check.isNull(directionalPackage.getFilterConvertedLevel())) {
-                targetJson.put("filter_converted_level", directionalPackage.getFilterConvertedLevel());
+            if (!Check.isNull(data.getInteger("filterConvertedLevel"))) {
+                targetJson.put("filter_converted_level", data.getInteger("filterConvertedLevel"));
             }
-            if (!Check.isNull(directionalPackage.getDeviceBrand())) {
-                targetJson.put("device_brand", directionalPackage.getDeviceBrand());
+            if (!Check.isNull(data.getJSONArray("deviceBrand"))) {
+                targetJson.put("device_brand", data.getJSONArray("deviceBrand"));
             }
-            if (!Check.isNull(directionalPackage.getDevicePrice())) {
-                targetJson.put("device_price", directionalPackage.getDevicePrice());
+            if (!Check.isNull(data.getJSONArray("devicePrice"))) {
+                targetJson.put("device_price", data.getJSONArray("devicePrice"));
             }
-            if (!Check.isNull(directionalPackage.getBusinessInterestType())) {
-                targetJson.put("business_interest_type", directionalPackage.getBusinessInterestType());
+            if (!Check.isNull(data.getInteger("businessInterestType"))) {
+                targetJson.put("business_interest_type", data.getInteger("businessInterestType"));
             }
-            if (!Check.isNull(directionalPackage.getBusinessInterest())) {
-                targetJson.put("business_interest", directionalPackage.getBusinessInterest());
+            if (!Check.isNull(data.getJSONArray("businessInterest"))) {
+                targetJson.put("business_interest", data.getJSONArray("businessInterest"));
             }
-            if (!Check.isNull(directionalPackage.getFansStar())) {
-                targetJson.put("fans_star", directionalPackage.getFansStar());
+            if (!Check.isNull(data.getJSONArray("fansStar"))) {
+                targetJson.put("fans_star", data.getJSONArray("fansStar"));
             }
-            if (!Check.isNull(directionalPackage.getInterestVideo())) {
-                targetJson.put("interest_video", directionalPackage.getInterestVideo());
+            if (!Check.isNull(data.getJSONArray("interestVideo"))) {
+                targetJson.put("interest_video", data.getJSONArray("interestVideo"));
             }
-            if (!Check.isNull(directionalPackage.getAppInterest())) {
-                targetJson.put("app_interest", directionalPackage.getAppInterest());
+            if (!Check.isNull(data.getJSONArray("appInterest"))) {
+                targetJson.put("app_interest", data.getJSONArray("appInterest"));
             }
-            if (!Check.isNull(directionalPackage.getAppIds())) {
-                targetJson.put("app_ids", directionalPackage.getAppIds());
+            if (!Check.isNull(data.getJSONArray("appIds"))) {
+                targetJson.put("app_ids", data.getJSONArray("appIds"));
             }
-            if (!Check.isNull(directionalPackage.getPopulation())) {
-                targetJson.put("population", directionalPackage.getPopulation());
+            if (!Check.isNull(request.getJSONArray("population"))) {
+                targetJson.put("population", request.getJSONArray("population"));
+                rel.setPopulation(request.getString("population"));
             }
-            if (!Check.isNull(directionalPackage.getPaidAudience())) {
-                targetJson.put("paid_audience", directionalPackage.getPaidAudience());
+            if (!Check.isNull(request.getJSONArray("paidAudience"))) {
+                targetJson.put("paid_audience", request.getJSONArray("paidAudience"));
+                rel.setPaidAudience(request.getString("paidAudience"));
             }
-            if (!Check.isNull(directionalPackage.getExcludePopulation())) {
-                targetJson.put("exclude_population", directionalPackage.getExcludePopulation());
+            if (!Check.isNull(request.getJSONArray("excludePopulation"))) {
+                targetJson.put("exclude_population", request.getJSONArray("excludePopulation"));
+                rel.setExcludePopulation(request.getString("excludePopulation"));
             }
-            JSONObject intelliExtendJson = new JSONObject();
+            if (!Check.isNull(data.getInteger("isOpen"))) {
+                JSONObject intelliExtendJson = new JSONObject();
+                intelliExtendJson.put("is_open", data.getInteger("isOpen"));
 
-            if (!Check.isNull(directionalPackage.getIsOpen())) {
-                intelliExtendJson.put("is_open", directionalPackage.getIsOpen());
-            }
-            if (!Check.isNull(directionalPackage.getNoAgeBreak())) {
-                intelliExtendJson.put("no_age_break", directionalPackage.getNoAgeBreak());
-            }
-            if (!Check.isNull(directionalPackage.getNoGenderBreak())) {
-                intelliExtendJson.put("no_gender_break", directionalPackage.getNoGenderBreak());
-            }
-            if (!Check.isNull(directionalPackage.getNoAreaBreak())) {
-                intelliExtendJson.put("no_area_break", directionalPackage.getNoAreaBreak());
-            }
-            if (!Check.isNull(intelliExtendJson)) {
-                targetJson.put("intelli_extend", intelliExtendJson);
+                if (!Check.isNull(data.getInteger("noAgeBreak"))) {
+                    intelliExtendJson.put("no_age_break", data.getInteger("noAgeBreak"));
+                }
+                if (!Check.isNull(data.getInteger("noGenderBreak"))) {
+                    intelliExtendJson.put("no_gender_break", data.getInteger("noGenderBreak"));
+                }
+                if (!Check.isNull(data.getInteger("noAreaBreak"))) {
+                    intelliExtendJson.put("no_area_break", data.getInteger("noAreaBreak"));
+                }
+                if (!Check.isNull(intelliExtendJson)) {
+                    targetJson.put("intelli_extend", intelliExtendJson);
+                }
             }
             if (!Check.isNull(targetJson)) {
                 param.put("target", targetJson);
@@ -381,23 +377,23 @@ public class KuaishouDirectionalPackageServiceImpl extends ServiceImpl<KuaishouD
             JSONObject behaviorInterest = new JSONObject();
             JSONObject behavior = new JSONObject();
             JSONObject interest = new JSONObject();
-            if (!Check.isNull(directionalPackage.getKeyword())) {
-                behavior.put("keyword", directionalPackage.getKeyword());
+            if (!Check.isNull(data.getJSONArray("keyword"))) {
+                behavior.put("keyword", data.getJSONArray("keyword"));
             }
-            if (!Check.isNull(directionalPackage.getLabel())) {
-                behavior.put("label", directionalPackage.getLabel());
+            if (!Check.isNull(data.getJSONArray("label"))) {
+                behavior.put("label", data.getJSONArray("label"));
             }
-            if (!Check.isNull(directionalPackage.getStrengthType())) {
-                behavior.put("strength_type", directionalPackage.getStrengthType());
+            if (!Check.isNull(data.getInteger("strengthType"))) {
+                behavior.put("strength_type", data.getInteger("strengthType"));
             }
-            if (!Check.isNull(directionalPackage.getTimeType())) {
-                behavior.put("time_type", directionalPackage.getTimeType());
+            if (!Check.isNull(data.getInteger("timeType"))) {
+                behavior.put("time_type", data.getInteger("timeType"));
             }
-            if (!Check.isNull(directionalPackage.getSceneType())) {
-                behavior.put("scene_type", directionalPackage.getSceneType());
+            if (!Check.isNull(data.getJSONArray("sceneType"))) {
+                behavior.put("scene_type", data.getJSONArray("sceneType"));
             }
-            if (!Check.isNull(directionalPackage.getInterestLabel())) {
-                interest.put("label", directionalPackage.getInterestLabel());
+            if (!Check.isNull(data.getJSONArray("interestLabel"))) {
+                interest.put("label", data.getJSONArray("interestLabel"));
             }
             if (!Check.isNull(behavior)) {
                 behaviorInterest.put("behavior", behavior);
@@ -419,43 +415,94 @@ public class KuaishouDirectionalPackageServiceImpl extends ServiceImpl<KuaishouD
                 message = resultJson.getString("message");
                 if (code == 0) {
                     kuaishouTemplateService.getTemplateByAccountId(accountId, oauthToken.getAccessToken(), 1);
-                    JSONObject data = resultJson.getJSONObject("data");
-                    KuaishouDirectionalTemplateRel rel = new KuaishouDirectionalTemplateRel();
-                    rel.setDirId(directionalPackage.getId());
-                    rel.setRelId(accountId);
-                    rel.setRelType("account");
-                    rel.setProjectId(directionalPackage.getProjectId());
-                    rel.setTemplateId(data.getLong("template_id"));
-                    rel.setTemplateName(directionalPackage.getTemplateName());
-                    rel.setMessage(message);
-                    relService.save(rel);
+                    JSONObject results = resultJson.getJSONObject("data");
+                    rel.setTemplateId(results.getLong("template_id"));
+                    rel.setDataStatus(1);
                 } else {
-                    log.error("创建定向包失败," + message);
+                    message = "推送定向包失败," + message;
+                    log.error(message);
                 }
             } else {
-                message = "创建定向包失败,返回结果为空";
+                message = "推送定向包失败,返回结果为空";
             }
         } catch (Exception e) {
-            log.error("创建定向包出现异常", e);
+            message = "推送定向包出现异常";
+            log.error(message, e);
         }
+        rel.setMessage(message);
+        relMapper.replace(rel);
     }
 
     @Override
-    public Result<Object> getHistory(Long projectId, Long templateId, Integer pageNo, Integer pageSize) {
-        return null;
+    public Result<Object> queryPushResults(String id, JSONArray accountIds) {
+        List<JSONObject> list = relMapper.queryPushResults(id, accountIds);
+        return Result.ok(new PageInfo<>(list));
     }
 
+
     @Override
-    public Result<Object> getAccountByProjectId(Long projectId, Integer pageNo, Integer pageSize) {
-        return null;
+    public Result<Object> updatePopulation(JSONObject requestJson) {
+        Long accountId = requestJson.getLong("accountId");
+        String message = "";
+        KuaishouDirectionalTemplateRel rel = new KuaishouDirectionalTemplateRel();
+        try {
+            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
+            QueryWrapper<KuaishouDirectionalTemplateRel> queryWrapper = new QueryWrapper<>();
+            queryWrapper.eq("dir_id", requestJson.getString("id"));
+            queryWrapper.eq("rel_id", accountId);
+            queryWrapper.eq("rel_type", "account");
+            queryWrapper.eq("template_id", requestJson.getLong("templateId"));
+            JSONObject param = new JSONObject();
+            param.put("template_id", requestJson.getLong("templateId"));
+            param.put("advertiser_id", accountId);
+            param.put("template_name", requestJson.getString("templateName"));
+            JSONObject targetJson = new JSONObject();
+            if (!Check.isNull(requestJson.getJSONArray("population"))) {
+                targetJson.put("population", requestJson.getJSONArray("population"));
+                rel.setPopulation(requestJson.getString("population"));
+            }
+            if (!Check.isNull(requestJson.getJSONArray("paidAudience"))) {
+                targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
+                rel.setPaidAudience(requestJson.getString("paidAudience"));
+            }
+            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
+                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
+                rel.setExcludePopulation(requestJson.getString("excludePopulation"));
+            }
+            if (!Check.isNull(targetJson)) {
+                param.put("target", targetJson);
+            }
+            Map<String, String> headers = new HashMap<String, String>();
+            headers.put("Access-Token", oauthToken.getAccessToken());
+            headers.put("Content-Type", " application/json");
+            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_UPDATE;
+            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
+            JSONObject resultJson = JSONObject.parseObject(result);
+            if (!Check.isNull(resultJson)) {
+                Integer code = resultJson.getInteger("code");
+                message = resultJson.getString("message");
+                if (code == 0) {
+                    kuaishouTemplateService.getTemplateByAccountId(requestJson.getLong("accountId"), oauthToken.getAccessToken(), 1);
+                    JSONObject data = resultJson.getJSONObject("data");
+                    relService.update(rel, queryWrapper);
+                    return Result.ok("修改成功");
+                } else {
+                    return Result.error("修改失败," + message);
+                }
+            } else {
+                return Result.error("修改失败,返回结果为空");
+            }
+        } catch (Exception e) {
+            log.error("修改定向模板人群包信息异常,账户:{}", accountId, e.getMessage());
+            e.printStackTrace();
+        }
+        return Result.error("修改失败");
     }
 
     @Override
-    public Result<Object> delete(Long accountId, Long templateId) {
-        int delete = packageMapper.delete(accountId, templateId);
-        if (delete > 0) {
-            return Result.ok("删除成功");
-        }
-        return Result.error("删除失败");
+    public Result<Object> getAccountByProjectId(Long projectId, String id) {
+        List<JSONObject> list = relMapper.getAccountByProjectId(projectId, id);
+        return Result.ok(new PageInfo<>(list));
     }
+
 }