package cn.com.ctop.kuaishou.modules.dimension.controller;

import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.ISysRoleExtService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouAppList;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouAppListService;
import cn.com.ctop.kuaishou.modules.dimension.entity.KuaiShouDimensionAccount;
import cn.com.ctop.kuaishou.modules.dimension.entity.KuaiShouDimensionMaterial;
import cn.com.ctop.kuaishou.modules.dimension.entity.KuaiShouDimensionStrategy;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionAccountService;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionMaterialService;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionStrategyService;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionVariableService;
import cn.com.ctop.kuaishou.modules.report.service.IEtlKuaishouReportAccountDailyService;
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.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 多维度测试策略表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-07-19
 */
@Slf4j
@Api(tags = "多维度测试策略表")
@RestController
@RequestMapping("/dimension/kuaiShouDimensionStrategy")
public class KuaiShouDimensionStrategyController {
    @Autowired
    private IKuaiShouDimensionStrategyService kuaiShouDimensionStrategyService;
    @Autowired
    private IKuaiShouDimensionAccountService kuaiShouDimensionAccountService;
    @Autowired
    private IKuaiShouDimensionVariableService variableService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private IEtlKuaishouReportAccountDailyService reportAccountDailyService;
    @Autowired
    private IKuaiShouDimensionMaterialService dimensionMaterialService;
    @Autowired
    private IKuaiShouAppListService appListService;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private ISysRoleService roleService;

    @GetMapping(value = "/checkStrategyName")
    public Result<Boolean> checkStrategyName(String strategyName, Long id) {
        Result<Boolean> result = new Result<>();
        try {
            if (Check.isNull(strategyName)) {
                throw new Exception("入参不能为空");
            }
            QueryWrapper<KuaiShouDimensionStrategy> dimensionStrategyQueryWrapper = new QueryWrapper<>();
            dimensionStrategyQueryWrapper.eq("strategy_name", strategyName);
            dimensionStrategyQueryWrapper.last("limit 1");
            KuaiShouDimensionStrategy one = kuaiShouDimensionStrategyService.getOne(dimensionStrategyQueryWrapper);
            Boolean trueOrFalse = false;
            if (!Check.isNull(one)) {
                if (!one.getId().equals(id)) {
                    trueOrFalse = true;
                }

            }

            result.setResult(trueOrFalse);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    @ApiOperation(value = "多维度测试策略表-添加", notes = "多维度测试策略表-添加")
    @PostMapping(value = "/create")
    public Result<JSONObject> create(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参不能为空");
            }
            Long id = requestJson.getLong("id");
            if (Check.isNull(id)) {
                throw new Exception("策略id不能为空");
            }
            JSONArray materialArray = requestJson.getJSONArray("materialArray");
            if (Check.isNull(materialArray)) {
                throw new Exception("请选择需要创建的素材");
            }

            List<KuaiShouDimensionMaterial> dimensionMaterials = new ArrayList<>();

            for (int i = 0; i < materialArray.size(); i++) {
                Long photoId = materialArray.getLong(i);
                KuaiShouDimensionMaterial addMaterial = new KuaiShouDimensionMaterial();
                addMaterial.setStrategyId(id);
                addMaterial.setPhotoId(photoId);
           /*  String signature = dimensionMaterialService.getSignatureByPhotoId(photoId);
                if (!Check.isNull(signature)) {
                    addMaterial.setSignature(signature);
                }*/
                dimensionMaterials.add(addMaterial);
            }

            dimensionMaterialService.addBatch(dimensionMaterials);
            JSONObject returnJson = kuaiShouDimensionStrategyService.create(id, materialArray);
            result.setResult(returnJson);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param kuaiShouDimensionStrategy
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-分页列表查询", notes = "多维度测试策略表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<KuaiShouDimensionStrategy>> queryPageList(KuaiShouDimensionStrategy kuaiShouDimensionStrategy,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        Result<IPage<KuaiShouDimensionStrategy>> result = new Result<>();
        String strategyName = kuaiShouDimensionStrategy.getStrategyName();
        kuaiShouDimensionStrategy.setStrategyName(null);
        String startDate = kuaiShouDimensionStrategy.getStartDate();
        String endDate = kuaiShouDimensionStrategy.getEndDate();
        if (Check.isNull(startDate) || Check.isNull(endDate)) {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            startDate = nowDate;
            endDate = nowDate;
        }
        kuaiShouDimensionStrategy.setStartDate(null);
        kuaiShouDimensionStrategy.setEndDate(null);
        QueryWrapper<KuaiShouDimensionStrategy> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouDimensionStrategy, req.getParameterMap());
        if (!Check.isNull(strategyName)) {
            queryWrapper.like("strategy_name", strategyName);
        }
        queryWrapper.orderByDesc("create_time");
        String userId = kuaiShouDimensionStrategy.getUserId();
        if (Check.isNull(userId)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = sysUser.getId();
        }
        String roleCode = sysRoleService.getRoleCodeByUserId(userId);
        List<String> userIds = new ArrayList<>();
        if ("CompanyManager".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if ("bytedanceDirector".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if ("kuaishouDirector".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if (!"admin".equals(roleCode)) {
            userIds.add(userId);
        }
        if (!Check.isNull(userIds)) {
            queryWrapper.in("user_id", userIds);
        }
        queryWrapper.orderByDesc("create_time");
        Page<KuaiShouDimensionStrategy> page = new Page<KuaiShouDimensionStrategy>(pageNo, pageSize);
        IPage<KuaiShouDimensionStrategy> pageList = kuaiShouDimensionStrategyService.page(page, queryWrapper);
        List<KuaiShouDimensionStrategy> records = pageList.getRecords();
        if (!Check.isNull(records)) {
            for (KuaiShouDimensionStrategy strategy : records) {
                Long id = strategy.getId();
                List<KuaiShouDimensionAccount> accountList = kuaiShouDimensionAccountService.getListByStrategyId(id, null);
                if (Check.isNull(accountList)) {
                    continue;
                }
                JSONArray accountIds = new JSONArray(); // 需要查询报表数据的账户集合
                for (KuaiShouDimensionAccount account : accountList) {
                    accountIds.add(account.getAccountId());
                }
                if (!Check.isNull(accountIds)) {
                    JSONObject dataJson = reportAccountDailyService.getReportData(startDate, endDate, accountIds);
                    strategy.setReportData(dataJson);
                }
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param strategyJson
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-添加", notes = "多维度测试策略表-添加")
    @PostMapping(value = "/insertOrUpdate")
    public Result<KuaiShouDimensionStrategy> add(@RequestBody JSONObject strategyJson) {
        Result<KuaiShouDimensionStrategy> result = new Result<>();
        try {
            if (Check.isNull(strategyJson)) {
                throw new Exception("策略配置不能为空");
            }

            JSONArray appInfoArray = strategyJson.getJSONArray("appInfoArray");
            if (Check.isNull(appInfoArray)) {
                throw new Exception("策略配置应用不能为空");
            }
            String userId = strategyJson.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("userId不能为空");
            }
            kuaiShouDimensionStrategyService.insertStrategy(userId, strategyJson);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param kuaiShouDimensionStrategy
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-编辑", notes = "多维度测试策略表-编辑")
    @PostMapping(value = "/edit")
    public Result<KuaiShouDimensionStrategy> edit(@RequestBody KuaiShouDimensionStrategy kuaiShouDimensionStrategy) {
        Result<KuaiShouDimensionStrategy> result = new Result<KuaiShouDimensionStrategy>();
        KuaiShouDimensionStrategy kuaiShouDimensionStrategyEntity = kuaiShouDimensionStrategyService.getById(kuaiShouDimensionStrategy.getId());
        if (kuaiShouDimensionStrategyEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = kuaiShouDimensionStrategyService.updateById(kuaiShouDimensionStrategy);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-通过id删除", notes = "多维度测试策略表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            kuaiShouDimensionStrategyService.removeById(id);
            kuaiShouDimensionAccountService.removeByStrategyId(id);
            variableService.removeByStrategyId(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-批量删除", notes = "多维度测试策略表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<KuaiShouDimensionStrategy> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<KuaiShouDimensionStrategy> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaiShouDimensionStrategyService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "多维度测试策略表-通过id查询", notes = "多维度测试策略表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<KuaiShouDimensionStrategy> queryById(@RequestParam(name = "id", required = true) Long id) {
        Result<KuaiShouDimensionStrategy> result = new Result<>();
        KuaiShouDimensionStrategy kuaiShouDimensionStrategy = kuaiShouDimensionStrategyService.getById(id);
        if (kuaiShouDimensionStrategy == null) {
            result.error500("未找到对应实体");
        } else {
            List<KuaiShouDimensionAccount> accountList = kuaiShouDimensionAccountService.getListByStrategyId(id, null);
            if (!Check.isNull(accountList)) {
                JSONArray accountIds = new JSONArray(); // 需要查询报表数据的账户集合
                JSONArray appInfoArray = new JSONArray();
                JSONArray creativeArray = new JSONArray();
                JSONArray crowdArray = new JSONArray();
                for (KuaiShouDimensionAccount account : accountList) {
                    accountIds.add(account.getAccountId());
                    UserAllocation accountInfo = userAllocationService.getByAccountId(account.getAccountId());
                    JSONObject appInfo = new JSONObject();
                    appInfo.put("accountId", account.getAccountId());
                    if (!Check.isNull(accountInfo)) {
                        appInfo.put("accountName", accountInfo.getAuthName());
                    }
                    appInfo.put("accountStatus", account.getAccountStatus());
                    appInfo.put("appId", account.getAppId());
                    appInfo.put("clickTrackUrl", account.getClickTrackUrl());
                    appInfo.put("actionbarClickUrl", account.getActionbarClickUrl());
                    appInfo.put("useSchemaUri", account.getUseSchemaUri());
                    if (!Check.isNull(account.getSchemaUri())) {
                        appInfo.put("schemaUri", account.getSchemaUri());
                    }
                    KuaiShouAppList kuaiShouAppInfo = appListService.getAppInfo(account.getAccountId(), account.getAppId());
                    if (!Check.isNull(kuaiShouAppInfo)) {
                        appInfo.put("appName", kuaiShouAppInfo.getAppName());
                        appInfo.put("appVersion", kuaiShouAppInfo.getAppVersion());
                        appInfo.put("platform", kuaiShouAppInfo.getPlatform());
                    }
                    appInfoArray.add(appInfo);
                    JSONObject creative = new JSONObject();
                    creative.put("accountId", account.getAccountId());
                    if (!Check.isNull(accountInfo)) {
                        creative.put("accountName", accountInfo.getAuthName());
                    }
                    creative.put("creativeCategory", account.getCreativeCategory());
                    creative.put("creativeTag", account.getCreativeTag());
                    creativeArray.add(creative);

                    JSONObject crowd = new JSONObject();
                    crowd.put("accountId", account);
                    if (!Check.isNull(accountInfo)) {
                        crowd.put("accountName", accountInfo.getAuthName());
                    }
                    if (!Check.isNull(account.getPopulation())) {
                        crowd.put("population", JSONArray.parseArray(account.getPopulation()));
                    }
                    if (!Check.isNull(account.getExcludePopulation())) {
                        crowd.put("excludePopulation", JSONArray.parseArray(account.getExcludePopulation()));
                    }
                    if (!Check.isNull(account.getPaidAudience())) {
                        crowd.put("paidAudience", JSONArray.parseArray(account.getPaidAudience()));
                    }
                    crowdArray.add(crowd);
                }
                kuaiShouDimensionStrategy.setAppInfoArray(appInfoArray);
                kuaiShouDimensionStrategy.setCreativeArray(creativeArray);
                kuaiShouDimensionStrategy.setCrowdArray(crowdArray);
            }
            result.setResult(kuaiShouDimensionStrategy);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<KuaiShouDimensionStrategy> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                KuaiShouDimensionStrategy kuaiShouDimensionStrategy = JSON.parseObject(deString, KuaiShouDimensionStrategy.class);
                queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouDimensionStrategy, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<KuaiShouDimensionStrategy> pageList = kuaiShouDimensionStrategyService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "多维度测试策略表列表");
        mv.addObject(NormalExcelConstants.CLASS, KuaiShouDimensionStrategy.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("多维度测试策略表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<KuaiShouDimensionStrategy> listKuaiShouDimensionStrategys = ExcelImportUtil.importExcel(file.getInputStream(), KuaiShouDimensionStrategy.class, params);
                kuaiShouDimensionStrategyService.saveBatch(listKuaiShouDimensionStrategys);
                return Result.ok("文件导入成功！数据行数:" + listKuaiShouDimensionStrategys.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
