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.*;
import com.winsun.mapper.*;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.ImportExcel;
import com.winsun.utils.MyBatisPlusUpdateUtils;
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.SimpleDateFormat;
import java.util.*;

/**
 * 楼长KPI校检
 * @Author: xiangli
 * @Date:
 */
@Slf4j
@RestController
@RequestMapping("/lzKpi")
public class LzKpiController extends BaseController {
    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;
    /**
     * KPI信息模板列名
     */
    private static String SL_reportDaily = "汇总任务量";
    private static String SL_collectiveSales = "参与集中营销";
    private static String SL_weeklyMeeting = "组织周例会";
    private static String SL_organTraining = "定制扫楼营销方案";
    private static String SL_designPlan = "组织培训";
    private static String SL_kpi = "KPI总值";
    private static String SL_month = "KPI月份";
    private static String SL_sysuName = "姓名(必填)";
    private static String SL_account = "账号(必填)";
    private static String SL_substName = "县分";
    private static String SL_schoolName = "学校";

    @Autowired
    private LzKpiMapper lzKpiMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private HhrUserMapper hhrUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;


    /**
     * 校检账号是否存在
     *
     * @param account 添加对象json字符串
     * @return
     */
    @Permission(menuname = "校检账号是否存在", value = "checkAccount", method = RequestMethod.POST)
    public ResponseData<String> checkAccount(@RequestParam("account") String account) {
        ShiroUser user = getShiroUser();

        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        sysWrapper.eq("account",account);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        if(sysUserList.size()>0){
            return ResponseData.success("账号已存在！");
        }
        return ResponseData.error("账号不存在!!!");
    }
    /**
     * 楼长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){
            LzKpi kpi = new LzKpi();
            kpi.setUserId(sysUserList.get(0).getId());
            kpi.setDesignPlan(Integer.valueOf(hashMap.get("designPlan").toString()));
            kpi.setOrganTraining(Integer.valueOf(hashMap.get("organTraining").toString()));
            kpi.setReportDaily(Integer.valueOf(hashMap.get("reportDaily").toString()));
            kpi.setWeeklyMeeting(Integer.valueOf(hashMap.get("weeklyMeeting").toString()));
            kpi.setCollectiveSales(Integer.valueOf(hashMap.get("collectiveSales").toString()));
            kpi.setKpi(Integer.valueOf(hashMap.get("kpi").toString()));
            kpi.setMonth(hashMap.get("month").toString());
            kpi.setIsDel("0");
            lzKpiMapper.insert(kpi);
            return ResponseData.success("添加成功！");
        }
        return ResponseData.error("账号不存在!!!");
    }

    /**
     * kpi删除
     * @param id 需要删除的id
     * @return
     */
    @Permission(menuname = "删除楼长KPI信息", 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)){
            lzKpiMapper.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());
        lzKpiMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        return ResponseData.success("修改成功！");
    }

    /**
     *
     * @param userName
     * @param substName
     * @param schoolName
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询楼长KPI信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<Map<String,Object>>> listProduct(
            @RequestParam(name = "userName", required = false) String userName,@RequestParam(name = "substName", required = false) String substName,
            @RequestParam(name = "schoolName", required = false) String schoolName,@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<Map<String,Object>> page = new Page<>(pageNo, pageSize);
        List<Map<String,Object>> dataList = new ArrayList<>();
        List<Map<String,Object>> list = new ArrayList<>();

        List<String> userIds01 = new ArrayList<>();
        Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
        hhrUserWrapper.eq("position","楼长");
        List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
        for (HhrUser hhrUser : hhrUserList) {
            userIds01.add(hhrUser.getId());
        }
        List<String> userIds1 = new ArrayList<>();
        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        sysWrapper.in("id",userIds01);
        sysWrapper.like(StringUtils.isNotBlank(userName), "name", userName, SqlLike.DEFAULT);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        for (SysUser sysUser : sysUserList) {
            userIds1.add(sysUser.getId());
        }
        if(sysUserList.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        List<Integer> schoolIds = new ArrayList<>();
        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.eq(StringUtils.isNotBlank(substName), "sub_name", substName);
        schoolWrapper.eq(StringUtils.isNotBlank(schoolName), "school_name", schoolName);
        List<School> schoolList = schoolMapper.selectList(schoolWrapper);
        for (School school : schoolList) {
            schoolIds.add(school.getId());
        }
        if(schoolList.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }

        List<String> userIds = new ArrayList<>();
        Wrapper<UserSchool> usWrapper = new EntityWrapper<>();
        usWrapper.in("user_id",userIds1);
        usWrapper.in("school_id",schoolIds);
        List<UserSchool> userSchoolList = userSchoolMapper.selectList(usWrapper);
        for (UserSchool userSchool : userSchoolList) {
            userIds.add(userSchool.getUserId());
        }
        Wrapper<LzKpi> wrapper = new EntityWrapper();
        if(month.length()>7){
            month = month.substring(0,7);
        }
        wrapper.eq(StringUtils.isNotBlank(month),"month",month);
        wrapper.in("user_id",userIds);
        List<LzKpi> lzKpis = lzKpiMapper.selectList(wrapper);
        if(lzKpis.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        for (LzKpi lzKpi : lzKpis) {
            Map<String,Object> map = new HashMap<>();
            map.put("id",lzKpi.getId());
            map.put("reportDaily",lzKpi.getReportDaily());
            map.put("collectiveSales",lzKpi.getCollectiveSales());
            map.put("weeklyMeeting",lzKpi.getWeeklyMeeting());
            map.put("organTraining",lzKpi.getOrganTraining());
            map.put("designPlan",lzKpi.getDesignPlan());
            map.put("kpi",lzKpi.getKpi());
            map.put("userId",lzKpi.getUserId());
            map.put("month",lzKpi.getMonth());
            map.put("isDel",lzKpi.getIsDel());
            for (SysUser sysUser : sysUserList) {
                if(lzKpi.getUserId().equals(sysUser.getId())){
                    map.put("sysuName",sysUser.getName());
                    map.put("account",sysUser.getAccount());
                    break;
                }
            }
            for (UserSchool userSchool : userSchoolList) {
                if(lzKpi.getUserId().equals(userSchool.getUserId())){
                    String schoolId = userSchool.getSchoolId();
                    for (School school : schoolList) {
                        if(schoolId.equals(school.getId()+"")){
                            map.put("schoolName",school.getSchoolName());
                            map.put("substName",school.getSubName());
                            break;
                        }
                    }
                }
            }
            list.add(map);
        }
        if(lzKpis.size() < pageSize) {
            dataList = list;
        }else {
            Integer endpageSize = (pageNo-1) == lzKpis.size()/pageSize?(pageNo-1)*pageSize+lzKpis.size()%pageSize:pageNo*pageSize;
            dataList = list.subList((pageNo-1)*pageSize, endpageSize);
        }

        page.setRecords(dataList);
        page.setTotal(lzKpis.size());
        return ResponseData.success(page, "查询成功！");
    }

    /**
     *
     * @param userName
     * @param substName
     * @param schoolName
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "导出楼长KPI信息", value = "excelOut", method = RequestMethod.POST)
    public void excelOut(
            @RequestParam(name = "userName", required = false) String userName,@RequestParam(name = "substName", required = false) String substName,
            @RequestParam(name = "schoolName", required = false) String schoolName,@RequestParam(name = "month", required = false) String month,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize
    )  throws IOException {

        List<String> userIds01 = new ArrayList<>();
        Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
        hhrUserWrapper.eq("position","楼长");
        List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
        for (HhrUser hhrUser : hhrUserList) {
            userIds01.add(hhrUser.getId());
        }
        List<String> userIds1 = new ArrayList<>();
        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        sysWrapper.in("id",userIds01);
        sysWrapper.like(StringUtils.isNotBlank(userName), "name", userName, SqlLike.DEFAULT);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        for (SysUser sysUser : sysUserList) {
            userIds1.add(sysUser.getId());
        }
        if(sysUserList.size()==0){
            log.error("查询数据为空！");
        }
        List<Integer> schoolIds = new ArrayList<>();
        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.eq(StringUtils.isNotBlank(substName), "substName", substName);
        schoolWrapper.eq(StringUtils.isNotBlank(schoolName), "schoolName", schoolName);
        List<School> schoolList = schoolMapper.selectList(schoolWrapper);
        for (School school : schoolList) {
            schoolIds.add(school.getId());
        }
        if(schoolList.size()==0){
            log.error("查询数据为空！");
        }
        List<String> userIds2 = new ArrayList<>();
        Wrapper<UserSchool> usWrapper = new EntityWrapper<>();
        usWrapper.in("school_id",schoolIds);
        List<UserSchool> userSchoolList = userSchoolMapper.selectList(usWrapper);
        List<UserSchool> userSchoolsTemp = new ArrayList<>();
        for (UserSchool userSchool : userSchoolList) {
            userIds2.add(userSchool.getUserId());
        }
        List<String> userIds = new ArrayList<>();
        for (String s : userIds1) {
            for (String s1 : userIds2) {
                if(s.equals(s1)){
                    userIds.add(s1);
                    break;
                }
            }
        }
        List<Map<String,Object>> list = new ArrayList<>();
        Wrapper<LzKpi> wrapper = new EntityWrapper();
        if(month.length()>7){
            month = month.substring(0,7);
        }
        wrapper.eq(StringUtils.isNotBlank(month),"month",month);
        wrapper.in("user_id",userIds);
        List<LzKpi> lzKpis = lzKpiMapper.selectList(wrapper);
        if(lzKpis.size()==0){
            log.error("查询数据为空！");
        }
        for (LzKpi lzKpi : lzKpis) {
            Map<String,Object> map = new HashMap<>();
            map.put("reportDaily",lzKpi.getReportDaily());
            map.put("collectiveSales",lzKpi.getCollectiveSales());
            map.put("weeklyMeeting",lzKpi.getWeeklyMeeting());
            map.put("organTraining",lzKpi.getOrganTraining());
            map.put("designPlan",lzKpi.getDesignPlan());
            map.put("kpi",lzKpi.getKpi());
            map.put("userId",lzKpi.getUserId());
            map.put("month",lzKpi.getMonth());
            map.put("isDel",lzKpi.getIsDel());
            for (SysUser sysUser : sysUserList) {
                if(lzKpi.getUserId().equals(sysUser.getId())){
                    map.put("sysuName",sysUser.getName());
                    map.put("account",sysUser.getAccount());
                    break;
                }
            }
            for (UserSchool userSchool : userSchoolList) {
                if(lzKpi.getUserId().equals(userSchool.getUserId())){
                    String schoolId = userSchool.getSchoolId();
                    for (School school : schoolList) {
                        if(schoolId.equals(school.getId()+"")){
                            map.put("schoolName",school.getSchoolName());
                            map.put("substName",school.getSubName());
                            break;
                        }
                    }
                }
            }
            list.add(map);
        }
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.kpiExcel("楼长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_reportDaily);
        columns.add(SL_collectiveSales);
        columns.add(SL_weeklyMeeting);
        columns.add(SL_organTraining);
        columns.add(SL_designPlan);
        columns.add(SL_kpi);
        columns.add(SL_month);
        columns.add(SL_sysuName);
        columns.add(SL_account);
        columns.add(SL_substName);
        columns.add(SL_schoolName);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("楼长KPI信息");
            sheet.setColumnWidth(0, 3000);
            sheet.setColumnWidth(1, 3000);
            sheet.setColumnWidth(2, 3000);
            sheet.setColumnWidth(3, 3000);
            sheet.setColumnWidth(4, 3000);
            sheet.setColumnWidth(5, 3000);
            sheet.setColumnWidth(6, 5000);
            sheet.setColumnWidth(7, 5000);
            sheet.setColumnWidth(8, 6000);
            sheet.setColumnWidth(9, 4000);
            sheet.setColumnWidth(10, 4000);
            //下拉选项
            /*List<String> fengju = new ArrayList<>();
            fengju.add("受理不成功");
            fengju.add("受理成功");
            sheet = this.getXSSFSheet(sheet, fengju, 1, 1);*/
            //添加表头
            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_reportDaily)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(SL_collectiveSales)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(SL_weeklyMeeting)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(SL_organTraining)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("e").toString().equals(SL_designPlan)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("f").toString().equals(SL_kpi)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("g").toString().equals(SL_month)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("h").toString().equals(SL_sysuName)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("i").toString().equals(SL_account)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("j").toString().equals(SL_substName)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("k").toString().equals(SL_schoolName)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (listMap.get(0).size() != 11) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }

        List<String> accountList = new LinkedList<>();
        List<Map<String,Object>> sysUserList = 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) + "行的姓名不能为空");
                }
                if (StringUtils.isBlank(temp.get("h").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的姓名不能为空");
                }
                if (!temp.containsKey("i")) {
                    return ResponseData.error("第" + (i + 1) + "行的账号不能为空");
                }
                if (StringUtils.isBlank(temp.get("i").toString())) {
                    return ResponseData.error("第" + (i + 1) + "行的账号不能为空");
                }
                if (temp.containsKey("i")) {
                    accountList.add(temp.get("i").toString());
                }
            }
            Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
            sysWrapper.setSqlSelect("id,account");
            sysWrapper.in("account",accountList);
            sysUserList = sysUserMapper.selectMaps(sysWrapper);
            for (Map<String, Object> map : listMap) {
                String account = map.get("i").toString();
                for (Map<String, Object> tmap : sysUserList) {
                    if(account.equals(tmap.get("account").toString())){
                        map.put("h",tmap.get("id").toString());
                        break;
                    }
                }

            }
            //检查excel表中是否有重复人员编号
            int size = listMap.size();
            Set<String> accountSet = new HashSet<>(size);
            for (int i = 0; i < size; i++) {
                Map<String, Object> temp = listMap.get(i);
                accountSet.add((String) temp.get("i"));
            }
            if (accountSet.size() != size) {
                return ResponseData.error("文件中有重复的用户账号，请确认用户账号不能重复!");
            }
        } catch (Exception e) {
            log.error("楼长KPI信息导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化时间
        Calendar c = Calendar.getInstance();
        //过去6个月
        c.add(Calendar.MONTH, -6);
        Date m = c.getTime();
        Wrapper<LzKpi> lzKpiWrapper = new EntityWrapper<>();
        lzKpiWrapper.ge("month",sdf.format(m));
        lzKpiWrapper.le("month",sdf.format(new Date()));
        List<LzKpi> lzKpiList = lzKpiMapper.selectList(lzKpiWrapper);
        int number = 0;
        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            LzKpi lzKpi = new LzKpi();
            Integer reportDaily = Integer.valueOf(map.get("a").toString());
            lzKpi.setReportDaily(reportDaily);
            Integer collectiveSales = Integer.valueOf(map.get("b").toString());
            lzKpi.setCollectiveSales(collectiveSales);
            Integer weeklyMeeting = Integer.valueOf(map.get("c").toString());
            lzKpi.setWeeklyMeeting(weeklyMeeting);
            Integer organTraining = Integer.valueOf(map.get("d").toString());
            lzKpi.setOrganTraining(organTraining);
            Integer designPlan = Integer.valueOf(map.get("e").toString());
            lzKpi.setDesignPlan(designPlan);
            Integer kpi = Integer.valueOf(map.get("f").toString());
            lzKpi.setKpi(kpi);
            String month = map.get("g").toString();
            lzKpi.setMonth(month);
            String userId = map.get("h").toString();
            lzKpi.setUserId(userId);
            lzKpi.setIsDel("0");
            String userId0 = null;
            if (StringUtils.isNotBlank(map.get("h").toString())) {
                userId0 = map.get("h").toString();
            }
            boolean isUpdate = false;
            for (LzKpi lzKpi1 : lzKpiList) {
                if(lzKpi1.getUserId().equals(userId)){
                    lzKpi.setId(lzKpi1.getId());
                    isUpdate = true;
                    break;
                }
            }
            try {
                if(isUpdate){
                    Wrapper<LzKpi> wrapper = new EntityWrapper<>();
                    wrapper.eq("id",lzKpi.getId());
                    lzKpiMapper.update(lzKpi,wrapper);
                    number++;
                }else{
                    Integer integer = lzKpiMapper.insert(lzKpi);
                    if (integer == 1) {
                        number++;
                    } else {
                        error.append("第" + (i + 1) + "行的更新失败,");
                    }
                }
            }catch (Exception e){
                log.info(e.getMessage());
                error.append("第" + (i + 1) + "行的更新失败,");
            }

        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }
}
