package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.constant.CtopRoleCodeConstant;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.kuaishou.modules.ai.entity.AiKuaishouAccountAutoStrategy;
import cn.com.ctop.kuaishou.modules.ai.entity.AiKuaishouAdvertiserStrategy;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouAccountAutoStrategyService;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouAdvertiserStrategyService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaiShouAppMultipleBidsService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouVideoRelateCreativesService;
import cn.com.ctop.kuaishou.modules.channel.entity.KuaishouChannelItems;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 快手账户策略设置信息表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-01-25
 */
@Slf4j
@RestController
@RequestMapping("/ctop/aiKuaishouAdvertiserStrategy")
public class AiKuaishouAdvertiserStrategyController {
    @Autowired
    private IKuaishouVideoRelateCreativesService kuaishouVideoRelateCreativesService;
    @Autowired
    private IAiKuaishouAdvertiserStrategyService aiKuaishouAdvertiserStrategyService;
    @Autowired
    private IUserAllocationService allocationService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IKuaiShouAppMultipleBidsService kuaiShouAppMultipleBidsService;

    @Autowired
    private IAiKuaishouAccountAutoStrategyService aiKuaishouAccountAutoStrategyService;

    /**
     * 分页列表查询
     *
     * @param aiKuaishouAdvertiserStrategy
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<PageInfo<AiKuaishouAdvertiserStrategy>> queryPageList(AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategy,
                                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        HttpServletRequest req) {
        Result<PageInfo<AiKuaishouAdvertiserStrategy>> result = new Result<>();
        String userId = aiKuaishouAdvertiserStrategy.getUserId();
        String roleCode = sysRoleService.getRoleCodeByUserId(userId);
        List<String> userIds = new ArrayList<>();
        if ("CompanyManager".equals(roleCode)) {
            userIds = sysRoleService.getCompanyUsers(roleCode, userId);
            aiKuaishouAdvertiserStrategy.setUserIds(userIds);
        } else if ("bytedanceDirector".equals(roleCode)) {
            userIds = sysRoleService.getCompanyUsers(roleCode, userId);
            aiKuaishouAdvertiserStrategy.setUserIds(userIds);
        } else if ("kuaishouDirector".equals(roleCode)) {
            userIds = sysRoleService.getCompanyUsers(roleCode, userId);
            aiKuaishouAdvertiserStrategy.setUserIds(userIds);
        } else if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode)) {
            aiKuaishouAdvertiserStrategy.setUserIds(null);
        }else {
            userIds.add(userId);
            aiKuaishouAdvertiserStrategy.setUserIds(userIds);
        }
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<AiKuaishouAdvertiserStrategy> pageInfo = aiKuaishouAdvertiserStrategyService.queryList(aiKuaishouAdvertiserStrategy);
        List<AiKuaishouAdvertiserStrategy> list = pageInfo.getList();
        List<AiKuaishouAdvertiserStrategy> setData = new ArrayList<>();
        if (null != list && !list.isEmpty()) {
            list.forEach(record -> {
                Long accountId = record.getAccountId();
                UserAllocation allocation = allocationService.getByAccountId(accountId);
                if (null != allocation) {
                    record.setAuthName(allocation.getAuthName());
                }
            });
        }
        pageInfo.setList(list);
        result.setSuccess(true);
        result.setResult(pageInfo);
        return result;
    }

    /**
     * 添加
     *
     * @param aiKuaishouAdvertiserStrategy
     * @return
     */
    @PostMapping(value = "/add")
    public Result<AiKuaishouAdvertiserStrategy> add(@RequestBody AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategy) {
        Result<AiKuaishouAdvertiserStrategy> result = new Result<>();
        try {
            Long accountId = aiKuaishouAdvertiserStrategy.getAccountId();
            AiKuaishouAdvertiserStrategy getEntity = aiKuaishouAdvertiserStrategyService.getByAccountId(accountId);
            if (null != getEntity) {
                result.error500("该账户配置信息已经被创建");
                return result;
            }
            UserAllocation allocation = allocationService.getByAccountId(accountId);
            if (null != allocation) {
                aiKuaishouAdvertiserStrategy.setUserId(allocation.getUserId());
            }
            aiKuaishouAdvertiserStrategy.setDescription(aiKuaishouAdvertiserStrategy.getDescription().trim());
            Integer singleAppId = aiKuaishouAdvertiserStrategy.getSingleAppid();
            if (null != singleAppId && singleAppId == 1) {
                if (aiKuaishouAdvertiserStrategy.getCampaignType() == 2 || aiKuaishouAdvertiserStrategy.getCampaignType() == 7) {
                    Integer appId = Integer.parseInt(JSONArray.parseArray(aiKuaishouAdvertiserStrategy.getAppIdArray()).getString(0));
                    aiKuaishouAdvertiserStrategy.setAppId(appId);
                }

            }
            aiKuaishouAdvertiserStrategyService.save(aiKuaishouAdvertiserStrategy);
            Thread thread = new Thread() {
                @Override
                public void run() {
                    kuaishouVideoRelateCreativesService.videoRelateCreatives(aiKuaishouAdvertiserStrategy.getAccountId());
                }
            };
            thread.start();
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param aiKuaishouAdvertiserStrategy
     * @return
     */
    @PostMapping(value = "/edit")
    public Result<AiKuaishouAdvertiserStrategy> edit(@RequestBody AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategy) {
        Result<AiKuaishouAdvertiserStrategy> result = new Result<>();
        AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategyEntity = aiKuaishouAdvertiserStrategyService.getById(aiKuaishouAdvertiserStrategy.getId());
        if (aiKuaishouAdvertiserStrategyEntity == null) {
            result.error500("未找到对应实体");
        } else {
            Integer singleAppId = aiKuaishouAdvertiserStrategy.getSingleAppid();
            if (aiKuaishouAdvertiserStrategy.getCampaignType() == 2 || aiKuaishouAdvertiserStrategy.getCampaignType() == 7) {
                if (null != singleAppId && singleAppId == 1) {
                    Integer appId = Integer.parseInt(JSONArray.parseArray(aiKuaishouAdvertiserStrategy.getAppIdArray()).getString(0));
                    aiKuaishouAdvertiserStrategy.setAppId(appId);
                }
            }

            boolean ok = aiKuaishouAdvertiserStrategyService.updateById(aiKuaishouAdvertiserStrategy);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 开启
     *
     * @return
     */
    @GetMapping(value = "/oprateStatus")
    public Map<String, Object> oprateStatus(Long id, Integer status) {
        Map<String, Object> result = new HashMap<>();
        if (null == id || status == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategyEntity = aiKuaishouAdvertiserStrategyService.getById(id);
        if (aiKuaishouAdvertiserStrategyEntity == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        if (status != 0) {
            status = 1;
        }
        QueryWrapper<AiKuaishouAccountAutoStrategy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", aiKuaishouAdvertiserStrategyEntity.getAccountId()).last("limit 1");
        AiKuaishouAccountAutoStrategy one = aiKuaishouAccountAutoStrategyService.getOne(queryWrapper);
        if (null != one && one.getStatus() == status && status == 1) {
            ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_AUTO_STRATEGY_UPDATE);
            return result;
        }
        aiKuaishouAdvertiserStrategyEntity.setStatus(status);
        aiKuaishouAdvertiserStrategyService.updateById(aiKuaishouAdvertiserStrategyEntity);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    /**
     * 开启
     *
     * @return
     */
    @GetMapping(value = "/oprateCreativeStatus")
    public Map<String, Object> oprateCreativeStatus(Long id, Integer status) {
        Map<String, Object> result = new HashMap<>();
        if (null == id || status == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategyEntity = aiKuaishouAdvertiserStrategyService.getById(id);
        if (aiKuaishouAdvertiserStrategyEntity == null) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        if (status != 0) {
            status = 1;
        }
        aiKuaishouAdvertiserStrategyEntity.setOpenProgramCreate(status);
        aiKuaishouAdvertiserStrategyService.updateById(aiKuaishouAdvertiserStrategyEntity);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            aiKuaishouAdvertiserStrategyService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<AiKuaishouAdvertiserStrategy> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<AiKuaishouAdvertiserStrategy> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.aiKuaishouAdvertiserStrategyService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */


    @GetMapping(value = "/queryById")
    public Result<AiKuaishouAdvertiserStrategy> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<AiKuaishouAdvertiserStrategy> result = new Result<>();
        AiKuaishouAdvertiserStrategy aiKuaishouAdvertiserStrategy = aiKuaishouAdvertiserStrategyService.getById(id);
        if (aiKuaishouAdvertiserStrategy == null) {
            result.error500("未找到对应实体");
        } else {
            if (aiKuaishouAdvertiserStrategy.getMultipleBids() == 1) {
                List<JSONObject> appInfoList = kuaiShouAppMultipleBidsService.getAppInfiList(aiKuaishouAdvertiserStrategy.getAccountId(), aiKuaishouAdvertiserStrategy.getAppIdArray());
                if (!Check.isNull(appInfoList)) {
                    aiKuaishouAdvertiserStrategy.setAppInfoList(appInfoList);

                }
            }

            result.setResult(aiKuaishouAdvertiserStrategy);
            result.setSuccess(true);
        }
        return result;
    }

    @GetMapping(value = "testCreate")
    public Map<String, Object> testCreate(Long accountId) {
        return aiKuaishouAdvertiserStrategyService.testCreate(accountId);
    }

    @GetMapping(value = "aiHistoricalMissingMaterial")
    public Map<String, Object> aiHistoricalMissingMaterial(Long accountId) {
        return aiKuaishouAdvertiserStrategyService.aiHistoricalMissingMaterial(accountId);
    }
}
