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.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.FileUtil;
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 com.winsun.auth.core.common.model.ResponseData;
import org.springframework.web.multipart.MultipartFile;

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(@RequestParam("subName") String subName,@RequestParam("schoolName") String schoolName,@RequestParam("netId") String netId,
                                             @RequestParam("lzgh") String lzgh,@RequestParam("bandproductId") String bandproductId,@RequestParam("netPhone") String netPhone,@RequestParam("isShowband") String isShowband,
                                             @RequestParam("isShowrh") String isShowrh,@RequestParam("isRecv") String isRecv,@RequestParam("chosePages") String chosePages) {

        School school = new School();
        school.setBandproductId(bandproductId);
        if (StringUtils.isNotBlank(isRecv)){
            school.setIsRecv(Integer.valueOf(isRecv));
        }
        school.setNetId(netId);
        school.setLzgh(lzgh);
        school.setSchoolName(schoolName);
        school.setSubName(subName);
        school.setIsShowband(isShowband);
        school.setIsShowrh(isShowrh);
        if (StringUtils.isNotBlank(netPhone)){
            school.setNetPhone(Integer.valueOf(netPhone));
        }
        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 id
     * @param subName    县分
     * @param schoolName 学校
     * @param netId 网点id
     * @param lzgh 揽装工号
     * @param bandproductId  单宽id
     * @param netPhone  购机
     * @param isShowband     显示宽带
     * @param isShowrh   融合
     * @param isRecv  收到电信卡
     * @param chosePages 套餐id
     * @return
     */
    @Permission(menuname = "修改学校信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updateSchool(@RequestParam("id") String id,@RequestParam("subName") String subName,@RequestParam("schoolName") String schoolName,@RequestParam("netId") String netId,
                                                @RequestParam("lzgh") String lzgh,@RequestParam("bandproductId") String bandproductId,@RequestParam("netPhone") String netPhone,@RequestParam("isShowband") String isShowband,
                                                 @RequestParam("isShowrh") String isShowrh,@RequestParam("isRecv") String isRecv,@RequestParam("chosePages") String chosePages) {

        Wrapper<School> wrapper = new EntityWrapper<>();
        wrapper.eq("id",id);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("sub_name", subName);
        dataMapping.put("school_name", schoolName);
        dataMapping.put("lzgh", lzgh);
        dataMapping.put("net_id", netId);
        dataMapping.put("is_recv", isRecv);
        dataMapping.put("net_phone", netPhone);
        dataMapping.put("bandproduct_id", bandproductId);
        dataMapping.put("is_showband", isShowband);
        dataMapping.put("is_showrh", isShowrh);
        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",id);
            schoolPackageMapper.delete(schoolPackagewrapper);
            for (String s : split) {
                SchoolPackage schoolPackage = new SchoolPackage();
                schoolPackage.setSchoolId(id);
                schoolPackage.setPackageId(s);
                schoolPackageMapper.insert(schoolPackage);
            }
        }
        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) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        Wrapper<School> wrapper = new EntityWrapper();
        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");
        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;
        boolean makefile = FileUtil.makefile(backgroundpath, file,id+FILENAME);
        Wrapper<School> wrapper = new EntityWrapper<>();
        wrapper.eq("id",id);
        Map<String, Object> map = new HashMap<>();
        map.put("service_qrcode",backgroundpath+id+FILENAME);
        Integer integer = schoolMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(map), wrapper);
        if (integer!=1){
            return ResponseData.error("上传失败！");
        }
        return ResponseData.success("上传成功" );
    }
}
