package org.jeecg.modules.basedata.controller;

import java.util.*;
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 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.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdQuotationTemplate;
import org.jeecg.modules.basedata.entity.FdQuotationTemplateItem;
import org.jeecg.modules.basedata.service.IFdQuotationTemplateService;

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.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
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-05-16
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdQuotationTemplate")
@Slf4j
public class FdQuotationTemplateController {
    @Autowired
    private IFdQuotationTemplateService fdQuotationTemplateService;

    @Autowired
    private ISysDictService sysDictService;


    /**
     * 分页列表查询
     *
     * @param fdQuotationTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdQuotationTemplate>> queryPageList(FdQuotationTemplate fdQuotationTemplate,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<FdQuotationTemplate>> result = new Result<IPage<FdQuotationTemplate>>();
        //对报价表模板名称进行模糊查询
        if (StringUtils.isNotBlank(fdQuotationTemplate.getName())) {
            fdQuotationTemplate.setName("*" + fdQuotationTemplate.getName() + "*");
        }

        QueryWrapper<FdQuotationTemplate> queryWrapper = QueryGenerator.initQueryWrapper(fdQuotationTemplate, req.getParameterMap());
        queryWrapper.orderByDesc("type");
        queryWrapper.orderByAsc("create_time");
        Page<FdQuotationTemplate> page = new Page<FdQuotationTemplate>(pageNo, pageSize);
        //IPage<FdQuotationTemplate> pageList = fdQuotationTemplateService.page(page, queryWrapper);
        IPage<FdQuotationTemplate> pageList = fdQuotationTemplateService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 分页列表查询（有权限）
     *
     * @param fdQuotationTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list1")
    @RequiresPermissions("url:quotation:view")
    public Result<IPage<FdQuotationTemplate>> queryPageList1(FdQuotationTemplate fdQuotationTemplate,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<FdQuotationTemplate>> result = new Result<IPage<FdQuotationTemplate>>();
        //对报价表模板名称进行模糊查询
        if (StringUtils.isNotBlank(fdQuotationTemplate.getName())) {
            fdQuotationTemplate.setName("*" + fdQuotationTemplate.getName() + "*");
        }

        QueryWrapper<FdQuotationTemplate> queryWrapper = QueryGenerator.initQueryWrapper(fdQuotationTemplate, req.getParameterMap());
        queryWrapper.orderByDesc("type");
        queryWrapper.orderByAsc("create_time");
        Page<FdQuotationTemplate> page = new Page<FdQuotationTemplate>(pageNo, pageSize);
        //IPage<FdQuotationTemplate> pageList = fdQuotationTemplateService.page(page, queryWrapper);
        IPage<FdQuotationTemplate> pageList = fdQuotationTemplateService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

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

        }
        return result;
    }

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

        return result;
    }

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

        return result;
    }

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

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

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQuotationTemplate> pageList = fdQuotationTemplateService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "报价单模板列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQuotationTemplate.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<FdQuotationTemplate> listFdQuotationTemplates = ExcelImportUtil.importExcel(file.getInputStream(), FdQuotationTemplate.class, params);
                for (FdQuotationTemplate fdQuotationTemplateExcel : listFdQuotationTemplates) {
                    fdQuotationTemplateService.save(fdQuotationTemplateExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQuotationTemplates.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 陈创
     * @date 2019/5/23
     * @param
     * @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     */
    @GetMapping(value = "getTemplateByType")
    public Result<List<Map<String, Object>>> getTemplateByType() {
        Result<List<Map<String, Object>>> result = new Result<>();
        List<Map<String, Object>> listSysDict = sysDictService.queryDictItemsByCode("quotation_template_type");//模板类型
        List<FdQuotationTemplate> listTemplate = fdQuotationTemplateService.list();//模板名称
        //循环模板类型
        for (Map<String, Object> map : listSysDict) {
            String type = map.get("value").toString();//模板类型
            List<Map<String, Object>> list = new ArrayList<>();//定义模板名称list
            for (FdQuotationTemplate fdQuotationTemplate : listTemplate) {
                if (type.equals(fdQuotationTemplate.getType())) {//根据类型添加模板名称
                    // fdQuotationTemplate.setLeaf(true);//设置末端
                    //封装字段
                    Map<String, Object> listMap = new HashMap<>();//定义模板名称对象map
                    listMap.put("label", fdQuotationTemplate.getName());
                    listMap.put("value", fdQuotationTemplate.getId());
                    listMap.put("languageType", fdQuotationTemplate.getLanguageType());//语言类型
                    listMap.put("isLeaf", true);
                    list.add(listMap);
                }
            }
            map.put("children", list);
            map.put("label", map.get("text"));
        }

        result.setResult(listSysDict);
        return result;
    }


    /***
     * @Title:根据多个id查询模板
            * @Description:TODO
            * @param ids
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.basedata.entity.FdQuotationTemplate>>
            * @exception
            * @author 陈创
            * @date 2019/6/11 17:27
            * @updatehistory:
     *   2019/6/11 17:27 查询
            */
    @GetMapping(value = "getbyIdBatch")
    public Result<List<FdQuotationTemplate>> getbyIdBatch(@RequestParam("ids")List<String> ids) {
        Result<List<FdQuotationTemplate>> result=new Result<>();
        List<FdQuotationTemplate> quotationTemplateList= null;
        try {
            if(ids.isEmpty()){
                throw new RuntimeException("请选择模板");
            }
            quotationTemplateList = fdQuotationTemplateService.getbyIdBatch(ids);
            if(quotationTemplateList.isEmpty()){
                throw new RuntimeException("未查询到所对应的模板");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error500(e.getMessage());
        }
        result.setResult(quotationTemplateList);
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO 复制一条一样的模板
     * @Date 16:47 2019/7/5
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdQuotationTemplate>
     **/
    @PostMapping(value = "/copy")
    @NotDuplicate
    @RequiresPermissions("quotation:copy")
    public Result<FdQuotationTemplate> copy(@RequestBody String id) {
        Result<FdQuotationTemplate> result = new Result<FdQuotationTemplate>();
        try {
            List<FdQuotationTemplateItem> list=fdQuotationTemplateService.copy(id);
            result.success("复制成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO 删除模板同时删除模板项
     * @Date 20:01 2019/7/16
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdQuotationTemplate>
     **/
    @DeleteMapping(value = "/deleteAll")
    @NotDuplicate
    @RequiresPermissions("quotation:delete")
    public Result<FdQuotationTemplate> deleteAll(@RequestParam(name = "id", required = true) String id) {
        Result<FdQuotationTemplate> result = new Result<FdQuotationTemplate>();
        FdQuotationTemplate fdQuotationTemplate = fdQuotationTemplateService.getById(id);
        if (fdQuotationTemplate == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdQuotationTemplateService.deleteAll(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

}
