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.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.MyBatisPlusUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

	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, "查询完毕！");
	}

}
