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

import cn.com.ctop.common.module.entity.AccountCompensation;
import cn.com.ctop.common.module.service.IAccountCompensationService;
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.entity.KuaishouOperationReport;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouOperationReportService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
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.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 运营绩效
 */
@Slf4j
@Api(tags = "运营绩效")
@RestController
@RequestMapping("/kuaishou/operationReport")
public class KuaishouOperationReportController {
    @Autowired
    private IKuaishouOperationReportService kuaishouOperationReportService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IAccountCompensationService compensationService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询季度消耗
     * 条件：日期，岗位，人员
     */
    @ApiOperation(value = "运营绩效-分页列表查询", notes = "运营绩效-分页列表查询")
    @GetMapping(value = "/queryMonthlyData")
    public Result<Object> queryMonthlyData(String mediaId, Integer time, String role, String userId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(mediaId) || Check.isNull(time)) {
                return Result.error("请选择媒体或季度");
            }
            if (mediaId.equals("1")) {
                return kuaishouOperationReportService.queryToutiaoMonthlyData(time, role, userId, pageNo, pageSize);
            } else {
                return kuaishouOperationReportService.queryKuaishouMonthlyData(time, role, userId, pageNo, pageSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败！");
    }

    /**
     * 查询季度消耗
     * 条件：日期，岗位，人员
     */
    @ApiOperation(value = "运营绩效-分页列表查询", notes = "运营绩效-分页列表查询")
    @GetMapping(value = "/queryQuarterlyData")
    public Result<Object> queryQuarterlyData(String mediaId, Integer time, String role, String userId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(mediaId) || Check.isNull(time)) {
                return Result.error("请选择媒体或季度");
            }
            if ("1".equals(mediaId)) {
                return kuaishouOperationReportService.queryToutiaoQuarterlyCharge(time, role, userId, pageNo, pageSize);
            } else {
                return kuaishouOperationReportService.queryKuaishouQuarterlyCharge(time, role, userId, pageNo, pageSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败！");
    }

    /**
     * 添加
     *
     * @param kuaishouOperationReport
     * @return
     */
    @ApiOperation(value = "运营绩效-添加", notes = "运营绩效-添加")
    @PostMapping(value = "/add")
    public Result<KuaishouOperationReport> add(@RequestBody KuaishouOperationReport kuaishouOperationReport) {
        Result<KuaishouOperationReport> result = new Result<>();
        try {
            kuaishouOperationReportService.save(kuaishouOperationReport);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "运营绩效-通过id删除", notes = "运营绩效-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            kuaishouOperationReportService.removeById(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<KuaishouOperationReport> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<KuaishouOperationReport> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouOperationReportService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "运营绩效-通过id查询", notes = "运营绩效-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<KuaishouOperationReport> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<KuaishouOperationReport> result = new Result<>();
        KuaishouOperationReport kuaishouOperationReport = kuaishouOperationReportService.getById(id);
        if (kuaishouOperationReport == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(kuaishouOperationReport);
            result.setSuccess(true);
        }
        return result;
    }

    @ApiOperation(value = "赔付-添加", notes = "赔付-添加")
    @PostMapping(value = "/addAccountCompensation")
    public Result<AccountCompensation> addAccountCompensation(@RequestBody AccountCompensation account) {
        Result<AccountCompensation> result = new Result<>();
        try {
            //运营赔付扣罚比例：运营、运营助理为50%，运营经理、运营总监显示“-”
            //经理总监赔付比例：经理为30%，总监为20%，运营、运营助理显示“-”
            String roleCode = roleService.getRoleCodeByUserId(account.getUserId());
            if ("operationAssistant".equals(roleCode) || "operator".equals(roleCode)) {
                account.setCompMoney(account.getCompMoney().multiply(new BigDecimal("0.5")));
            } else if (roleCode.contains("Manager")) {
                account.setCompMoney(account.getCompMoney().multiply(new BigDecimal("0.3")));
            }
            compensationService.save(account);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @PostMapping(value = "/queryAccountCompensation")
    public Result<Object> queryAccountCompensation(AccountCompensation accountCompensation,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<JSONObject> pageList = compensationService.queryAccountCompensation(accountCompensation);
        return Result.ok(new PageInfo<>(pageList));
    }

    @GetMapping(value = "/getAllOperatorList")
    public Result<Object> getAllOperatorList(String mediaId) {
        List<String> roleCode = new ArrayList<>();
        //运营助理
        roleCode.add("operationAssistant");
        //运营专员
        roleCode.add("operator");
        //快手运营经理
        roleCode.add("touTiaoOperationManager");
        //快手运营经理
        roleCode.add("kuaishouOperationManager");
        return Result.OK(compensationService.getAllOperatorList(roleCode, mediaId));
    }

    @GetMapping(value = "/getAccountUser")
    public Result<Object> getAccountUser(Long accountId) {
        if (Check.isNull(accountId)) {
            return Result.error("请选择账户");
        }
        return Result.OK(compensationService.getAccountUser(accountId));
    }

    /**
     * 修改运营绩效发放系数
     */
    @GetMapping(value = "/updateUserSalary")
    public Result<Object> updateUserSalaryRatio(String userId, String paySalaryRatio, String paySalary) {
        try {
            SysUser user = new SysUser();
            user.setId(userId);
            if (Check.isNull(userId)) {
                Result.error("请选择人员");
            }
            if (!Check.isNull(paySalaryRatio)) {
                user.setPaySalaryRatio(paySalaryRatio);
            }
            if (!Check.isNull(paySalary)) {
                user.setPaySalary(paySalary);
            }
            sysUserService.updateById(user);
            return Result.ok("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("修改失败");
    }

    /**
     * 导出应季月度消耗
     */
    @GetMapping("/queryMonthlyDataExcel")
    public void queryMonthlyDataExcel(HttpServletResponse response, String mediaId, Integer time, String role, String userId) {
        try {
            Result<Object> result = null;
            if (mediaId.equals("1")) {
                result = kuaishouOperationReportService.queryToutiaoMonthlyData(time, role, userId, 1, 99999);
            } else {
                result = kuaishouOperationReportService.queryKuaishouMonthlyData(time, role, userId, 1, 99999);
            }
            List<List<Object>> excelList = new ArrayList<>();
            PageInfo pageInfo = (PageInfo) result.getResult();
            if (!Check.isNull(pageInfo)) {
                List<JSONObject> list = pageInfo.getList();
                if (!list.isEmpty()) {
                    list.forEach(data -> {
                        List<Object> temp = new ArrayList<>();
                        temp.add(data.getString("userName"));
                        temp.add(data.getString("roleName"));
                        temp.add(data.getString("upTime"));
                        temp.add(data.getString("1totalCharge"));
                        temp.add(data.getString("2totalCharge"));
                        temp.add(data.getString("3totalCharge"));
                        temp.add(data.getString("1KFCharge"));
                        temp.add(data.getString("2KFCharge"));
                        temp.add(data.getString("3KFCharge"));
                        temp.add(data.getString("1FWCharge"));
                        temp.add(data.getString("2FWCharge"));
                        temp.add(data.getString("3FWCharge"));
                        temp.add(data.getString("1JLCharge"));
                        temp.add(data.getString("2JLCharge"));
                        temp.add(data.getString("3JLCharge"));
                        temp.add(data.getString("quitTime"));
                        excelList.add(temp);
                    });
                }
                List<Integer> monthInt = kuaishouOperationReportService.getMonthInt(time);
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"运营", "岗位", "晋升时间",
                        monthInt.get(0) + "月总消耗", monthInt.get(1) + "月总消耗", monthInt.get(2) + "月总消耗",
                        monthInt.get(0) + "月框返消耗", monthInt.get(1) + "月框返消耗", monthInt.get(2) + "月框返消耗",
                        monthInt.get(0) + "月服务消耗", monthInt.get(1) + "月服务消耗", monthInt.get(2) + "月服务消耗",
                        monthInt.get(0) + "月激励消耗", monthInt.get(1) + "月激励消耗", monthInt.get(2) + "月激励消耗",
                        "离职时间"};
                eeu.exportExcelForAttendance(workbook, 0, "运营数据", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询季度消耗 导出
     * 条件：日期，岗位，人员
     */
    @ApiOperation(value = "运营绩效-分页列表查询", notes = "运营绩效-分页列表查询")
    @GetMapping(value = "/queryQuarterlyDataExcel")
    public void queryQuarterlyDataExcel(HttpServletResponse response, String mediaId, Integer time, String role, String userId) {
        try {
            Result<Object> result = null;
            if ("1".equals(mediaId)) {
                result = kuaishouOperationReportService.queryToutiaoQuarterlyCharge(time, role, userId, 1, 99999);
            } else {
                result = kuaishouOperationReportService.queryKuaishouQuarterlyCharge(time, role, userId, 1, 99999);
            }

            List<List<Object>> excelList = new ArrayList<>();
            List<JSONObject> list = (List<JSONObject>) result.getResult();
            if (!Check.isNull(list)) {
                if (!list.isEmpty()) {
                    list.forEach(data -> {
                        List<Object> temp = new ArrayList<>();
                        temp.add(data.getString("userName"));
                        temp.add(data.getString("roleName"));
                        temp.add(data.getString("upTime"));
                        temp.add(data.getString("quitTime"));
                        temp.add(data.getString("totalCharge"));
                        temp.add(data.getString("KFCharge"));
                        temp.add(data.getString("FWCharge"));
                        temp.add(data.getString("KFChargeIsOk"));
                        temp.add(data.getString("manageCharge"));
                        temp.add(data.getString("assistantCharge"));
                        temp.add(data.getString("FWChargeCommission"));
                        temp.add(data.getString("KFChargeCommission"));
                        temp.add(data.getString("manageChargeCommission"));
                        temp.add(data.getString("operateCompensation"));
                        temp.add(data.getString("manageCompensation"));
                        temp.add(data.getString("FWChargeIsOk"));
                        temp.add(data.getString("compMoney"));
                        temp.add(data.getString("paySalary"));
                        temp.add(data.getString("putMoney"));
                        temp.add(data.getString("paySalaryRatio"));
                        temp.add(data.getString("finalPutMoney"));
                        excelList.add(temp);
                    });
                }
                List<Integer> monthInt = kuaishouOperationReportService.getMonthInt(time);
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"运营", "岗位", "晋升时间", "离职时间",
                        "Q" + time + "总消耗", "Q" + time + "框返消耗", "Q" + time + "服务消耗", "框返消耗是否满足30W",
                        "管理消耗", "助理消耗", "服务消耗提成", "框返消耗提成",
                        "管理消耗提成", "运营赔付扣罚比例", "经理/总监赔付扣罚比例", "是否达标",
                        "扣减金额", "是否符合发放", "发放金额", "发放系数", "最终发放金额"
                };
                eeu.exportExcelForAttendance(workbook, 0, "运营绩效", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
