package com.winsun.controller;

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.SchoolPackage;
import com.winsun.constant.FilePath;
import com.winsun.interfaces.PermissionVerification;
import com.winsun.mapper.PackageMapper;
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.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.*;
import java.util.regex.Pattern;

/**
 *
 * @Date: 2020/2/12 17:25
 */
@Slf4j
@RestController
@RequestMapping("/packageManagement/package") //
public class PackageController extends BaseController {

    private static PackageMapper packageMapper;

    private static SchoolPackageMapper schoolPackageMapper;

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


    private static final String FILENAME = "adv_img.jpg";

    private static final String XIAOTUFILENAME = "logo.png";

    private static final Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]");


    @Autowired
    public PackageController(PackageMapper packageMapper, SchoolPackageMapper schoolPackageMapper) {
        PackageController.packageMapper = packageMapper;
        PackageController.schoolPackageMapper = schoolPackageMapper;
    }

    /**
     * @param id
     * @param packageName
     * @param name
     * @param isXbCard
     * @param monthFee
     * @param flow
     * @param voice
     * @param xbId
     * @param warmTip
     * @param explains
     * @return
     */
    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "添加套餐信息", value = "insert", method = RequestMethod.POST)
    public ResponseData<String> insertPackage(@RequestParam("id") String id
                                            , @RequestParam("packageName") String packageName
                                            , @RequestParam("name") String name
                                            , @RequestParam("isXbCard") int isXbCard
                                            , @RequestParam("isDelivery") int isDelivery
                                            , @RequestParam("monthFee") String monthFee
                                            , @RequestParam("flow") String flow
                                            , @RequestParam("voice") String voice
                                            , @RequestParam("xbId") String xbId
                                            , @RequestParam("warmTip") String warmTip
                                            , @RequestParam("explains") String explains) {
        Package aPackage = new Package();
        aPackage.setPackageName(packageName);
        aPackage.setName(name);
        aPackage.setIsXbCard(isXbCard);
        if("0".equals(isXbCard)){
            aPackage.setIsDelivery(isDelivery);
        }
        aPackage.setMonthFee(monthFee);
        aPackage.setFlow(flow);
        aPackage.setVoice(voice);
        aPackage.setXbId(xbId);
        aPackage.setWarmTip(warmTip);
        aPackage.setExplains(explains);
        Integer insert = packageMapper.insert(aPackage);
        if (insert == 1) {
            EntityWrapper<Package> packagewrapper = new EntityWrapper<>();
            packagewrapper.eq("id", aPackage.getId());
            String backgroundpath = DEFAULTPATH + aPackage.getId() + "/" + FILENAME;
            String logopath = DEFAULTPATH + aPackage.getId() + "/" + XIAOTUFILENAME;
            packageMapper.updateForSet("adv_img ='" + backgroundpath + "' ,  logo= '" + logopath + "'", packagewrapper);
            log.info("套餐信息新增完毕,id: {}", aPackage.getId());
            return ResponseData.success("新增完毕！");
        }
        log.info("套餐信息新增失败,id: {}", aPackage.getId());
        return ResponseData.success("新增失败！");
    }

    /**
     * @param id
     * @return
     */
    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "删除套餐信息", value = "delete", method = RequestMethod.POST)
    public ResponseData<String> deletePackage(@RequestParam("id") int id) {
        Integer integer = packageMapper.deleteById(id);
        //删除中间表信息
        EntityWrapper<SchoolPackage> schoolPackagewrapper = new EntityWrapper<>();
        schoolPackagewrapper.eq("package_id", id);
        schoolPackageMapper.delete(schoolPackagewrapper);
        if (integer == 1) {
            log.info("套餐信息删除完毕,删除id: {}", id);
            return ResponseData.success("删除完毕！");
        }
        log.info("套餐信息删除失败,删除id: {}", id);
        return ResponseData.success("删除失败！");
    }

    /**
     * @param id
     * @param packageName
     * @param name
     * @param isXbCard
     * @param monthFee
     * @param flow
     * @param voice
     * @param xbId
     * @param warmTip
     * @param explains
     * @return
     */
    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "修改套餐信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updatePackage(@RequestParam("id") String id
                                            , @RequestParam("packageName") String packageName
                                            , @RequestParam("name") String name
                                            , @RequestParam("isXbCard") String isXbCard
                                            , @RequestParam("isDelivery") String isDelivery
                                            , @RequestParam("monthFee") String monthFee
                                            , @RequestParam("flow") String flow
                                            , @RequestParam("voice") String voice
                                            , @RequestParam("xbId") String xbId
                                            , @RequestParam("warmTip") String warmTip
                                            , @RequestParam("explains") String explains) {

        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("package_name", packageName);
        dataMapping.put("name", name);
        dataMapping.put("is_xb_card", isXbCard);
        if("0".equals(isXbCard)){
            if(isDelivery != null && StringUtils.isNotBlank(isDelivery)){
                dataMapping.put("is_delivery", isDelivery);
            }
        }
        dataMapping.put("month_fee", monthFee);
        dataMapping.put("flow", flow);
        dataMapping.put("voice", voice);
        dataMapping.put("xb_id", xbId);
        dataMapping.put("warm_tip", warmTip);
        dataMapping.put("explains", explains);
        dataMapping.put("create_time", new Date());
        Integer integer = packageMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 1) {
            log.info("成功修改完毕套餐信息");
            return ResponseData.success("修改完毕！");
        } else {
            log.info("修改失败套餐信息");
            return ResponseData.error("修改失败！");
        }

    }

    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "查询套餐信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<Package>> listPackage(@RequestParam("name") String name,
                                                   @RequestParam("monthFee") String monthFee,
                                                   @RequestParam("flow") String flow,
                                                   @RequestParam("voice") String voice,
                                                   @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<Package> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(name), "package_name", name, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(monthFee), "month_fee", monthFee, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(flow), "flow", flow, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(voice), "voice", voice, SqlLike.DEFAULT);
        List<String> objects = new ArrayList<>();
        objects.add("id");
        wrapper.orderDesc(objects);
        Page<Package> page = new Page<>(pageIndex, pageSize);
        try{
            List<Package> aPackage = packageMapper.selectPage(page, wrapper);
            page.setRecords(aPackage);
            return ResponseData.success(page, "查询完毕！");
        }catch (Exception e){
            log.info("查询套餐信息失败："+e);
        }
        return ResponseData.error("查询套餐信息失败");
    }

    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "套餐全称列表", value = "packageAllList", method = RequestMethod.POST)
    public ResponseData<List<String>> packageAll() {
        ArrayList<String> arrayList = new ArrayList<>();
        final List<Map<String, Object>> maps = packageMapper.packageAll();
        for (Map<String, Object> map : maps) {
            if (map != null) {
                arrayList.add(map.get("cdmaDiscDesc").toString());
            }
        }
        return ResponseData.success(arrayList, "查询完毕！");
    }


    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "上传背景图", value = "backgroundUpload", method = RequestMethod.POST)
    public ResponseData<String> backgroundUpload(MultipartFile file, @RequestParam(value = "id", required = false) String id) {
        if(!StringUtils.endsWithAny(file.getOriginalFilename(), "jpg", "jpeg", "png", "gif")) {
            return ResponseData.error("上传失败，仅支持jpg、jpeg、png");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        StringBuilder basePath = new StringBuilder();
        basePath.append("enclosure").append(DEFAULTPATH).append(File.separator);
        if (StringUtils.isBlank(id)) {
            EntityWrapper<Package> packagewrapper = new EntityWrapper<>();
            packagewrapper.setSqlSelect("max(id) as id");
            List<Map<String, Object>> selectMaps = packageMapper.selectMaps(packagewrapper);
            basePath.append(Integer.parseInt(selectMaps.get(0).get("id").toString()) + 1);
        } else {
            Package aPackage = packageMapper.selectById(id);
            basePath.append(aPackage.getId());
        }
        File dir = new File(basePath.toString());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File savePath = new File(dir, FILENAME);
        OutputStream os = null;
        try {
            os = new FileOutputStream(savePath);
            os.write(file.getBytes());
            os.flush();
            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) {
                }
            }
        }
    }

    //xiaotudUpload
    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "上传小图", value = "xiaotuUpload", method = RequestMethod.POST)
    public ResponseData<String> xiaotuUpload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "id", required = false) String id) {
        if(!StringUtils.endsWithAny(file.getOriginalFilename(), "jpg", "jpeg", "png", "gif")) {
            return ResponseData.error("上传失败，仅支持jpg、jpeg、png");
        }
        if ( (double)file.getSize()/1048576 > 100) {
            return ResponseData.error("文件过大，无法上传");
        }
        String backgroundpath = FilePath.BACKGROUNDIMG.getValue() + "/" + DEFAULTPATH + "/";
        if (StringUtils.isBlank(id)) {
            EntityWrapper<Package> packagewrapper = new EntityWrapper<>();
            packagewrapper.setSqlSelect("max(id) as id");
            List<Map<String, Object>> selectMaps = packageMapper.selectMaps(packagewrapper);
            id = selectMaps.get(0).get("id").toString();
            Integer fileid = Integer.valueOf(id) + 1;
            backgroundpath = backgroundpath + fileid.toString();
        } else {
            Package aPackage = packageMapper.selectById(id);
            backgroundpath = backgroundpath + aPackage.getId();
        }
        File dir = new File(backgroundpath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File savePath = new File(dir, XIAOTUFILENAME);
        OutputStream os = null;
        try {
            os = new FileOutputStream(savePath);
            os.write(file.getBytes());
            os.flush();

            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) {
                }
            }
        }
    }

    /**
     * 批量下架
     * @param ids
     * @return
     */
    @PermissionVerification(value = {"/school-center/productManagement/package"})
    @Permission(menuname = "批量下架", value = "batchUpdate", method = RequestMethod.POST)
    public ResponseData<String> batchUpdate(@RequestParam("ids") String ids) {
        Integer integer = packageMapper.delSchoolPackageByPackageId(ids.split(","));
        return ResponseData.success("已批量下架：" + integer + "个学校产品");
    }
}
