package com.winsun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.core.util.IOUtils;
import com.winsun.bean.ManagerKpi;
import com.winsun.bean.SysUser;
import com.winsun.mapper.*;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.ImportExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 总经理KPI
 * @Author: pxl
 * @create 2020/4/29 14:08
 */
@Slf4j
@RestController
@RequestMapping("/managerKpi")
public class ManagerKpiController extends BaseController {
    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;
    /**
     * 总经理KPI信息模板列名
     */
    private static String SL_month = "月份";
    private static String SL_county = "县分";
    private static String SL_name = "校园督导";
    private static String SL_performanceBase = "绩效基数";
    private static String SL_rwKpi = "移动入网\n（30%）";
    private static String SL_wxKpi = "存量维系\n（30%）";
    private static String SL_yyKpi = "团队运营\n（25%）";
    private static String SL_workKpi = "每月工作\n（15%）";
    private static String SL_totalBonus = "18年5月至今累计佣金";
    private static String SL_totalFund = "18年5月至今月累计分成";
    private static String SL_autumnBonus = "秋营达量奖";

    @Autowired
    private ManagerKpiMapper managerKpiMapper;
    @Autowired
    private LzKpiMapper lzKpiMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private HhrUserMapper hhrUserMapper;
    @Autowired
    private SalesListMapper salesOrderMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;
    /**
     * 总经理KPI信息添加
     *
     * @param lzKpi 添加对象json字符串
     * @return
     */
    @Permission(menuname = "添加总经理KPI信息", value = "insert", method = RequestMethod.POST)
    public ResponseData<String> insertProduct(@RequestParam("lzKpi") String lzKpi) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        HashMap hashMap = JSON.parseObject(lzKpi, HashMap.class);
        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        String account = hashMap.get("account").toString();
        String substName = hashMap.get("substName").toString();
        sysWrapper.eq(StringUtils.isNotBlank(account),"account",account);
        sysWrapper.eq(StringUtils.isNotBlank(substName),"name",substName);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        if(sysUserList.size()>0){
            /*ManagerKpi managerKpi = new ManagerKpi();
            managerKpi.setUserId(Integer.valueOf(sysUserList.get(0).getId()));
            managerKpi.setMonth(hashMap.get("month").toString());
            managerKpi.setRechargeNum(Integer.valueOf(hashMap.get("rechargeNum").toString()));
            managerKpi.setRechargeWage(Integer.valueOf(hashMap.get("rechargeWage").toString()));
            managerKpi.setKpi(Integer.valueOf(hashMap.get("kpi").toString()));
            managerKpi.setKpiWage(Integer.valueOf(hashMap.get("kpiWage").toString()));
            managerKpi.setWage(Integer.valueOf(hashMap.get("wage").toString()));
            managerKpiMapper.insert(managerKpi);*/
            return ResponseData.success("添加成功！");
        }
        return ResponseData.error("账号不存在?");
    }

    /**
     * 总经理KPI删除
     * @param id 需要删除的id
     * @return
     */
    @Permission(menuname = "删除正则信息", value = "delete", method = RequestMethod.POST)
    public ResponseData<String> deleteProduct(@RequestParam(name="id", required = false) String id,@RequestParam(name="isdel", required = false) String isdel) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        //Wrapper wrapper = new EntityWrapper<>();
        //wrapper.eq(StringUtils.isNotBlank(id),"id", id);
        //Map<String, Object> dataMapping = new HashMap<>();
        //dataMapping.put("is_del", isdel);
        //lzKpiMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if(StringUtils.isNotBlank(id)){
            /*lzWageMpapper.deleteById(id);*/
            return ResponseData.success("操作成功！");
        }
        return ResponseData.error("删除id不能为空!");
    }

    /**
     * 修改总经理KPI信息
     * @param lzKpi 编辑对象json字符串
     * @return
     */
    @Permission(menuname = "修改总经理KPI信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updateProduct(@RequestParam("lzKpi") String lzKpi) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        /*LzKpi pro = JSON.parseObject(lzKpi, LzKpi.class);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", pro.getId());
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("report_daily", pro.getReportDaily());
        dataMapping.put("collective_sales", pro.getCollectiveSales());
        dataMapping.put("weekly_meeting", pro.getWeeklyMeeting());
        dataMapping.put("organ_training", pro.getOrganTraining());
        dataMapping.put("design_plan", pro.getDesignPlan());
        dataMapping.put("kpi", pro.getKpi());
        dataMapping.put("user_id", pro.getUserId());
        dataMapping.put("month", pro.getMonth());
        dataMapping.put("is_Del", pro.getIsDel());
        lzWageMpapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);*/
        return ResponseData.success("修改成功！");
    }

    /**
     * @param name
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询总经理KPI信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<ManagerKpi>> listProduct(
            @RequestParam(name = "name", required = false) String name,@RequestParam(name = "month", required = false) String month,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        Page<ManagerKpi> page = new Page<>(pageNo, pageSize);
        Wrapper<ManagerKpi> managerKpiWrapper = new EntityWrapper<>();
        managerKpiWrapper.like(StringUtils.isNotBlank(name),"name",name, SqlLike.DEFAULT);
        if(StringUtils.isNotBlank(month)){
            String[] months = month.split("\\,");
            if(!month.equals(",") && StringUtils.isNotEmpty(month)){
                String m1 = months[0].substring(0,7);
                String month1 = m1.substring(0,4) + m1.substring(5);
                String m2 = months[1].substring(0,7);
                String month2 = m2.substring(0,4) + m2.substring(5);
                managerKpiWrapper.ge(StringUtils.isNotBlank(month1),"month",month1);
                managerKpiWrapper.le(StringUtils.isNotBlank(month2),"month",month2);
            }
        }
        List<ManagerKpi> aPackage = managerKpiMapper.selectPage(page, managerKpiWrapper);
        page.setRecords(aPackage);
        return ResponseData.success(page, "查询成功！");
    }

    /**
     * @param name
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "导出总经理KPI信息", value = "excelOut", method = RequestMethod.POST)
    public void excelOut(
            @RequestParam(name = "name", required = false) String name,@RequestParam(name = "month", required = false) String month,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize
    )  throws IOException {
        ShiroUser user = getShiroUser();

        Wrapper<ManagerKpi> managerKpiWrapper = new EntityWrapper<>();
        List<ManagerKpi> managerKpiList = managerKpiMapper.selectList(managerKpiWrapper);
        List<Map<String, Object>> list = new LinkedList<>();
        for (ManagerKpi managerKpi : managerKpiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("month", managerKpi.getMonth());
            map.put("county", managerKpi.getCounty());
            map.put("name", managerKpi.getName());
            map.put("totalPerformance", managerKpi.getTotalPerformance());
            map.put("performanceBase", managerKpi.getPerformanceBase());
            map.put("yfPerformance", managerKpi.getYfPerformance());
            map.put("kpi", managerKpi.getKpi());
            map.put("rwKpi", managerKpi.getRwKpi());
            map.put("wxKpi", managerKpi.getWxKpi());
            map.put("yyKpi", managerKpi.getYyKpi());
            map.put("workKpi", managerKpi.getWorkKpi());
            map.put("totalBonus", managerKpi.getTotalBonus());
            map.put("totalFund", managerKpi.getTotalFund());
            map.put("autumnBonus", managerKpi.getAutumnBonus());
            map.put("yfBonus", managerKpi.getYfBonus());
            list.add(map);
        }
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.managerKpiExcel("楼长总经理KPI清单"), list);
        try {
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }

    /**
     * 受理订单模板下载
     *
     * @return
     */
    @Permission(menuname = "楼长总经理KPI信息导入模板", method = RequestMethod.POST, value = "downloadMoBan")
    public ResponseData downloadMoBan() {
        ArrayList<String> columns = new ArrayList<>();
        columns.add(SL_month);
        columns.add(SL_county);
        columns.add(SL_name);
        columns.add(SL_performanceBase);
        columns.add(SL_rwKpi);
        columns.add(SL_wxKpi);
        columns.add(SL_yyKpi);
        columns.add(SL_workKpi);
        columns.add(SL_totalBonus);
        columns.add(SL_totalFund);
        columns.add(SL_autumnBonus);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("楼长总经理KPI信息");
            sheet.setColumnWidth(0, 2500);
            sheet.setColumnWidth(1, 2500);
            sheet.setColumnWidth(2, 2500);
            sheet.setColumnWidth(3, 2500);
            sheet.setColumnWidth(4, 2500);
            sheet.setColumnWidth(5, 2500);
            sheet.setColumnWidth(6, 2500);
            sheet.setColumnWidth(7, 2500);
            sheet.setColumnWidth(8, 2500);
            sheet.setColumnWidth(9, 2500);
            sheet.setColumnWidth(10, 2500);

            //添加表头
            final XSSFRow row = sheet.createRow(0);
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            columns.forEach(val -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(val);
            });
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;fileName=data.xlsx");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("楼长总经理KPI信息模板文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        return ResponseData.error("楼长总经理KPI信息模板出错");
    }

    XSSFSheet getXSSFSheet(XSSFSheet sheet, List<String> datas, int firstcol, int lastcol) {
        if (datas.size() == 0) {
            return sheet;
        }
        String[] strdata = new String[datas.size()];
        for (int i = 0; i < datas.size(); i++) {
            strdata[i] = datas.get(i);
        }
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(strdata);
        CellRangeAddressList addressList = new CellRangeAddressList(1, 20000, firstcol, lastcol);
        XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint1, addressList);
        sheet.addValidationData(validation);
        return sheet;
    }

    /**
     * 受理订单
     *
     * @param file 上传的数据文件
     * @return
     */
    @Permission(menuname = "上传数据", value = "importDate", method = RequestMethod.POST)
    public ResponseData<String> updateDatas(@RequestParam(name = "file") MultipartFile file) {
        StringBuffer error = new StringBuffer();
        if (!StringUtils.endsWithAny(file.getOriginalFilename(), "xlsx", "xls")) {
            return ResponseData.error("手工上传数据仅支持Excel文件，其他格式不支持！");
        }
        ShiroUser user = getShiroUser();
        // 当前是否有数据权限
        boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "活动上单员", "数据管理员", "超级管理员"));
        if (!hasDataPermission) {
            return ResponseData.error("无数据权限！");
        }
        ImportExcel importExcel = null;
        try {
            importExcel = new ImportExcel(file, HEADER_NUM, SHEET_INDEX);
        } catch (Exception e) {
            log.error("楼长总经理KPI信息导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        List<Map<String, Object>> listMap = importExcel.getDataListMap();
        if (listMap.size() == 1) {
            return ResponseData.error("文件不能为空");
        }
        if (!listMap.get(0).get("a").toString().equals(SL_month)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(SL_county)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(SL_name)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(SL_performanceBase)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("e").toString().equals(SL_rwKpi)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("f").toString().equals(SL_wxKpi)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("g").toString().equals(SL_yyKpi)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("h").toString().equals(SL_workKpi)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("i").toString().equals(SL_totalBonus)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("j").toString().equals(SL_totalFund)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("k").toString().equals(SL_autumnBonus)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (listMap.get(0).size() != 11) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }

        List<String> userNameList = new LinkedList<>();
        //校验数据
        try {
            //校验数据
            for (int i = 1; i < listMap.size(); i++) {
                Map<String, Object> temp = listMap.get(i);
                if (!temp.containsKey("a")) {
                    return ResponseData.error("第" + (i + 1) + "行的月份不能为空");
                }
                if (StringUtils.isBlank(temp.get("a").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的月份不能为空");
                }
                if (!temp.containsKey("b")) {
                    return ResponseData.error("第" + (i + 1) + "行的县分不能为空");
                }
                if (StringUtils.isBlank(temp.get("b").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的县分不能为空");
                }
                if (!temp.containsKey("c")) {
                    return ResponseData.error("第" + (i + 1) + "行的校园督导不能为空");
                }
                if (StringUtils.isBlank(temp.get("c").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的校园督导不能为空");
                }
                if (!temp.containsKey("d")) {
                    return ResponseData.error("第" + (i + 1) + "行的绩效基数不能为空");
                }
                if (StringUtils.isBlank(temp.get("d").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的绩效基数不能为空");
                }
                if (!temp.containsKey("e")) {
                    return ResponseData.error("第" + (i + 1) + "行的移动入网不能为空");
                }
                if (StringUtils.isBlank(temp.get("e").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的移动入网不能为空");
                }
                if (!temp.containsKey("f")) {
                    return ResponseData.error("第" + (i + 1) + "行的存量维系kpi不能为空");
                }
                if (StringUtils.isBlank(temp.get("f").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的存量维系kpi不能为空");
                }
                if (!temp.containsKey("g")) {
                    return ResponseData.error("第" + (i + 1) + "行的团队运营kpi不能为空");
                }
                if (StringUtils.isBlank(temp.get("g").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的团队运营kpi不能为空");
                }
                if (!temp.containsKey("h")) {
                    return ResponseData.error("第" + (i + 1) + "行的每月工作kpi不能为空");
                }
                if (StringUtils.isBlank(temp.get("h").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的每月工作kpi不能为空");
                }
                if (!temp.containsKey("i")) {
                    return ResponseData.error("第" + (i + 1) + "行的累计佣金不能为空");
                }
                if (StringUtils.isBlank(temp.get("i").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的累计佣金不能为空");
                }
                if (!temp.containsKey("j")) {
                    return ResponseData.error("第" + (i + 1) + "行的累计分成不能为空");
                }
                if (StringUtils.isBlank(temp.get("j").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的累计分成不能为空");
                }
                /*if (!temp.containsKey("k")) {
                    return ResponseData.error("第" + (i + 1) + "行的秋营达标奖不能为空");
                }*/
                /*if (StringUtils.isBlank(temp.get("k").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的秋营达标奖不能为空");
                }*/

            }
        } catch (Exception e) {
            log.error("楼长总经理KPI信息导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        Wrapper<ManagerKpi> managerKpiWrapper = new EntityWrapper<>();
        managerKpiMapper.delete(managerKpiWrapper);
        Integer number = 0;
        Date acceptDate = new Date();
        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            ManagerKpi managerKpi = new ManagerKpi();
            DecimalFormat df = new DecimalFormat("#.0");

            String month = map.get("a").toString();
            managerKpi.setMonth(month);
            managerKpi.setCounty(map.get("b").toString());
            managerKpi.setName(map.get("c").toString());
            //绩效基数
            Integer performanceBase = Integer.valueOf(map.get("d").toString());
            managerKpi.setPerformanceBase(performanceBase);

            Integer rwKpi = Integer.valueOf(map.get("e").toString());
            managerKpi.setRwKpi(rwKpi);
            Integer wxKpi = Integer.valueOf(map.get("f").toString());
            managerKpi.setWxKpi(wxKpi);
            Integer yyKpi = Integer.valueOf(map.get("g").toString());
            managerKpi.setYyKpi(yyKpi);
            Integer workKpi = Integer.valueOf(map.get("h").toString());
            managerKpi.setWorkKpi(workKpi);
            //kpi=移动入网kpi+存量维系kpi+团队运营kpi+每月工作kpi
            Integer kpi = rwKpi+wxKpi+yyKpi+workKpi;
            managerKpi.setKpi(kpi);
            //应发绩效=绩效基数*（kpi/100）
            double formance = performanceBase * kpi / 100;
            String tt0 = df.format(formance);
            double yfPerformance = Double.valueOf(tt0);
            managerKpi.setYfPerformance(yfPerformance);
            //累计佣金
            double bonus = Double.valueOf(map.get("i").toString());
            String tt1 = df.format(bonus);
            double totalBonus = Double.valueOf(tt1);
            managerKpi.setTotalBonus(totalBonus);
            //累计分成
            double fund = Double.valueOf(map.get("j").toString());
            String tt2 = df.format(fund);
            double totalFund = Double.valueOf(tt2);
            managerKpi.setTotalFund(totalFund);
            //秋营达标奖
            double autumnBonus = 0;
            if (!StringUtils.isBlank(map.get("k").toString())) {
                autumnBonus = Double.valueOf(map.get("k").toString());
                String tt = df.format(autumnBonus);
                autumnBonus = Double.valueOf(tt);
            }
            managerKpi.setAutumnBonus(autumnBonus);
            //应发提成=累计分成+秋营达量奖
            double yfBonus = autumnBonus + totalFund;
            managerKpi.setYfBonus(yfBonus);
            //绩效佣金= 应发绩效+累计分成
            managerKpi.setTotalPerformance((yfPerformance+totalFund)+"");

            number  += managerKpiMapper.insert(managerKpi);
        }
        return ResponseData.success(error.toString(), "导入完成");
    }
}
