package org.jeecg.modules.qualityControl.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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
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.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.financeManage.service.IFdProjectReceivablesService;
import org.jeecg.modules.projectManagement.entity.FdProjectFileCompound;
import org.jeecg.modules.projectManagement.service.IFdProjectFileCompoundService;
import org.jeecg.modules.qualityControl.entity.FdQaProcessFacility;
import org.jeecg.modules.qualityControl.entity.FdQaProcessFacilityItems;
import org.jeecg.modules.qualityControl.service.IFdQaBiologicalAnalysisVerificationService;
import org.jeecg.modules.qualityControl.service.IFdQaProcessFacilityItemsService;
import org.jeecg.modules.qualityControl.service.IFdQaProcessFacilityService;

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.sampleAndConsumableManagement.controller.FdColumnManagementController;
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("/qualityControl/fdQaProcessFacility")
@Slf4j
public class FdQaProcessFacilityController {
    @Autowired
    private IFdQaProcessFacilityService fdQaProcessFacilityService;
    @Resource
    private FdColumnManagementController fdColumnManagementController;
    @Resource
    private IFdProjectFileCompoundService fdProjectFileCompoundService;
    @Resource
    private IFdQaBiologicalAnalysisVerificationService fdQaBiologicalAnalysisVerificationService;
    @Resource
    private IFdQaProcessFacilityItemsService fdQaProcessFacilityItemsService;
    @Resource
    private IFdProjectReceivablesService fdProjectReceivablesService;
    /**
     * 分页列表查询
     *
     * @param fdQaProcessFacility
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:processAndFacility:view")
    @PermissionData(pageComponent="processAndFacility")
    public Result<IPage<FdQaProcessFacility>> queryPageList(FdQaProcessFacility fdQaProcessFacility,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<FdQaProcessFacility>> result = new Result<IPage<FdQaProcessFacility>>();
        if (StringUtils.isNotBlank(fdQaProcessFacility.getProjectName())){
            fdQaProcessFacility.setProjectName("*"+fdQaProcessFacility.getProjectName()+"*");
        }
        //提交时间范围
        String startTime=fdQaProcessFacility.getStartTime();
        if(StringUtils.isNotBlank(startTime)){
            fdQaProcessFacility.setStartTime(null);
        }
        String endTime=fdQaProcessFacility.getEndTime();
        if(StringUtils.isNotBlank(endTime)){
            fdQaProcessFacility.setEndTime(null);
        }
        QueryWrapper<FdQaProcessFacility> queryWrapper = QueryGenerator.initQueryWrapper(fdQaProcessFacility, req.getParameterMap());
        //提交日期
        if(StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime)){
            queryWrapper.between("date_format(qa_submission_date,'%Y-%m-%d')",startTime,endTime);
        }
        queryWrapper.lambda().eq(FdQaProcessFacility::getDelFlag,"0");
        queryWrapper.orderByDesc("create_time");
        Page<FdQaProcessFacility> page = new Page<FdQaProcessFacility>(pageNo, pageSize);
        IPage<FdQaProcessFacility> pageList = fdQaProcessFacilityService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

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

    /**
     * 编辑
     *
     * @param fdQaProcessFacility
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdQaProcessFacility> edit(@RequestBody @Valid FdQaProcessFacility fdQaProcessFacility, BindingResult bindingResult) {
        Result<FdQaProcessFacility> result = new Result<FdQaProcessFacility>();
        FdQaProcessFacility fdQaProcessFacilityEntity = fdQaProcessFacilityService.getById(fdQaProcessFacility.getId());
        if (fdQaProcessFacilityEntity == 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 = fdQaProcessFacilityService.updateById(fdQaProcessFacility);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

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

        return result;
    }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdQaProcessFacility> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaProcessFacility> result = new Result<FdQaProcessFacility>();
        FdQaProcessFacility fdQaProcessFacility = fdQaProcessFacilityService.getById(id);
        if (fdQaProcessFacility == null) {
            result.error500("未找到对应实体");
        } else {
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(FdProjectFileCompound::getProjectId,fdQaProcessFacility.getPkProjectFile());
            queryWrapper1.eq(FdProjectFileCompound::getDelFlag,"0");
            List<FdProjectFileCompound> list1 = fdProjectFileCompoundService.list(queryWrapper1);
            fdQaProcessFacility.setFdProjectFileCompoundList(list1);
            //类型名称
            String analysisTypeName = fdQaBiologicalAnalysisVerificationService.getByDict(fdQaProcessFacility.getQaType());
            fdQaProcessFacility.setQaTypeName(analysisTypeName);
            //明细
            LambdaQueryWrapper<FdQaProcessFacilityItems> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdQaProcessFacilityItems::getPkQaProcessFacility,fdQaProcessFacility.getId());
            queryWrapper.orderByAsc(FdQaProcessFacilityItems::getCode);
            List<FdQaProcessFacilityItems> fdQaProcessFacilityItems = fdQaProcessFacilityItemsService.list(queryWrapper);
            //获取对应图片文件
            fdQaProcessFacilityService.getPictureUpload(fdQaProcessFacilityItems);
            fdQaProcessFacility.setFdQaProcessFacilityItemsList(fdQaProcessFacilityItems);
            result.setResult(fdQaProcessFacility);
            result.setSuccess(true);
        }
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdQaProcessFacility> pageList = fdQaProcessFacilityService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "质量保证（工艺与设备）列表");
        mv.addObject(NormalExcelConstants.CLASS, FdQaProcessFacility.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<FdQaProcessFacility> listFdQaProcessFacilitys = ExcelImportUtil.importExcel(file.getInputStream(), FdQaProcessFacility.class, params);
                for (FdQaProcessFacility fdQaProcessFacilityExcel : listFdQaProcessFacilitys) {
                    fdQaProcessFacilityService.save(fdQaProcessFacilityExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdQaProcessFacilitys.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 10:55 2019/6/10
  	 * @Param [fdQaProcessFacility, bindingResult]
  	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaProcessFacility>
  	 **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    @RequiresPermissions(value = {"processAndFacility:add","processAndFacility:update"},logical = Logical.OR)
    public Result<FdQaProcessFacility> addAll(@RequestBody @Valid FdQaProcessFacility fdQaProcessFacility, BindingResult bindingResult) {
        Result<FdQaProcessFacility> result = new Result<FdQaProcessFacility>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            if (fdQaProcessFacility.getFdQaProcessFacilityItemsList().size()==0){
                result.error500("操作失败,明细不能为空");
                return result;
            }
            //新增执行
            if(oConvertUtils.isEmpty(fdQaProcessFacility.getId())){
                LambdaQueryWrapper<FdQaProcessFacility> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FdQaProcessFacility::getQualityAssuranceFormNumber,fdQaProcessFacility.getQualityAssuranceFormNumber());
                queryWrapper.eq(FdQaProcessFacility::getDelFlag,"0");
                List<FdQaProcessFacility> list = fdQaProcessFacilityService.list(queryWrapper);
                if ( list!=null && list.size()>0){
                    result.error500("操作失败,质量保证单号不能重复");
                    return result;
                }
                //发送邮件通知
                String msg="工艺与设备-质量保证单号：‘"+fdQaProcessFacility.getQualityAssuranceFormNumber()+"’已经填写，请及时回复！";
//                fdProjectReceivablesService.noticeFinance(fdQaProcessFacility.getResponsibleQA(),"回复提醒",msg);
            }

            //根据子表评论判断主表状态
            boolean isOk=true;
            for(FdQaProcessFacilityItems items: fdQaProcessFacility.getFdQaProcessFacilityItemsList()){
                //如果找到一个不是接受的就是未完成
                if(StringUtils.isEmpty(items.getQaReview())||!items.getQaReview().equals("1")){
                    isOk=false;
                }
            }
            if(isOk){
                fdQaProcessFacility.setQualityStatus(2);
            }else{
                fdQaProcessFacility.setQualityStatus(1);
            }
            fdQaProcessFacilityService.addAll(fdQaProcessFacility);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 根据合同id查询项目档案数据
     * @Date 9:34 2019/7/3
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaProcessFacility>
     **/
    @GetMapping(value = "/queryQaProcessFacilityByConId")
    public Result<FdQaProcessFacility> queryQaProcessFacilityByConId(@RequestParam(name = "contractId", required = true) String contractId) {
        Result<FdQaProcessFacility> result = new Result<FdQaProcessFacility>();
        FdQaProcessFacility fdQaProcessFacility = fdQaProcessFacilityService.queryQaProcessFacilityByConId(contractId);
        if (fdQaProcessFacility == null) {
            result.error500("未找到对应实体");
        } else {
            //合同方名称
            String contractPartyName = fdColumnManagementController.getContractPartyName(fdQaProcessFacility.getPkContractParty());
            fdQaProcessFacility.setContractPartyName(contractPartyName);
            //化合物
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdProjectFileCompound::getProjectId, fdQaProcessFacility.getPkProjectFile());
            List<FdProjectFileCompound> list1 = fdProjectFileCompoundService.list(queryWrapper);
            String compoundName = "";
            String pkCompound = "";
            for (FdProjectFileCompound fdProjectFileCompound : list1) {
                if (compoundName == "") {
                    compoundName = fdProjectFileCompound.getCompound();
                    pkCompound = fdProjectFileCompound.getId();
                } else {
                    compoundName += "," + fdProjectFileCompound.getCompound();
                    pkCompound += "," + fdProjectFileCompound.getId();
                }
            }
            fdQaProcessFacility.setCompoundName(compoundName);
            fdQaProcessFacility.setPkCompound(pkCompound);
            fdQaProcessFacility.setFdProjectFileCompoundList(list1);
            //默认化合物 sort为1
            LambdaQueryWrapper<FdProjectFileCompound> queryWrapper6 = new LambdaQueryWrapper<>();
            queryWrapper6.eq(FdProjectFileCompound::getProjectId, fdQaProcessFacility.getPkProjectFile());
            queryWrapper6.eq(FdProjectFileCompound::getSort, "1");
            FdProjectFileCompound one = fdProjectFileCompoundService.getOne(queryWrapper6);
            fdQaProcessFacility.setCompound1(one.getCompound());
            fdQaProcessFacility.setCompound1Id(one.getId());

            result.setResult(fdQaProcessFacility);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * @Author gurui
     * @Description //TODO  删除 质量保证（工艺与设备） 同时删除其明细表
     * @Date 10:34 2019/7/3
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.qualityControl.entity.FdQaProcessFacility>
     **/
    @DeleteMapping(value = "/deleteAll")
    @NotDuplicate
    @RequiresPermissions("processAndFacility:delete")
    public Result<FdQaProcessFacility> deleteAll(@RequestParam(name = "id", required = true) String id) {
        Result<FdQaProcessFacility> result = new Result<FdQaProcessFacility>();
        FdQaProcessFacility fdQaProcessFacility = fdQaProcessFacilityService.getById(id);
        if (fdQaProcessFacility == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdQaProcessFacilityService.deleteAll(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }


}
