package org.jeecg.modules.sampleAndConsumableManagement.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage;
import org.jeecg.modules.sampleAndConsumableManagement.service.IFdSampleStorageService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 样本存储
 * @author： jeecg-boot
 * @date： 2019-06-06
 * @version： V1.0
 */
@RestController
@RequestMapping("/sampleAndConsumableManagement/fdSampleStorage")
@Slf4j
public class FdSampleStorageController {
    @Autowired
    private IFdSampleStorageService fdSampleStorageService;

    /**
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage < org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage>>
     * @Author gurui
     * @Description //TODO 分页查询
     * @Date 14:28 2019/6/6
     * @Param [fdSampleStorage, pageNo, pageSize, req]
     **/
    @GetMapping(value = "/list")
    @RequiresPermissions("url:sample-storage:view")
    public Result<IPage<FdSampleStorage>> queryPageList(FdSampleStorage fdSampleStorage,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<FdSampleStorage>> result = new Result<IPage<FdSampleStorage>>();
        String trackingCode = fdSampleStorage.getTrackingCode();
        if (StringUtils.isNotBlank(fdSampleStorage.getTrackingCode())){
             fdSampleStorage.setTrackingCode(null);
         }
        String contractCode = fdSampleStorage.getContractCode();
        if (StringUtils.isNotBlank(fdSampleStorage.getContractCode())){
            fdSampleStorage.setContractCode(null);
        }
        QueryWrapper<FdSampleStorage> queryWrapper = QueryGenerator.initQueryWrapper(fdSampleStorage, req.getParameterMap());
        if (StringUtils.isNotBlank(trackingCode)) {
            queryWrapper.like("tracking_code", trackingCode);
        }
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        queryWrapper.lambda().eq(FdSampleStorage::getDelFlag,"0");
        queryWrapper.lambda().orderByDesc(FdSampleStorage::getCreateTime);
        Page<FdSampleStorage> page = new Page<FdSampleStorage>(pageNo, pageSize);
        // IPage<FdSampleStorage> pageList = fdSampleStorageService.findByPage(page, queryWrapper);
        IPage<FdSampleStorage> pageList = fdSampleStorageService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdSampleStorage
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    @RequiresPermissions("sample-storage:add")
    public Result<FdSampleStorage> add(@RequestBody @Valid FdSampleStorage fdSampleStorage, BindingResult bindingResult) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdSampleStorageService.save(fdSampleStorage);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 样本存储添加
    * @Date 2020/8/13 9:17
    * @Param [fdSampleStorage, bindingResult]
    * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage>
    */
    @PostMapping(value = "/addCustom")
    @NotDuplicate
    @RequiresPermissions("sample-storage:add")
    public Result<FdSampleStorage> addCustom(@RequestBody @Valid FdSampleStorage fdSampleStorage, BindingResult bindingResult) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdSampleStorageService.addCustom(fdSampleStorage);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdSampleStorage
     * @return
     */
    @PutMapping(value = "/updateCustom")
    @NotDuplicate
    @RequiresPermissions("sample-storage:update")
    public Result<FdSampleStorage> updateCustom(@RequestBody @Valid FdSampleStorage fdSampleStorage, BindingResult bindingResult) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        FdSampleStorage fdSampleStorageEntity = fdSampleStorageService.getById(fdSampleStorage.getId());
        if (fdSampleStorageEntity == null) {
            result.error500("未找到对应实体");
        } else {
            try {
                StringBuilder sb = new StringBuilder();
                if (bindingResult.hasErrors()) {
                    //记录错误信息
                    bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                    result.error500(sb.toString());
                    return result;
                }
                fdSampleStorageService.updateCustom(fdSampleStorage);
                result.success("修改成功！");
            } catch (Exception e) {
                e.printStackTrace();
                log.info(e.getMessage());
                result.error500("操作失败"+e.getMessage());
            }
        }

        return result;
    }

    @PutMapping(value = "/edit")
    @NotDuplicate
    @RequiresPermissions("sample-storage:update")
    public Result<FdSampleStorage> edit(@RequestBody @Valid FdSampleStorage fdSampleStorage, BindingResult bindingResult) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        FdSampleStorage fdSampleStorageEntity = fdSampleStorageService.getById(fdSampleStorage.getId());
        if (fdSampleStorageEntity == null) {
            result.error500("未找到对应实体");
        } else {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            boolean ok = fdSampleStorageService.updateById(fdSampleStorage);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    // @DeleteMapping(value = "/delete")
    // public Result<FdSampleStorage> delete(@RequestParam(name = "id", required = true) String id) {
    //     Result<FdSampleStorage> result = new Result<FdSampleStorage>();
    //     FdSampleStorage fdSampleStorage = fdSampleStorageService.getById(id);
    //     if (fdSampleStorage == null) {
    //         result.error500("未找到对应实体");
    //     } else {
    //         boolean ok = fdSampleStorageService.removeById(id);
    //         if (ok) {
    //             result.success("删除成功!");
    //         }
    //     }
    //
    //     return result;
    // }

    /***
     * @Title:删除
            * @Description:TODO
            * @param id
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage>
            * @exception
            * @author 陈创
            * @date 2019/11/1 17:10
            * @updatehistory:
     *   2019/11/1 17:10 删除
            */
    @DeleteMapping(value = "/delete")
    @NotDuplicate
    @RequiresPermissions("sample-storage:delete")
    public Result<FdSampleStorage> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        FdSampleStorage fdSampleStorage = fdSampleStorageService.getById(id);
        if (fdSampleStorage == null) {
            result.error500("未找到对应实体");
        } else {
            fdSampleStorage.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            boolean ok = fdSampleStorageService.updateById(fdSampleStorage);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdSampleStorage> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdSampleStorageService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdSampleStorage> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        FdSampleStorage fdSampleStorage = fdSampleStorageService.getById(id);
        if (fdSampleStorage == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdSampleStorage);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdSampleStorage> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdSampleStorage fdSampleStorage = JSON.parseObject(deString, FdSampleStorage.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdSampleStorage, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdSampleStorage> pageList = fdSampleStorageService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "样本存储列表");
        mv.addObject(NormalExcelConstants.CLASS, FdSampleStorage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("样本存储列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdSampleStorage> listFdSampleStorages = ExcelImportUtil.importExcel(file.getInputStream(), FdSampleStorage.class, params);
                for (FdSampleStorage fdSampleStorageExcel : listFdSampleStorages) {
                    fdSampleStorageService.save(fdSampleStorageExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdSampleStorages.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * @Author gurui
     * @Description //TODO  添加样本存储同时 添加   存储位置
     * @Date 13:38 2019/6/10
     * @Param [fdSampleStorage, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    public Result<FdSampleStorage> addAll(@RequestBody @Valid FdSampleStorage fdSampleStorage, BindingResult bindingResult) {
        Result<FdSampleStorage> result = new Result<FdSampleStorage>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdSampleStorageService.addAll(fdSampleStorage);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:根据合同id查询项目档案相关信息
            * @Description:TODO
            * @param contractId
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.sampleAndConsumableManagement.entity.FdSampleStorage>
            * @exception 
            * @author 陈创
            * @date 2019/6/25 13:37
            * @updatehistory:
     *   2019/6/25 13:37 查询
            */
    @GetMapping(value = "/getSampleStorageByConId")
        public Result<FdSampleStorage> getSampleStorageByConId(String projectFileId){
        Result<FdSampleStorage> result=new Result<>();
        FdSampleStorage fdSampleStorage=fdSampleStorageService.getSampleStorageByConId(projectFileId);
        if(fdSampleStorage==null){
            result.error500("未找到对应数据");
        }else{
            result.setResult(fdSampleStorage);
            result.setSuccess(true);
        }
        return result;
    }

}
