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.bean.ExportExcel;
import com.winsun.bean.YsmUser;
import com.winsun.mapper.ExportExcelMapper;
import com.winsun.mapper.YsmUserMapper;
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.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 智能平台账号实名管理
 * @Author: chancy
 * @Date:
 */
@Slf4j
@RestController
@RequestMapping("/exportExcel")
public class ExportExcelController extends BaseController {

    private static ExportExcelMapper exportExcelMapper;

    @Autowired
    public ExportExcelController(ExportExcelMapper exportExcelMapper) {
        ExportExcelController.exportExcelMapper = exportExcelMapper;
    }



    @Permission(menuname = "订单excel文件下载", value = "uploadExcel", method = RequestMethod.POST)
    public void uploadExcel(String exportId) {
        ServletOutputStream os = null;
        try {
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            ExportExcel exportExcel = exportExcelMapper.selectById(exportId);
            //输入流：本地文件路径
            DataInputStream in = new DataInputStream(new FileInputStream(new File(exportExcel.getExportUrl())));
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                os.write(bufferOut, 0, bytes);
            }
            in.close();
            os.flush();
        } catch (Exception e) {
            log.error("下载excel文件异常", e.getMessage());
        }
    }


    @Permission(menuname = "查询下载列表", value = "listExportExcel", method = RequestMethod.POST)
    public ResponseData<Page<ExportExcel>> listExportExcel(@RequestParam(value = "fileName",required = false) String fileName,@RequestParam(name = "pageNo") int pageIndex, @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();
        Wrapper<ExportExcel> wrapper = new EntityWrapper();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            wrapper.like("create_user",user.getId().toString() , SqlLike.DEFAULT);
        }
        wrapper.like(StringUtils.isNotBlank(fileName), "file_name", fileName, SqlLike.DEFAULT);
        Page<ExportExcel> page = new Page<>(pageIndex, pageSize);
        List<ExportExcel> exportExcels = exportExcelMapper.selectPage(page, wrapper);
        page.setRecords(exportExcels);
        return ResponseData.success(page, "查询成功！");
    }

    @Permission(menuname = "删除文件", value = "deleteExcel", method = RequestMethod.POST)
    public ResponseData<String> deleteExcel(String exportId) {
        ExportExcel exportExcel = exportExcelMapper.selectById(exportId);
        File file = new File(exportExcel.getExportUrl());
        Boolean flag = false;
        //判断文件是否存在
        if (file.exists() == true){
            flag = file.delete();
            if (flag){
                exportExcelMapper.deleteById(Integer.parseInt(exportId));
                log.info("成功删除"+file.getName());
                return ResponseData.success("成功删除"+file.getName()+"！");
            }else {
                log.error("删除失败"+file.getName());
                return ResponseData.error("删除失败！");
            }
        }else {
            log.info(file.getName()+"不存在，终止操作");
        }
        return ResponseData.error("删除失败！");
    }
}
