package org.jeecg.modules.projectManagement.controller;

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 org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.projectManagement.entity.FdProjectQuotationTemplate;
import org.jeecg.modules.projectManagement.service.IFdProjectQuotationTemplateService;

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.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-05-20
 * @version： V1.0
 */
@RestController
@RequestMapping("/projectManagement/fdProjectQuotationTemplate")
@Slf4j
public class FdProjectQuotationTemplateController {
    @Autowired
    private IFdProjectQuotationTemplateService fdProjectQuotationTemplateService;

    /**
     * 分页列表查询
     *
     * @param fdProjectQuotationTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdProjectQuotationTemplate>> queryPageList(FdProjectQuotationTemplate fdProjectQuotationTemplate,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                   HttpServletRequest req) {
        Result<IPage<FdProjectQuotationTemplate>> result = new Result<IPage<FdProjectQuotationTemplate>>();
        QueryWrapper<FdProjectQuotationTemplate> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectQuotationTemplate, req.getParameterMap());
        queryWrapper.lambda().eq(FdProjectQuotationTemplate::getDelFlag,"0");
        Page<FdProjectQuotationTemplate> page = new Page<FdProjectQuotationTemplate>(pageNo, pageSize);
        IPage<FdProjectQuotationTemplate> pageList = fdProjectQuotationTemplateService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdProjectQuotationTemplate
     * @return
     */
    @PostMapping(value = "/add")
    public Result<FdProjectQuotationTemplate> add(@RequestBody FdProjectQuotationTemplate fdProjectQuotationTemplate) {
        Result<FdProjectQuotationTemplate> result = new Result<FdProjectQuotationTemplate>();
        try {
            fdProjectQuotationTemplateService.saveProjectQuotationTemplate(fdProjectQuotationTemplate);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdProjectQuotationTemplate
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<FdProjectQuotationTemplate> edit(@RequestBody FdProjectQuotationTemplate fdProjectQuotationTemplate) {
        Result<FdProjectQuotationTemplate> result = new Result<FdProjectQuotationTemplate>();
        FdProjectQuotationTemplate fdProjectQuotationTemplateEntity = fdProjectQuotationTemplateService.getById(fdProjectQuotationTemplate.getId());
        if (fdProjectQuotationTemplateEntity == null) {
            result.error500("未找到对应实体");
        } else {
            fdProjectQuotationTemplateService.updateProjectQuotationTemplate(fdProjectQuotationTemplate);

        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdProjectQuotationTemplate> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectQuotationTemplate> result = new Result<FdProjectQuotationTemplate>();
        FdProjectQuotationTemplate fdProjectQuotationTemplate = fdProjectQuotationTemplateService.getById(id);
        if (fdProjectQuotationTemplate == null) {
            result.error500("未找到对应实体");
        } else {
            fdProjectQuotationTemplateService.updateById(fdProjectQuotationTemplate);
        }

        return result;
    }

    /**
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdProjectQuotationTemplate>
     * @Author gurui
     * @Description //TODO 单个或多个删除
     * @Date 11:32 2019/5/21
     * @Param [ids]
     **/
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdProjectQuotationTemplate> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdProjectQuotationTemplate> result = new Result<FdProjectQuotationTemplate>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdProjectQuotationTemplateService.deleteProjectQuotationTemplate(ids);
            result.success("删除成功!");
        }
        return result;
    }

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

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdProjectQuotationTemplate> pageList = fdProjectQuotationTemplateService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "项目报价选择的模板对照表列表");
        mv.addObject(NormalExcelConstants.CLASS, FdProjectQuotationTemplate.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<FdProjectQuotationTemplate> listFdProjectQuotationTemplates = ExcelImportUtil.importExcel(file.getInputStream(), FdProjectQuotationTemplate.class, params);
                for (FdProjectQuotationTemplate fdProjectQuotationTemplateExcel : listFdProjectQuotationTemplates) {
                    fdProjectQuotationTemplateService.save(fdProjectQuotationTemplateExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdProjectQuotationTemplates.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /*
     *
     * 根据报价单id查询模板类型
     * @author 陈创
     * @date 2019/5/24
     * @param
     * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectQuotationTemplate>>
     */
    @GetMapping(value = "getByQuotationId")
    public Result<List<FdProjectQuotationTemplate>> getByQuotationId(@RequestParam("quotationId") String quotationId) {
        Result<List<FdProjectQuotationTemplate>> result = new Result<>();
        result.setResult(fdProjectQuotationTemplateService.getByQuotationId(quotationId));
        return result;
    }

    //根据合同档案基本信息表 的 来源报价单id 查询模板类型
    @GetMapping(value = "getByQuotationId1")
    public Result<List<FdProjectQuotationTemplate>> getByQuotationId1(@RequestParam("quotationId") String quotationId) {
        Result<List<FdProjectQuotationTemplate>> result = new Result<>();
        result.setResult(fdProjectQuotationTemplateService.getByQuotationId1(quotationId));
        return result;
    }


    /***
     * @Title:获取模板以及模板下的明细项
            * @Description:TODO
            * @param quotationId
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectQuotationTemplate>>
            * @exception 
            * @author 陈创
            * @date 2019/9/20 12:08
            * @updatehistory:
     *   2019/9/20 12:08 新增
            */
    @GetMapping(value = "/getTemplateAndItemsByQuotationId")
    public Result<List<FdProjectQuotationTemplate>> getTemplateAndItemsByQuotationId(@RequestParam("quotationId") String quotationId) {
        Result<List<FdProjectQuotationTemplate>> result = new Result<>();
        result.setResult(fdProjectQuotationTemplateService.getTemplateAndItemsByQuotationId(quotationId));
        return result;
    }
}
