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

import cn.com.ctop.common.module.service.ISysUserService;
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 cn.com.ctop.kuaishou.modules.report.service.ISalesBudgetService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/budget")
public class SalesBudgetController {
    @Autowired
    private ISalesBudgetService salesBudgetService;
    @Autowired
    private ISysUserService sysUserService;

    @GetMapping("/report")
    public Result<Object> getOperateGroupInfo(String userId, String mediaId, String date, Integer pageNo, Integer pageSize) {
        try {

            if (Check.isNull(date)) {
                throw new Exception("请传入日期");
            }
            String roleCode = sysUserService.getRoleCodeByUserId(userId);
            String saleId = null;
            if (!"admin".equals(roleCode) && !"saleDirector".equals(roleCode)) {
                saleId = userId;
            }
            Long statDate = Long.valueOf(date.replace("-", ""));
            if ("1".equals(mediaId)) {
                return salesBudgetService.bytedanceSalesReport(saleId, statDate, pageNo, pageSize);
            } else {
                return salesBudgetService.kuaiShouSalesReport(saleId, statDate, pageNo, pageSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @GetMapping("/ocpxList")
    public Result<List> ocpxList(String mediaId) {
        try {

            if (Check.isNull(mediaId)) {
                throw new Exception("媒体");
            }
            List<JSONObject> jsonObjects = salesBudgetService.ocpxList(mediaId);
            return Result.OK(jsonObjects);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("失败", null);
    }


    @GetMapping("/add")
    public JSONObject add(String mediaId, String userId, String addInfo) {

        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(mediaId)) {
                throw new Exception("请传入媒体");
            }

            if (Check.isNull(userId)) {
                throw new Exception("请传入用户ID");
            }
            JSONObject addInfoJson = JSONObject.parseObject(addInfo);

            if (Check.isNull(addInfoJson)) {
                throw new Exception("请传入出价信息");
            }

            Long projectId = addInfoJson.getLong("projectId");
            if (Check.isNull(projectId)) {
                throw new Exception("请传入项目ID");
            }
            BigDecimal budget = addInfoJson.getBigDecimal("budget");
         /*   BigDecimal budget = addInfoJson.getBigDecimal("budget");
            if (Check.isNull(budget)) {
                throw new Exception("请传入预算信息");
            }*/

            JSONArray ruleDetails = addInfoJson.getJSONArray("ruleDetails");
            if (Check.isNull(ruleDetails)) {
                throw new Exception("请传入出价信息");
            }
            salesBudgetService.deleteInfo(projectId);
            List<JSONObject> addList = new ArrayList<>();
            if (!Check.isNull(budget)) {
                JSONObject budgetInfo = new JSONObject();
                budgetInfo.put("projectId", projectId);
                budgetInfo.put("mediaId", mediaId);
                budgetInfo.put("userId", userId);
                budgetInfo.put("budgetKey", "budget");
                budgetInfo.put("budgetVale", "预算");
                budgetInfo.put("maxValue", budget);
                addList.add(budgetInfo);
            }

            for (int i = 0; i < ruleDetails.size(); i++) {
                JSONObject addJson = new JSONObject();
                addJson.put("projectId", projectId);
                addJson.put("mediaId", mediaId);
                addJson.put("userId", userId);
                JSONObject jsonObject = ruleDetails.getJSONObject(i);
                String budget_key = jsonObject.getString("ocpxCode");
                String budget_vale = jsonObject.getString("ocpxName");
                BigDecimal maxValue = jsonObject.getBigDecimal("maxValue");
                addJson.put("budgetKey", budget_key);
                addJson.put("budgetVale", budget_vale);
                addJson.put("maxValue", maxValue);
                addList.add(addJson);
            }
            salesBudgetService.adds(addList);
            returnJson.put("success", true);
            returnJson.put("message", "设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("success", false);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getById")
    public JSONObject getById(Long projectId) {

        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(projectId)) {
                throw new Exception("请传入项目ID");
            }
            JSONObject data = salesBudgetService.getById(projectId);
            returnJson.put("success", true);
            returnJson.put("message", "设置成功");
            returnJson.put("data", data);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("success", false);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/exportReport")
    public void exportReport(HttpServletResponse response, String userId, String mediaId, String date) {
        try {
            if (Check.isNull(date)) {
                throw new Exception("请传入日期");
            }
            String roleCode = sysUserService.getRoleCodeByUserId(userId);
            String saleId = null;
            if (!"admin".equals(roleCode) && !"saleDirector".equals(roleCode)) {
                saleId = userId;
            }
            Long statDate = Long.valueOf(date.replace("-", ""));
            Result<Object> result = null;
            if ("1".equals(mediaId)) {
                result = salesBudgetService.bytedanceSalesReport(saleId, statDate, 1, 99999);
            } else {
                result = salesBudgetService.kuaiShouSalesReport(saleId, statDate, 1, 99999);
            }
            PageInfo<JSONObject> pageInfo = (PageInfo<JSONObject>) result.getResult();
            List<JSONObject> list = pageInfo.getList();

            List<List<Object>> excelList = new ArrayList<>();
            if (!Check.isNull(list)) {
                list.forEach(data -> {
                    List<Object> temp = new ArrayList<>();
                    temp.add(data.getString("projectName"));//项目
                    StringBuffer buffer1 = new StringBuffer();
                    buffer1.append("销售：").append(data.getString("saleName")).append(String.valueOf((char) 10))
                            .append("运营：").append(data.getString("responsibleName"));
                    temp.add(buffer1);//相关人
                    StringBuffer buffer2 = new StringBuffer();
                    JSONObject budgetJson = data.getJSONObject("budgetJson");
                    String actualBudget = null;
                    String setBudget = null;
                    String subtract = null;
                    Integer budgetCompare = null;
                    String colorSubtract = null;
                    if (!Check.isNull(budgetJson)) {
                        actualBudget = budgetJson.getString("actualBudget");
                        setBudget = budgetJson.getString("setBudget");
                        subtract = budgetJson.getString("subtract");
                        budgetCompare = budgetJson.getInteger("compare");
                    }
                    if (!Check.isNull(setBudget)) {
                        buffer2.append("预算：").append(setBudget);
                    }
                    if (!Check.isNull(actualBudget)) {
                        buffer2.append(String.valueOf((char) 10)).append("消耗：").append(actualBudget);
                    }

                    if (!Check.isNull(budgetCompare) && budgetCompare == 0) {
                        colorSubtract = "-";
                    } else if (!Check.isNull(budgetCompare) && budgetCompare > 0) {
                        colorSubtract = ":red" + "↑" + subtract;
                    } else if (!Check.isNull(budgetCompare) && budgetCompare < 0) {
                        colorSubtract = ":green" + "↓" + subtract;
                    } else {
                        colorSubtract = "-";
                    }
                    if (!colorSubtract.equals("-")) {
                        buffer2.append(String.valueOf((char) 10)).append("差值：").append(colorSubtract);
                    }
                    temp.add(buffer2);//预算情况


                    StringBuffer buffer3 = new StringBuffer();
                    JSONArray costArray = data.getJSONArray("costArray");
                    if (!Check.isNull(costArray)) {

                        for (int i = 0; i < costArray.size(); i++) {
                            JSONObject obj = costArray.getJSONObject(i);
                            String cost = obj.getString("cost");
                            Integer costCompare = obj.getInteger("compare");
                            String colorCost = null;
                            if (i > 0) {
                                buffer3.append(String.valueOf((char) 10));
                            }

                            if (!Check.isNull(costCompare) && costCompare == 0) {
                                colorCost = cost;
                            } else if (!Check.isNull(costCompare) && costCompare > 0) {
                                colorCost = ":hong" + "↑" + cost;
                            } else if (!Check.isNull(costCompare) && costCompare < 0) {
                                colorCost = ":lv" + "↓" + cost;
                            }

                            buffer3.append(obj.getString("name")).append(" 考核：").append(obj.getString("setCost"))
                                    .append("  实际：").append(colorCost).append("&br;");
                        }
                    }
                    temp.add(buffer3);//成本情况
                    if ("1".equals(mediaId)) {
                        temp.add(data.getString("active"));//激活数
                        temp.add(data.getString("activeCost"));//激活成本
                        temp.add(data.getString("attributionNextDayOpenCnt"));//次留
                        temp.add(data.getString("attributionNextDayOpenRate"));//次留率
                        temp.add(data.getString("attributionNextDayOpenCost"));//次留成本
                        temp.add(data.getString("form"));//表单数
                        temp.add(data.getString("formCost"));//表单成本
                        temp.add(data.getString("payCount"));//付费数
                        temp.add(data.getString("payCost"));//付费成本
                        temp.add(data.getString("gameAddiction"));//关键行为数
                        temp.add(data.getString("gameAddictionCost"));//关键行为成本
                        temp.add(data.getString("register"));//注册数
                        temp.add(data.getString("registerCost"));//注册成本
                        temp.add(data.getString("loanCompletion"));//完件数
                        temp.add(data.getString("loanCompletionCost"));//完件成本
                        temp.add(data.getString("preLoanCredit"));//授信数
                        temp.add(data.getString("preLoanCreditCost"));//授信成本
                        temp.add(data.getString("inAppUv"));//app内访问数
                        temp.add(data.getString("inAppUvCost"));//app内访问成本
                        temp.add(data.getString("inAppPay"));//app内付费数
                        temp.add(data.getString("inAppPayCost"));//app内付费成本
                        temp.add(data.getString("statPayAmount"));//首日roi

                    } else {
                        temp.add(data.getString("activation"));//激活数
                        temp.add(data.getString("activationCost"));//激活成本
                        temp.add(data.getString("eventNextDayStay"));//次留
                        temp.add(data.getString("eventNextDayStayRate"));//次留率
                        temp.add(data.getString("eventNextDayStayCost"));//次留成本
                        temp.add(data.getString("formCount"));//表单数
                        temp.add(data.getString("formCountCost"));//表单成本
                        temp.add(data.getString("eventPay"));//付费数
                        temp.add(data.getString("eventCost"));//付费成本
                        temp.add(data.getString("keyAction"));//关键行为数
                        temp.add(data.getString("keyActionCost"));//关键行为成本
                        temp.add(data.getString("eventAppInvoked"));//唤起数
                        temp.add(data.getString("eventAppInvokedCost"));//唤起成本
                        temp.add(data.getString("eventPayPurchaseAmountFirstDayCost"));//roi
                        temp.add(data.getString("eventThreeDayStayByConversionCost"));//3留
                        temp.add(data.getString("eventWeekStayByConversionCost"));//7留
                    }
                    excelList.add(temp);
                });
            }
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = new String[]{};
            if ("1".equals(mediaId)) {
                titles = new String[]{"项目", "相关人", "预算情况", "成本情况", "激活数", "激活成本", "次留", "次留率", "次留成本"
                        , "表单数", "表单成本", "付费数", "付费成本", "关键行为数", "关键行为成本", "注册数", "注册成本", "完件数"
                        , "完件成本", "授信数", "授信成本", "app内访问数", "app内访问成本", "app内付费数", "app内付费成本", "首日roi"};
            } else {
                titles = new String[]{"项目", "相关人", "预算情况", "成本情况", "激活数", "激活成本", "次留", "次留率", "次留成本"
                        , "表单数", "表单成本", "付费数", "付费成本", "关键行为数", "关键行为成本", "唤起数", "唤起成本", "roi", "3留", "7留"};
            }
            String sheetName = null;
            if (mediaId.equals("1")) {
                sheetName = "头条成本报表";
            } else if (mediaId.equals("2")) {
                sheetName = "快手成本报表";
            }
            eeu.exportExcelBudget(workbook, 0, sheetName, titles, excelList);
            HttpUtils.setResponseHeader(response, "销售成本报表.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
