package cn.com.ctop.report.controller;

import cn.com.ctop.common.constant.AccountReportConstants;
import cn.com.ctop.common.constant.CtopAdConstant;
import cn.com.ctop.common.mapper.SysRoleMapper;
import cn.com.ctop.common.service.IProjectMemberService;
import cn.com.ctop.common.service.ISysRoleService;
import cn.com.ctop.common.service.ISysUserService;
import cn.com.ctop.common.service.IUserAllocationService;
import cn.com.ctop.common.utils.Check;
import cn.com.ctop.common.utils.JsonResourceUtil;
import cn.com.ctop.common.utils.ResultMapUtils;
import cn.com.ctop.common.utils.StatusCode;
import cn.com.ctop.report.service.IKuaishouMaterialVideoReportDailyDwService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("material/report")
@Slf4j
public class KuaishouMaterialReportDailyDwController {
    @Autowired
    IKuaishouMaterialVideoReportDailyDwService materialVideoReportDailyDwService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IProjectMemberService projectMemberService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private ISysRoleService roleService;
    /**
     * 获取项目以及账户信息
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/getProjectAccountByUserId")
    public Map<String, Object> getProjectAccount(@RequestBody JSONObject params) {
        Map<String, Object> resultMap = new HashMap<>();
        String getUserId = params.getString("userId");
        String type = params.getString("type");
        if (null == getUserId || "".equals(getUserId.trim()) || null == type || "".equals(type.trim())) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_PARAM_ERROR);
            return resultMap;
        }
        List<Integer> mediaIds = new ArrayList<>();
        if ("kuaishou".equals(type)) {
            mediaIds.add(2);
            mediaIds.add(4);
        } else if (CtopAdConstant.PLATFORM_TYPE_TENCENT_PY.equals(type)) {
            mediaIds.add(CtopAdConstant.PLATFORM_TYPE_TENCENT_INT);
        } else {
            mediaIds.add(1);
            mediaIds.add(3);
        }
        //查询用户角色
        String userId = getUserId;
        String roleCode = sysRoleMapper.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) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
            userIds = null;
        }else{
            userIds.add(userId);
        }
        String operatorId = null;
        if ("operator".equals(roleCode) || roleCode.contains("operationAssistant")) {
            operatorId = getUserId;
        }
        //查询项目信息以及广告主
        List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
        List<JSONObject> haveList = new ArrayList<>();
        if (!Check.isNull(projectList)) {
            //项目id 查询账户人员信息
            Map<Long, List<JSONObject>> accountMap = userAllocationService.getAccountListByProjectList(projectList,operatorId);
            for (int i = 0; i < projectList.size(); i++) {
                JSONObject project = projectList.get(i);
                if (!Check.isNull(project)) {
                    List<JSONObject> accountList = accountMap.get(project.getLong("projectId"));
                    if (!Check.isNull(accountList)) {
                        project.put("accountList", accountList);
                        haveList.add(project);
                    }
                }
            }
        }
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS);
        resultMap.put("data", haveList);
        return resultMap;
    }

    @PostMapping("/kuaishou/list")
    public Result<PageInfo<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {
            int pageSize = requestBody.getInteger("pageSize");
            int pageNo = requestBody.getInteger("pageNo");
            String startDate = requestBody.getString("startDate");
            String mediaType = requestBody.getString("mediaType");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入查询开始时间");
            }
            String endDate = requestBody.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入查询结束时间");
            }

            //开始和结束时间的时间跨度，不能超过60天
            long days = DateUtils.getDiscrepantDays(startDate, endDate) + 1;
            if (days > 60) {
                throw new Exception("开始和结束时间的时间跨度，不能超过60天，请重新选择");
            }

            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getKuaishouVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }
            String userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", Long.parseLong(startDate.replace("-","")));
            requestMap.put("endDate", Long.parseLong(endDate.replace("-","")));

            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }

            if (!Check.isNull(requestBody.getString("target"))) {
                requestMap.put("target", requestBody.getString("target"));
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getInteger("channelType"))) {
                requestMap.put("channelType", requestBody.getInteger("channelType"));
            }
            String roleCode = sysRoleMapper.getRoleCodeByUserId(userId);
            if ("admin".equals(roleCode)) {
                //管理员
            } else if ("clip".equals(roleCode)) {
                requestMap.put("clipId", userId);
            } else if (!Check.isNull(requestBody.getString("clipId"))) {
                requestMap.put("clipId", requestBody.getString("clipId"));
            }

            if ("shot".equals(roleCode)) {
                requestMap.put("shotId", userId);
            } else if (!Check.isNull(requestBody.getString("shotId"))) {
                requestMap.put("shotId", requestBody.getString("shotId"));
            }

            if ("plan".equals(roleCode)) {
                requestMap.put("planId", userId);
            } else if (!Check.isNull(requestBody.getString("planId"))) {
                requestMap.put("planId", requestBody.getString("planId"));
            }

            if ("designTeamLeader".equals(roleCode)) {
                requestMap.put("leaderId", userId);
            } else if (!Check.isNull(requestBody.getString("leaderId"))) {
                requestMap.put("leaderId", requestBody.getString("leaderId"));
            }
            PageInfo<JSONObject> listData = materialVideoReportDailyDwService.getKuaiShouVideoPageReportByMap(requestMap, pageSize, pageNo);
            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            result.setSuccess(true);
            result.setResult(listData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.toString());
        }
        return result;
    }



    @PostMapping("/kuaishou/detail")
    public Result<List<JSONObject>> getReportDetail(@RequestBody JSONObject requestBody) {
        Result<List<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {

            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            String signature = requestBody.getString("signature");
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getDicMapKs());
            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                List<JSONObject> listData = materialVideoReportDailyDwService.getVideoDetailBy(accountIds, startDate, endDate, filedAll, signature);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }
}
