package com.winsun.controller;

import com.alibaba.excel.util.DateUtils;
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.Package;
import com.winsun.bean.Product;
import com.winsun.bean.School;
import com.winsun.bean.SchoolPackage;
import com.winsun.constant.FilePath;
import com.winsun.mapper.PackageMapper;
import com.winsun.mapper.ProductMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SchoolPackageMapper;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.ImportExcel;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import io.lettuce.core.dynamic.annotation.Param;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
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.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Author: chancy
 * @Date: 2020/2/12 17:25 学校管理
 */
@Slf4j
@RestController
@RequestMapping("/school/schoolManagement")
public class SchoolManagementController extends BaseController {

    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;

    private static String SL_SUB_NAME = "县分（必填）";
    private static String SL_SCHOOL = "学校名称（必填）";
    private static String SL_productUniversity = "单宽学校名称";
    private static String SL_NetId = "网点id(合伙人id)";
    private static String SL_LZGH = "揽装工号（宽带）";
    private static String SL_LZ_USER = "揽装人（宽带）";
    private static String SL_NET_CODE = "网点编码";
    private static String SL_NET_NAME = "网点名称";
    private static String SL_APP_ID = "随身厅终端编码";
    private static String SL_APP_KEY = "随身厅终端密匙";

	private static SchoolMapper schoolMapper;

    private static SchoolPackageMapper schoolPackageMapper;

    private static PackageMapper packageMapper;

    private static ProductMapper productMapper;

    //默认路径
    private static String   DEFAULTPATH="images/schoolPartner/";


    private static String FILENAME=".jpg";

    @Autowired
    public SchoolManagementController(SchoolMapper schoolMapper, SchoolPackageMapper schoolPackageMapper,PackageMapper packageMapper,ProductMapper productMapper) {
        SchoolManagementController.schoolMapper = schoolMapper;
        SchoolManagementController.schoolPackageMapper = schoolPackageMapper;
        SchoolManagementController.packageMapper = packageMapper;
        SchoolManagementController.productMapper = productMapper;
    }

    @Permission(menuname = "添加学校信息", value = "insert", method = RequestMethod.POST)
    public ResponseData<String> insertSchool( School school, @RequestParam("chosePages") String chosePages,
                                              @RequestParam(value = "startDateStr", required = false) String startDateStr,
                                              @RequestParam(value = "endDateStr", required = false) String endDateStr) {
        try {
            if (StringUtils.isNotBlank(startDateStr)) {
                school.setStartDate(DateUtils.parseDate(startDateStr));
            }
            if (StringUtils.isNotBlank(endDateStr)) {
                school.setEndDate(DateUtils.parseDate(endDateStr));
            }
        }catch(Exception e){
            return ResponseData.error("日期格式转换错误");
        }
        Integer insert = schoolMapper.insert(school);

        //插入中间表
        if (StringUtils.isNotBlank(chosePages)){
            String[] split = chosePages.split(",");
            if (split.length<=0) {
                return ResponseData.success("添加成功！");
            }
            for (String s : split) {
                SchoolPackage schoolPackage = new SchoolPackage();
                schoolPackage.setSchoolId( String.valueOf(school.getId()));
                schoolPackage.setPackageId(s);
                schoolPackageMapper.insert(schoolPackage);
            }
        }
        if (insert==1){
            EntityWrapper<School> schoolwrapper = new EntityWrapper<>();
            schoolwrapper.eq("id",school.getId());
            String  backgroundpath= "/"+DEFAULTPATH+ school.getId()+FILENAME;
            schoolMapper.updateForSet("service_qrcode ='"+backgroundpath+"'",schoolwrapper);
            log.info("学校信息新增完毕,id: {}",school.getId());
            return ResponseData.success("添加成功！");
        }
        return ResponseData.error("添加失败！");

    }

    @Permission(menuname = "删除學校信息", value = "hidestatus", method = RequestMethod.POST)
    public ResponseData<String> deleteSchool(@RequestParam("id") String id,@RequestParam("status") int status) {

        Integer integer = schoolMapper.updateForSet("status=" + status, new EntityWrapper<School>().eq("id", id));
        if (integer==1){
            return ResponseData.success("修改成功！");
        }
        return  ResponseData.error("修改失败");

    }

    /**
     * 修改学校信息
     * @param school
     * @param chosePages
     * @return
     */
    @Permission(menuname = "修改学校信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updateSchool(School school, @RequestParam("chosePages") String chosePages,
                                             @RequestParam(value = "startDateStr", required = false) String startDateStr,
                                             @RequestParam(value = "endDateStr", required = false) String endDateStr) {
        try{
            if (StringUtils.isNotBlank(startDateStr)) {
                school.setStartDate(DateUtils.parseDate(startDateStr));
            }
            if (StringUtils.isNotBlank(endDateStr)) {
                school.setEndDate(DateUtils.parseDate(endDateStr));
            }

            Wrapper<School> wrapper = new EntityWrapper<>();
            wrapper.eq("id",school.getId());
            Map<String, Object> dataMapping = new HashMap<>();
            schoolMapper.update(school, wrapper);
//        schoolMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
            //插入学校与套餐中间表数据
            if (StringUtils.isNotBlank(chosePages)){
                String[] split = chosePages.split(",");
                if (split.length<=0) {
                    return ResponseData.success("修改完毕！");
                }
                EntityWrapper<SchoolPackage> schoolPackagewrapper = new EntityWrapper<>();
                schoolPackagewrapper.eq("school_id",school.getId());
                schoolPackageMapper.delete(schoolPackagewrapper);
                for (String s : split) {
                    SchoolPackage schoolPackage = new SchoolPackage();
                    schoolPackage.setSchoolId(school.getId() + "");
                    schoolPackage.setPackageId(s);
                    schoolPackageMapper.insert(schoolPackage);
                }
            }
        }catch(Exception e) {
            log.error("修改学校失败！" + e.getMessage());
        }

        return ResponseData.success("修改完毕！");
    }

    /**
     *
     * @param subName
     * @param status
     * @param schoolName
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询学校信息", value = "findByList", method = RequestMethod.POST)
    public ResponseData<Page<Map<String,Object>>> listSchool(@RequestParam("subName") String subName, @RequestParam("status") String status,
                                                 @RequestParam("schoolName") String schoolName, @RequestParam(name = "pageNo", required = false) int pageIndex,
                                                 @RequestParam(name = "pageSize", required = false) int pageSize,
                                                 @RequestParam("networkName") String networkName) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "系统管理员"))) {
            return ResponseData.error("无数据权限");
        }
        Wrapper<School> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(networkName), "network_name", networkName, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(schoolName), "school_name", schoolName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(subName), "sub_name", subName);
        wrapper.eq(StringUtils.isNotBlank(status), "status", status);
        Page<Map<String,Object>> page = new Page<>(pageIndex, pageSize);
        List<Map<String, Object>> maps = schoolMapper.selectMapsPage(page, wrapper);

        //查询县分列表
        Wrapper<School> wrapperSubName = new EntityWrapper();
        wrapperSubName.setSqlSelect("sub_name as subNameList").groupBy("sub_name");
        List<Map<String, Object>> selectMaps = schoolMapper.selectMaps(wrapperSubName);
        EntityWrapper<Package> packagewrapper = new EntityWrapper<>();
        packagewrapper.setSqlSelect("id,package_name as packageName");
        packagewrapper.orderBy(true, "create_time", false);
        List<Map<String, Object>> packageselectMaps = packageMapper.selectMaps(packagewrapper);
        //查询单宽学校名称
        Wrapper<Product> productwrapper = new EntityWrapper();
        productwrapper.setSqlSelect("product_id as productId,product_university as ProductUniversity");
        productwrapper.eq("product_state", "0");
        List<Map<String, Object>> products = productMapper.selectMaps(productwrapper);
        //存放县分下拉列表和单宽学校名称下拉列表
        if (!CollectionUtils.isEmpty(maps)){
            maps.get(0).put("subNameList",selectMaps);
            maps.get(0).put("packageName",packageselectMaps);
            maps.get(0).put("products",products);
        }
        page.setRecords(maps);
        return ResponseData.success(page, "查询完毕！");
    }

    @Permission(menuname = "编辑套餐选择回显数据", value = "choosepages", method = RequestMethod.POST)
    public ResponseData<Map<String,Object>> editdisplay(@RequestParam("id") String id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        EntityWrapper<SchoolPackage> schoolPackagewrapper = new EntityWrapper<>();
        schoolPackagewrapper.eq("school_id",id);
        List<SchoolPackage> schoolPackages = schoolPackageMapper.selectList(schoolPackagewrapper);
        ArrayList<String> arrayList = new ArrayList<>();
        schoolPackages.forEach(val->{
            arrayList.add(val.getPackageId());
        });

        hashMap.put("choosepages",arrayList);
        return ResponseData.success(hashMap, "查询完毕！");
    }

    @Permission(menuname = "上传二维码", value = "qrcodeUpload", method = RequestMethod.POST)
    public ResponseData<String>xiaotuUpload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "id",required = false) String id) {
        String  backgroundpath = FilePath.BACKGROUNDIMG.getValue() + "/" + DEFAULTPATH;
        File dir = new File(backgroundpath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if(!StringUtils.endsWithAny(file.getOriginalFilename(), "jpg", "jpeg", "png", "gif")) {
            return ResponseData.error("上传失败，仅支持jpg、jpeg、png");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("图片过大，无法上传");
        }
        School school1 = schoolMapper.selectById(id);
        File savePath = new File(backgroundpath, school1.getId() + FILENAME);
        OutputStream os = null;
        try {
            os = new FileOutputStream(savePath);
            os.write(file.getBytes());
            os.flush();

            Wrapper<School> wrapper = new EntityWrapper<>();
            wrapper.eq("id",id);
            School school = schoolMapper.selectById(id);
            Map<String, Object> map = new HashMap<>();
            map.put("service_qrcode",backgroundpath+school.getId()+FILENAME);
            Integer integer = schoolMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(map), wrapper);
            if (integer!=1){
                return ResponseData.error("上传失败！");
            }
            return ResponseData.success("上传成功" );
        } catch (Exception e) {
            log.error("上传文件失败：" + e.getMessage(), e);
            return ResponseData.error("上传失败" + e.getMessage());
        } finally {
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e) {}
            }
        }
    }


    @RequestMapping(name = "获取县分下拉列表", value = "substList", method = RequestMethod.POST)
	public ResponseData<List<Map<String, Object>>> substList() {
//		ShiroUser user = getShiroUser();
//		if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
//			return ResponseData.error("无数据权限");
//		}

		// 查询县分列表
		Wrapper<School> wrapperSubName = new EntityWrapper<School>();
		wrapperSubName.setSqlSelect("sub_name")
					  .ne("sub_name", "null")
					  .groupBy("sub_name");
		List<Map<String, Object>> substNameList = schoolMapper.selectMaps(wrapperSubName);

		return ResponseData.success(substNameList, "查询完毕！");
	}

    @RequestMapping(name = "获取学校下拉列表", value = "schoolList", method = RequestMethod.POST)
	public ResponseData<List<Map<String, Object>>> schoolList(@RequestParam("substName") String substName) {
//		ShiroUser user = getShiroUser();
//		if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
//			return ResponseData.error("无数据权限");
//		}

		// 查询县分列表
		Wrapper<School> wrapper = new EntityWrapper<School>();
		wrapper.setSqlSelect("id,school_name")
					  .eq("sub_name", substName)
					  .groupBy("school_name");
		List<Map<String, Object>> schoolList = schoolMapper.selectMaps(wrapper);

		return ResponseData.success(schoolList, "查询完毕！");
	}
    /**
     * 受理订单
     *
     * @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文件，其他格式不支持！");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        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("受理单导入异常", 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_SUB_NAME)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("b").toString().equals(SL_SCHOOL)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("c").toString().equals(SL_productUniversity)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("d").toString().equals(SL_NetId)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("e").toString().equals(SL_LZGH)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("f").toString().equals(SL_LZ_USER)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("g").toString().equals(SL_NET_CODE)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("h").toString().equals(SL_NET_NAME)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("i").toString().equals(SL_APP_ID)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (!listMap.get(0).get("j").toString().equals(SL_APP_KEY)) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        if (listMap.get(0).size() != 8) {
            return ResponseData.error("模板不对，请选择正确的模板！");
        }
        //校验数据
        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")) {
                    listMap.get(i).put("c","");
                }
                if (!temp.containsKey("d")) {
                    listMap.get(i).put("d","");
                }
                if (!temp.containsKey("e")) {
                    listMap.get(i).put("e","");
                }
                if (!temp.containsKey("f")) {
                    listMap.get(i).put("f","");
                }
                if (!temp.containsKey("g")) {
                    listMap.get(i).put("g","");
                }
                if (!temp.containsKey("h")) {
                    listMap.get(i).put("h","");
                }
                if (!temp.containsKey("i")) {
                    listMap.get(i).put("i","");
                }
                if (!temp.containsKey("j")) {
                    listMap.get(i).put("j","");
                }
            }
            //检查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("a")+temp.get("b"));
            }
            if (accountSet.size() != size) {
                return ResponseData.error("文件中有重复的学校，请确认学校不能重复!");
            }
        } catch (Exception e) {
            log.error("学校导入异常", e.getMessage());
            return ResponseData.error("导入异常！");
        }
        int number = 0;

        Integer integer = 0;
        Map<String,Object> schoolMap = new HashMap<>();
        Map<String,Object> productmap = new HashMap<>();

        for (int i = 1; i < listMap.size(); i++) {
            Map<String, Object> map = listMap.get(i);
            integer = 0;

            schoolMap = schoolMapper.querySchoolMap(map.get("a").toString(),map.get("b").toString());
            productmap = productMapper.queryProductMaps(map.get("c").toString()).get(0);
            map.put("c",productmap.get("productId").toString());
            try{
                if(schoolMap != null && schoolMap.size() != 0){
                    integer = schoolMapper.updateSchoolMap(map);
                }else {
                    integer = schoolMapper.insertSchoolMap(map);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

            if (integer > 0) {
                number++;
            } else {
                error.append("第" + (i + 1) + "行的更新失败,");
            }
        }
        error.append("成功更新" + number + "条数据！");
        return ResponseData.success(error.toString(), "导入完成");
    }
    /**
     *
     * @return
     */
    @Permission(menuname = "导出学校列表信息", value = "excelOut", method = RequestMethod.POST)
    public void excelOut(@Param("networkName") String networkName,
                         @Param("status") String status,
                         @Param("subName") String subName,
                         @Param("schoolName") String schoolName){

        Wrapper<School> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(networkName), "network_name", networkName, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(schoolName), "school_name", schoolName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(subName), "sub_name", subName);
        wrapper.eq(StringUtils.isNotBlank(status), "status", status);
        List<Map<String, Object>> maps = schoolMapper.selectMaps(wrapper);
        List<Map<String, Object>> schoolmaps = new ArrayList<>();
        Map<String,Object> productMap = new HashMap<>();
        for (Map<String,Object> map:maps){
            map.put("productUniversity","");
            if(null != map.get("bandproductId") && StringUtils.isNotBlank(map.get("bandproductId").toString())){
                productMap = productMapper.queryProductByIdMap(map.get("bandproductId").toString());
                if(productMap != null && productMap.size() != 0){
                    map.put("productUniversity",productMap.get("productUniversity"));
                }
            }
            schoolmaps.add(map);
        }
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.schoolExcel("校园列表"), schoolmaps);
        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);
        }
    }

    @Permission(menuname = "下载学校上传模板", value = "excelMBOut", method = RequestMethod.POST)
    public void excelMBOut(){
        Map<String,Object> map = new HashMap<>();
        map.put("subName", "");
        map.put("schoolName", "");
        map.put("netId", "");
        map.put("lzgh", "");
        map.put("lzUser", "");
        map.put("networkCode", "");
        map.put("networkName", "");
        map.put("appId", "");
        map.put("appKey", "");
        List<Map<String, Object>> maps =  new ArrayList<Map<String,Object>>();
        maps.add(map);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.schoolExcel("校园模板"), maps);
        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);
        }
    }
}
