package com.nantian.cloud.jljc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.TTraining;
import com.nantian.cloud.jljc.service.GetTrainingOutService;
import com.nantian.cloud.jljc.service.TTrainingService;
import com.nantian.cloud.jljc.service.TTrainingVideoService;
import com.nantian.cloud.jljc.tools.UploadUtils;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * 培训活动
 *
 * @date 2020-09-03 13:23:34
 */
@Slf4j
@CrossOrigin
@AllArgsConstructor
@Api(value = "ttraining", tags = "培训活动")
@RestController
@RequestMapping("/ttraining")
public class TTrainingController {
    @Autowired
    private TTrainingService tTrainingService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private GetTrainingOutService getTrainingOutService;
    @Autowired
    private TTrainingVideoService tTrainingVideoService;

    /**
     * 列表
     */
    @SysLog("分页获取培训")
    @ApiOperation(value = "分页获取培训", notes = "分页获取培训")
    @GetMapping("/page")
    @ApiImplicitParam(name = "TTraining", value = "分页获取培训", required = true, paramType = "path")
    public R page(Page page, TTraining tTraining) {
        tTraining.setDelFlag("1");  //查询未删除项
        return R.ok(tTrainingService.page(page, Wrappers.query(tTraining).orderByDesc("update_time")));
    }


    @SysLog("分页获取培训(带权限)")
    @ApiOperation(value = "分页获取培训(带权限)", notes = "分页获取培训(带权限)")
    @GetMapping("/pageInfo")
    @ApiImplicitParam(name = "TTraining", value = "分页获取培训", required = true, paramType = "path")
    public R pageInfo(Page page, TTraining tTraining) {
        return R.ok(tTrainingService.pageInfo(page,tTraining));
    }

    @SysLog("获取培训(无登录认证)")
    @Inner(value = false)
    @PostMapping("/pageInfoOut")
    @ApiOperation(value = "获取培训(无登录认证)", notes = "获取培训(无登录认证)")
    public R pageInfoOut() {
        return R.ok(getTrainingOutService.pageInfo());
    }


    /**
     * 列表
     */
    @SysLog("获取培训最新的三条")
    @ApiOperation(value = "获取培训最新的三条", notes = "获取培训最新的三条")
    @GetMapping("/top3")
    public R top3(TTraining tTraining) {
        QueryWrapper<TTraining> q = Wrappers.query(tTraining);
        q.ge("del_flag", "1");
        q.orderByDesc("update_time");
        q.last("limit 3");
        List<TTraining> list = tTrainingService.list(q);
        for (int i = 0; i < list.size(); i++) {
            TTraining o = list.get(i);
            if (o != null) {
               /* byte[] pictureByte = o.getPlacard();
                if (pictureByte != null) {
                    list.get(i).setPlacardSting(Base64.getEncoder().encodeToString(pictureByte));
                }*/
            }
        }
        return R.ok(list);
    }

    /**
     * 信息
     */
    @SysLog("根据id获取培训")
    @ApiOperation(value = "获取培训", notes = "获取培训")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        TTraining o = tTrainingService.getById(id);
        return R.ok(o);
    }
    /**
     * 信息
     */
    @SysLog("获取培训（系统外）")
    @ApiOperation(value = "获取培训", notes = "获取培训")
    @GetMapping("/infoOut")
    @Inner(value = false)
    public R infoOut(@RequestParam Integer id) {
        TTraining o = tTrainingService.getById(id);
        return R.ok(o);
    }
    /**
     * 新增/修改培训信息
     */
    @SysLog("新增/修改培训信息")
    @ApiOperation(value = "新增/修改培训信息", notes = "新增/修改培训信息")
    @PostMapping("/addOrUp")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "培训海报文件", required = false, dataType = "File", paramType = "path"),
            @ApiImplicitParam(name = "startDateStr", value = "开始时间", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "endDateStr", value = "结束时间", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "TTraining", value = "培训信息", required = true, dataType = "json", paramType = "path")
    })
    public R addOrUp(TTraining tTraining, MultipartFile file,MultipartFile[] files,String downState,String startDateStr, String endDateStr,HttpServletRequest request) throws Exception {
        log.error("新增/修改培训信息：{}，##文件：{}，##开始时间：{}，##结束时间：{}",
                tTraining, file, startDateStr, endDateStr);
        String str="";
        String str1 ="";
        ScUser u = SecurityUtils.getUser();
        tTraining.setUserid(u.getId());
        tTraining.setUpdateTime(new Date());
        if(files!=null && files.length >0){
            for (int i=0;i<files.length;i++){
                MultipartFile trainingFile = files[i];
                str += getFileUrl(trainingFile)+",";
            }
        }
        if (tTraining.getId() == null) { //新增
            tTraining.setDelFlag("1");
            tTraining.setDeptId(u.getDeptId());
            if(str.length()>0){
                tTraining.setTrainingFile(str.substring(0,str.length()-1));
            }
        }else {
            //修改时有添加新的文件，取出原来的拼上新加的
            TTraining training1 = tTrainingService.getById(tTraining.getId());
            str1 = training1.getTrainingFile();
            tTraining.setTrainingFile(str+str1);
        }
        if (startDateStr != null && !"".equals(startDateStr)) {
            tTraining.setStartTime(new Date(startDateStr)); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (endDateStr != null && !"".equals(endDateStr)) {
            tTraining.setEndTime(new Date(endDateStr)); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (file != null) {
            if (file.getSize() > 0) {
                //海报文件
                tTraining.setPlacard(getFileUrl(file));
            }
        }
        tTrainingService.saveOrUpdate(tTraining);
        return R.ok(tTraining);
    }


    public String getFileUrl(MultipartFile file) throws Exception {
        String uuid = UUID.randomUUID().toString();
        InputStream inputStream = file.getInputStream(); //得到文件流
        String fileName = file.getOriginalFilename();    //文件名（含后缀）
        //minioTemplate.putObject("jljc", uuid, inputStream);
        minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");
        return fileName + "<" + uuid;
    }



    /**
     * 上传图片
     */

    public String uploadImage(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return "请上传图片";
        }
        try {
            String fileName = file.getOriginalFilename();
            String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
            fileName=UUID.randomUUID().toString().replace("_" , "")+"." + prefix;
            //存放上传图片文件夹
            File fileDir= UploadUtils.getImgDirFile();
            //输出文件夹绝对路径
            String url=fileDir.getAbsolutePath();

            //构建真是文件路径
            File newFile=new File(url+File.separator+fileName);
            System.err.println(newFile.getAbsolutePath());

            //上传图片到  绝对路径
            file.transferTo(newFile);
//            TTraining tTraining=new TTraining();
//            tTraining.setPlacard(fileName);

            //返回图片路径
            return String.valueOf(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片上传失败";
    }


    /**
     * 保存
     */
    @SysLog("增加培训")
    @ApiOperation(value = "增加培训", notes = "增加培训")
    @PostMapping("/save")
    @ApiImplicitParam(name = "TTraining", value = "增加培训", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TTraining tTraining) {
        ScUser u = SecurityUtils.getUser();
        tTraining.setUserid(u.getId());
        tTraining.setDeptId(u.getDeptId());
        tTraining.setDelFlag("1");
       /* if (!StringUtils.isEmpty(tTraining.getPlacardSting())) {
            tTraining.setPlacard(Base64.getDecoder().decode(tTraining.getPlacardSting()));
        }*/
        return R.ok(tTrainingService.save(tTraining));
    }

    /**
     * 修改
     */
    @SysLog("更新培训")
    @ApiOperation(value = "更新培训", notes = "更新培训")
    @PutMapping("/update")
    public R update(@RequestBody TTraining tTraining) {
        /*if (!StringUtils.isEmpty(tTraining.getPlacardSting())) {
            tTraining.setPlacard(Base64.getDecoder().decode(tTraining.getPlacardSting()));
        }*/
        return R.ok(tTrainingService.updateById(tTraining));
    }

    /**
     * 删除
     */
    @SysLog("删除培训")
    @ApiOperation(value = "删除培训", notes = "删除培训")
    @DeleteMapping("/delete")
    public R delete(Integer id) {
        TTraining tTraining = tTrainingService.getById(id);
        if (tTraining == null) {
            return R.failed("培训信息不存在，删除失败！");
        }
        ScUser u = SecurityUtils.getUser();
        tTraining.setUserid(u.getId());
        tTraining.setUpdateTime(new Date());
        tTraining.setDelFlag("4");
        return R.ok(tTrainingService.updateById(tTraining));
    }


    /**
     *  根据用户输入的关键字 进行模糊查询
     * @param name
     * @return
     */
    @SysLog("关键字查询培训")
    @ApiOperation(value = "关键字查询", notes = "关键字查询")
    @GetMapping("/getByKeyWord")
    public R getInfoByKeyWord(@RequestParam(value = "name") String name){
        return R.ok(tTrainingService.getInfoByKeyWord(name));
    }

    @SysLog("导入培训信息")
    @PostMapping("/excelImportTraining")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file) throws FileFormatException {
        return  tTrainingService.excelImport(file);
    }


    /*
    培训视频添加地址
     */
    @SysLog("培训视频添加地址")
    @PostMapping("/addVideoLink")
    @ApiOperation(value = "培训视频添加地址", notes = "培训视频添加地址")
    public R trainingVideo(@RequestParam Integer id,@RequestBody List<Object> videoLinks) throws Exception {
        TTraining tTraining = tTrainingService.getOne(new QueryWrapper<>(new TTraining())
                .eq("id",id)
                .eq("del_flag","1"));
        String videoLink = "";
        for (int i = 0; i < videoLinks.size(); i++){
            videoLink+=videoLinks.get(i)+",";
        }
        tTraining.setVideoLink(videoLink.substring(0,videoLink.length()-1));
        tTrainingService.updateById(tTraining);
        return R.ok("添加成功");
    }

    @SysLog("删除培训资料")
    @GetMapping("/deleteTrainingFile")
    @ApiOperation(value = "删除培训资料", notes = "删除培训资料")
    public R deleteTrainingFile(@RequestParam Integer trainingId,@RequestParam String fileName){
        TTraining tTraining = tTrainingService.getById(trainingId);
        if (tTraining!=null){
            String oldFiles = tTraining.getTrainingFile();
            String[] oldArr = oldFiles.split(",");
            List<String> list = Arrays.asList(oldArr);
            List<String> arrayList = new ArrayList<>(list);
            if (arrayList.size() > 0 && arrayList != null){
                arrayList.remove(fileName);
            }
            String str = "";
            if(arrayList.size() > 0) {
                for (int i = 0; i < arrayList.size(); i++) {
                    str += arrayList.get(i) + ",";
                }
            }else {
                str="";
            }
            if(str.length()>0){
                tTraining.setTrainingFile(str.substring(0, str.length() - 1));
            }else {
                tTraining.setTrainingFile(str);
            }
            return R.ok(tTrainingService.updateById(tTraining));
        }
        return R.failed("删除失败");
    }





}
