package cn.com.ctop.common.module.achievements.controller;

import cn.com.ctop.common.module.achievements.service.IDesignerService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设计人员绩效
 *
 * @author: zian Y
 * @date: 2022-09-28
 * @cersion: V1.0
 */
@Slf4j
@Api(tags = "设计人员绩效")
@RestController
@RequestMapping("/designer/designerAchievementsController")
public class DesignerAchievementsController {
    @Autowired
    private IDesignerService designerService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 修改绩效中的用户部分信息
     *
     * @param jsonObject
     * @param
     * @return
     */
    @PostMapping(value = "/updateUserHappyProbability")
    public Result updateUserHappyProbability(@RequestBody JSONObject jsonObject) {

        return designerService.updateUserHappyProbability(jsonObject);

    }


    /**
     * 基础信息+爆款 --
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndHotVideoInfo")
    public Result getDesignerCommission(@RequestParam(name = "userId") String userId,
                                        @RequestParam(name = "yearTime") String yearTime,
                                        @RequestParam(name = "monthTime") String monthTime,
                                        @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return designerService.getDesignerBasicsAndHotVideoInfo(userId, yearTime, monthTime, pageNum, pageSize);

    }


    /**
     * 基础信息+绩效 --
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndAch")
    public Result getDesignerBasicsAndAch(@RequestParam(name = "userId") String userId,
                                          @RequestParam(name = "yearTime") String yearTime,
                                          @RequestParam(name = "monthTime") String monthTime,
                                          @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return designerService.getDesignerBasicsAndAch(userId, yearTime, monthTime, pageNum, pageSize);

    }


    /**
     * 基础信息+提成
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndAchAndComInfo")
    public Result getDesignerBasicsAndAchAndComInfo(@RequestParam(name = "userId") String userId,
                                                    @RequestParam(name = "yearTime") String yearTime,
                                                    @RequestParam(name = "monthTime") String monthTime,
                                                    @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return designerService.getDesignerBasicsAndAchAndComInfo(userId, yearTime, monthTime, pageNum, pageSize);

    }


    /**
     * 基础信息+爆款 --
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndHotVideoInfoExcel")
    public void getDesignerBasicsAndHotVideoInfoExcel(HttpServletResponse response,
                                                      @RequestParam(name = "userId") String userId,
                                                      @RequestParam(name = "yearTime") String yearTime,
                                                      @RequestParam(name = "monthTime") String monthTime) {
        try {
            Result<PageInfo<JSONObject>> result = designerService.getDesignerBasicsAndHotVideoInfo(userId, yearTime, monthTime, 1, 99999);
            PageInfo<JSONObject> pageInfo = result.getResult();
            List<List<Object>> excelList = new ArrayList<>();
            Integer month = 0;
            if (!Check.isNull(pageInfo)) {
                List<JSONObject> list = pageInfo.getList();
                if (!list.isEmpty()) {
                    month = list.get(0).getJSONObject("bytedance").getInteger("monthTime1");
                    list.forEach(data -> {
                        List<Object> temp = new ArrayList<>();
                        temp.add(data.getString("userName"));
                        temp.add(data.getString("roleName"));
                        temp.add("1".equals(data.getString("status")) ? "正常" : "冻结");
                        temp.add(data.getString("departName"));
                        JSONObject bytedance = data.getJSONObject("bytedance");
                        JSONObject kuaishou = data.getJSONObject("kuaishou");
                        temp.add(kuaishou.getString("hotNum1"));
                        temp.add(kuaishou.getString("hotNum2"));
                        temp.add(kuaishou.getString("hotNum3"));
                        temp.add(bytedance.getString("hotNum1"));
                        temp.add(bytedance.getString("hotNum2"));
                        temp.add(bytedance.getString("hotNum3"));
                        excelList.add(temp);
                    });
                }
                List<Integer> monthInt = null;
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"姓名", "岗位", "状态", "组别",
                        "快手" + month + "月爆款", "快手" + (month + 1) + "月爆款", "快手" + (month + 2) + "月爆款",
                        "头条" + month + "月爆款", "头条" + (month + 1) + "月爆款", "头条" + (month + 2) + "月爆款"};
                eeu.exportExcelForAttendance(workbook, 0, "设计爆款数据", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 基础信息+绩效 --
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndAchExcel")
    public void getDesignerBasicsAndAchExcel(HttpServletResponse response,
                                             @RequestParam(name = "userId") String userId,
                                             @RequestParam(name = "yearTime") String yearTime,
                                             @RequestParam(name = "monthTime") String monthTime) {
        try {
            Result<PageInfo<JSONObject>> result = null;
            String statDate = DateUtils.formatDate(new Date());
            String key = statDate + "-ACHINFO-" + userId.substring(0, 8).toUpperCase();
            Object hget = redisUtil.hget(key, monthTime);
            if (!Check.isNull(hget)) {
                result = (Result<PageInfo<JSONObject>>) hget;
            } else {
                result = designerService.getDesignerBasicsAndAch(userId, yearTime, monthTime, 1, 9999);
                Map<Object, Object> hmget = redisUtil.hmget(key);
                if (Check.isNull(hmget) || hmget.isEmpty()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put(monthTime, result);
                    redisUtil.hmset(key, map, 80000L);
                } else {
                    redisUtil.hset(key, monthTime, result);
                }
            }
            PageInfo<JSONObject> pageInfo = result.getResult();
            List<List<Object>> excelList = new ArrayList<>();
            Integer month = 0;
            if (!Check.isNull(pageInfo)) {
                List<JSONObject> list = pageInfo.getList();
                if (!list.isEmpty()) {
                    month = list.get(0).getJSONArray("byteDanceData").getJSONObject(0).getInteger("monthTime");
                    list.forEach(data -> {
                        List<Object> temp = new ArrayList<>();
                        temp.add(data.getString("userName"));
                        temp.add(data.getString("roleName"));
                        temp.add("1".equals(data.getString("status")) ? "正常" : "冻结");
                        temp.add(data.getString("departName"));
                        JSONArray bytedance = data.getJSONArray("byteDanceData");
                        JSONArray kuaishou = data.getJSONArray("kuaiShouData");
                        for (int i = 0; i < kuaishou.size(); i++) {//clip剪辑id>plan 编导id>shot 拍摄id
                            JSONObject obj = kuaishou.getJSONObject(i);
                            temp.add(obj.getDouble("cost"));
                            temp.add(obj.getDouble("commission"));
                        }
                        for (int i = 0; i < bytedance.size(); i++) {//clip剪辑id>plan 编导id>shot 拍摄id
                            JSONObject obj = bytedance.getJSONObject(i);
                            temp.add(obj.getDouble("cost"));
                            temp.add(obj.getDouble("commission"));
                        }
                        excelList.add(temp);
                    });
                }
                List<Integer> monthInt = null;
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"姓名", "岗位", "状态", "组别",
                        month + "月快手剪辑消耗", month + "月快手剪辑提成", month + "月快手编导消耗", month + "月快手编导提成", month + "月快手拍摄消耗", month + "月快手拍摄提成",
                        (month + 1) + "月快手剪辑消耗", (month + 1) + "月快手剪辑提成", (month + 1) + "月快手编导消耗", (month + 1) + "月快手编导提成", (month + 1) + "月快手拍摄消耗", (month + 1) + "月快手拍摄提成",
                        (month + 2) + "月快手剪辑消耗", (month + 2) + "月快手剪辑提成", (month + 2) + "月快手编导消耗", (month + 2) + "月快手编导提成", (month + 2) + "月快手拍摄消耗", (month + 2) + "月快手拍摄提成",
                        month + "月头条剪辑消耗", month + "月头条剪辑提成", month + "月头条编导消耗", month + "月头条编导提成", month + "月头条拍摄消耗", month + "月头条拍摄提成",
                        (month + 1) + "月头条剪辑消耗", (month + 1) + "月头条剪辑提成", (month + 1) + "月头条编导消耗", (month + 1) + "月头条编导提成", (month + 1) + "月头条拍摄消耗", (month + 1) + "月头条拍摄提成",
                        (month + 2) + "月头条剪辑消耗", (month + 2) + "月头条剪辑提成", (month + 2) + "月头条编导消耗", (month + 2) + "月头条编导提成", (month + 2) + "月头条拍摄消耗", (month + 2) + "月头条拍摄提成"};
                eeu.exportExcelForAttendance(workbook, 0, "设计基础数据", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 基础信息+提成
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/getDesignerBasicsAndAchAndComInfoExcel")
    public void getDesignerBasicsAndAchAndComInfoExcel(HttpServletResponse response,
                                                       @RequestParam(name = "userId") String userId,
                                                       @RequestParam(name = "yearTime") String yearTime,
                                                       @RequestParam(name = "monthTime") String monthTime) {

        try {
            Result<PageInfo<JSONObject>> result = null;
            String statDate = DateUtils.formatDate(new Date());
            String key = statDate + "-COMINFO-" + userId.substring(0, 8).toUpperCase();
            Object hget = redisUtil.hget(key, monthTime);
            if (!Check.isNull(hget)) {
                result = (Result<PageInfo<JSONObject>>) hget;
            } else {
                result = designerService.getDesignerBasicsAndAchAndComInfo(userId, yearTime, monthTime, 1, 9999);
                Map<Object, Object> hmget = redisUtil.hmget(key);
                if (Check.isNull(hmget) || hmget.isEmpty()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put(monthTime, result);
                    redisUtil.hmset(key, map, 80000L);
                } else {
                    redisUtil.hset(key, monthTime, result);
                }
            }
            PageInfo<JSONObject> pageInfo = result.getResult();
            List<List<Object>> excelList = new ArrayList<>();
            Integer month = 0;
            if (!Check.isNull(pageInfo)) {
                List<JSONObject> list = pageInfo.getList();
                if (!list.isEmpty()) {
                    month = list.get(0).getJSONObject("userFrozen").getJSONArray("commissionList").getJSONObject(0).getInteger("monthTime");
                    list.forEach(data -> {
                        List<Object> temp = new ArrayList<>();
                        temp.add(data.getString("userName"));
                        temp.add(data.getString("roleName"));
                        temp.add("1".equals(data.getString("status")) ? "正常" : "冻结");
                        temp.add(data.getString("departName"));
                        JSONObject userFrozen = data.getJSONObject("userFrozen");
                        JSONArray quarterCostList = userFrozen.getJSONArray("quarterCostList");
                        temp.add(quarterCostList.getJSONObject(0).getString("cost"));
                        temp.add(quarterCostList.getJSONObject(1).getString("cost"));
                        temp.add(userFrozen.getString("tatolQuarterCost"));
                        temp.add(userFrozen.getString("leaderCost"));
                        temp.add(userFrozen.getString("materialCostQualifiedFlag"));
                        temp.add(userFrozen.getString("hotVideoNum"));
                        temp.add(userFrozen.getString("openHotVideoNum"));
                        temp.add(userFrozen.getString("hotVideoTotalNum"));
                        temp.add(userFrozen.getString("coefficient"));
                        JSONArray commissionList = userFrozen.getJSONArray("commissionList");
                        temp.add(commissionList.getJSONObject(0).getString("commission"));
                        temp.add(commissionList.getJSONObject(1).getString("commission"));
                        temp.add(commissionList.getJSONObject(2).getString("commission"));
                        temp.add(userFrozen.getString("totalCommission"));
                        temp.add(userFrozen.getString("userHappyGetMoney"));
                        temp.add(userFrozen.getString("remarks"));
                        temp.add("1".equals(userFrozen.getString("paySalary")) ? "是" : "否");
                        temp.add("1".equals(userFrozen.getString("paySalary")) ? userFrozen.getString("userHappyGetMoney") : 0);
                        temp.add("1".equals(data.getString("status")) ? userFrozen.getString("userHappyProbability") : "-");
                        excelList.add(temp);
                    });
                }
                List<Integer> monthInt = null;
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"姓名", "岗位", "状态", "组别",
                        "头条素材消耗", "快手素材消耗", "素材总消耗", "管理消耗", "是否达标", "爆款素材数量", "开屏爆款数量", "爆款总量", "爆款达标"
                        , month + "月提成", (month + 1) + "月提成", (month + 2) + "月提成", "季度提成汇总", "负责人提成", "提成发放金额", "备注", "是否发放", "最终发放金额", "离职发放比例"
                };
                eeu.exportExcelForAttendance(workbook, 0, "设计基础数据", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据角色查询人员
     *
     * @param roleName
     * @return
     */
    @GetMapping(value = "/getUserByRoleName")
    public Result getUserByRoleName(@RequestParam(name = "roleName") String roleName) {
        return designerService.getUserByRoleName(roleName);

    }


}
