package com.foreverwin.mesnac.quality.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.quality.mapper.InspectionProjectDetailMapper;
import com.foreverwin.mesnac.quality.mapper.InspectionProjectMapper;
import com.foreverwin.mesnac.quality.model.InspectionProject;
import com.foreverwin.mesnac.quality.model.InspectionProjectDetail;
import com.foreverwin.mesnac.quality.service.InspectionProjectDetailService;
import com.foreverwin.mesnac.quality.service.InspectionProjectService;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import com.foreverwin.modular.core.util.R;
import com.visiprise.common.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author Robert
 * @since 2021-06-03
 */
@RestController
@RequestMapping("/Z-INSPECTION-PROJECT")
public class InspectionProjectController {

    @Autowired
    public InspectionProjectService inspectionProjectService;

    @Autowired
    public InspectionProjectMapper inspectionProjectMapper;
    
    @Autowired
    public InspectionProjectDetailMapper inspectionProjectDetailMapper;
    
    @Autowired
    public InspectionProjectDetailService inspectionProjectDetailService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public R getInspectionProjectById(@PathVariable String id) {
        return R.ok( inspectionProjectService.getById(id));
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public R getInspectionProjectList(InspectionProject inspectionProject){
        List<InspectionProject> result;
        QueryWrapper<InspectionProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(inspectionProject);
        result = inspectionProjectService.list(queryWrapper);
        return R.ok(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/page")
    public R page(FrontPage<InspectionProject> frontPage, InspectionProject inspectionProject){
        IPage result;
        QueryWrapper<InspectionProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(inspectionProject);
        if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
            //TODO modify global query
            queryWrapper.lambda().and(wrapper -> wrapper
                .like(InspectionProject::getHandle, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getSite, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getInspectProjectNo, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getInspectType, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getRevision, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getCurrentRevision, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getDescription, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getStatus, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getItemBo, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getItem, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getOperation, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getStepId, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getSubStep, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getCreateUser, frontPage.getGlobalQuery())
                .or().like(InspectionProject::getModifyUser, frontPage.getGlobalQuery())
    );
        }
        result = inspectionProjectService.page(frontPage.getPagePlus(), queryWrapper);
        return R.ok(result);
    }

    /**
     * 新增
     * @param inspectionProject  传递的实体
     * @return  null 失败  实体成功
     */
    @PostMapping
    public R save(@RequestBody InspectionProject inspectionProject) {
        return R.ok(inspectionProjectService.save(inspectionProject));
    }

    /**
     * 修改
     * @param inspectionProject  传递的实体
     * @return  null 失败  实体成功
     */
    @PutMapping
    public R updateById(@RequestBody InspectionProject inspectionProject) {
        return R.ok(inspectionProjectService.updateById(inspectionProject));
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public R removeById(@PathVariable("id") String id){
        return R.ok(inspectionProjectService.removeById(id));
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/delete-batch")
    public R removeByIds(List<String> ids){
        return R.ok(inspectionProjectService.removeByIds(ids));
    }


    @PostMapping("/saveAll")
    public R saveAll(@RequestBody InspectionProject inspectionProject){
        boolean b = false;
        if(StringUtil.isEmpty(inspectionProject.getInspectProjectNo())){
            b = true;
            inspectionProject.setInspectProjectNo(inspectionProjectService.InspectProjectNoGenerationRules(inspectionProject));
        }
        inspectionProject.setSite(CommonMethods.getSite());
        inspectionProject.setHandle("InspectionProjectBO:"+inspectionProject.getSite()+","+inspectionProject.getInspectProjectNo()+","+inspectionProject.getRevision());
        //保存检验项目维护-副
        //移除
        HashMap<String, Object> removeCondition = new HashMap<>();
        removeCondition.put("INSPECT_PROJECT_BO",inspectionProject.getHandle());
        inspectionProjectDetailService.removeByMap(removeCondition);
        if(null != inspectionProject.getInspectionProjectDetailList() && inspectionProject.getInspectionProjectDetailList().size() > 0){
            List<InspectionProjectDetail> inspectionProjectDetailList = inspectionProject.getInspectionProjectDetailList();
            for (InspectionProjectDetail inspectionProjectDetail : inspectionProjectDetailList) {
                inspectionProjectDetail.setHandle(UUID.randomUUID().toString());
                inspectionProjectDetail.setInspectProjectBo(inspectionProject.getHandle());
                inspectionProjectDetail.setCreatedDateTime(LocalDateTime.now());
                inspectionProjectDetail.setCreateUser(CommonMethods.getUser());
                inspectionProjectDetail.setModifiedDateTime(LocalDateTime.now());
                inspectionProjectDetail.setModifyUser(CommonMethods.getUser());
            }
            //保存
            inspectionProjectDetailService.saveBatch(inspectionProjectDetailList);
            
        }
        //保存检验项目维护-主
        if(inspectionProject.selectById(inspectionProject.getHandle()) == null){
            inspectionProject.setCreatedDateTime(LocalDateTime.now());
            inspectionProject.setCreateUser(CommonMethods.getUser());
            inspectionProject.setModifiedDateTime(LocalDateTime.now());
            inspectionProject.setModifyUser(CommonMethods.getUser());
            inspectionProjectService.save(inspectionProject);
        }else{
            inspectionProject.setModifiedDateTime(LocalDateTime.now());
            inspectionProject.setModifyUser(CommonMethods.getUser());
            if(b){
                throw new BaseException("请先检索再保存");
            }
            inspectionProjectService.saveOrUpdate(inspectionProject);
        }
        return R.ok();
    }
    @PostMapping("/deleteById")
    public R deleteById(@RequestBody InspectionProject inspectionProject){
        boolean bool = false;
        if(StringUtil.isEmpty(inspectionProject.getInspectProjectNo())){
            inspectionProject.setInspectProjectNo(inspectionProjectService.InspectProjectNoGenerationRules(inspectionProject));
            bool = true;
        }
        inspectionProject.setSite(CommonMethods.getSite());
        inspectionProject.setHandle("InspectionProjectBO:"+inspectionProject.getSite()+","+inspectionProject.getInspectProjectNo()+","+inspectionProject.getRevision());
        HashMap<String, Object> removeCondition = new HashMap<>();
        removeCondition.put("INSPECT_PROJECT_BO",inspectionProject.getHandle());
        inspectionProjectDetailService.removeByMap(removeCondition);
        boolean b = inspectionProjectService.removeById(inspectionProject);
        if(bool){
            if(b){
                throw new BaseException("请先检索再保存");
            }
        }
        return R.ok();
    }
    @GetMapping("/queryAll")
    public R queryAll(InspectionProject inspectionProject){
        if(StringUtil.isEmpty(inspectionProject.getInspectProjectNo())){
            inspectionProject.setInspectProjectNo(inspectionProjectService.InspectProjectNoGenerationRules(inspectionProject));
        }
        if(StringUtil.isEmpty(inspectionProject.getRevision())){
            String revision = inspectionProjectService.findRevisionByCurrentRevision(inspectionProject.getInspectProjectNo());
            if(StringUtil.isEmpty(revision)){
                throw new BaseException("请输入版本号");
            }
            inspectionProject.setRevision(revision);
        }
        inspectionProject.setSite(CommonMethods.getSite());
        inspectionProject.setHandle("InspectionProjectBO:"+inspectionProject.getSite()+","+inspectionProject.getInspectProjectNo()+","+inspectionProject.getRevision());

        HashMap<String, Object> findCondition = new HashMap<>();
        findCondition.put("INSPECT_PROJECT_BO",inspectionProject.getHandle());
        List<InspectionProjectDetail> inspectionProjectDetails = inspectionProjectDetailMapper.selectByMap(findCondition);
        InspectionProject handle = inspectionProjectMapper.selectById(inspectionProject.getHandle());
        handle.setInspectionProjectDetailList(inspectionProjectDetails);
        if(null == handle){
            throw new BaseException("根据此项目编号以及版本未检索到数据");
        }
        return R.ok(handle);
    }
}






























