package cn.ezhizao.project.business.technologicalProcess.controller;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.technologicalProcess.domain.BizTechnologicalProcess;
import cn.ezhizao.project.business.technologicalProcess.service.IBizTechnologicalProcessService;
import cn.ezhizao.project.business.technologicalProcessDetail.domain.BizTechnologicalProcessDetail;
import cn.ezhizao.project.business.technologicalProcessDetail.service.IBizTechnologicalProcessDetailService;
import cn.ezhizao.project.business.technologicalProcessDetailDrawing.domain.BizTechnologicalProcessDetailDrawing;
import cn.ezhizao.project.business.technologicalProcessDetailDrawing.service.IBizTechnologicalProcessDetailDrawingService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工艺主表Controller
 *
 * @author ezhizao
 * @date 2023-11-13
 */
@RestController
@RequestMapping("/business/technologicalProcess")
public class BizTechnologicalProcessController extends BaseController {
    @Resource
    private IBizTechnologicalProcessService bizTechnologicalProcessService;

    @Resource
    HttpServletRequest request;

    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;
    @Resource
    private IBizTechnologicalProcessDetailDrawingService bizTechnologicalProcessDetailDrawingService;

    /**
     * 查询工艺主表列表
     */
//    @PreAuthorize("@ss.hasPermi('business:product:list')")
    @Log(title = "标准工艺查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizTechnologicalProcess bizTechnologicalProcess) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizTechnologicalProcess.setTenantId(Long.valueOf(tenantId));
//        startPage();
        List<BizTechnologicalProcess> list = bizTechnologicalProcessService.getList(bizTechnologicalProcess);
        if (list.size() > 0){
            //判断工艺图纸上传状态
            //产品id
            Long productId = list.get(0).getProductId();
            //工艺版本
            List<String> technologyVersionList = list.stream().map(BizTechnologicalProcess::getTechnologyVersion).collect(Collectors.toList());
            //工艺版本id
            List<Long> technologyIdList =  list.stream().map(BizTechnologicalProcess::getId).collect(Collectors.toList());
            //工序
            List<BizTechnologicalProcessDetail> technologicalProcessDetailList = bizTechnologicalProcessDetailService.query().eq("product_id", productId).in("technological_process_id", technologyIdList).list();
            //图纸
            List<BizTechnologicalProcessDetailDrawing> technologicalProcessDetailDrawingList = bizTechnologicalProcessDetailDrawingService.query().eq("product_id", productId).ne("status","3").eq("abandoned",0).in("product_version", technologyVersionList).list();
            //如果工序和图纸都没有，则置为0
            if(technologicalProcessDetailDrawingList.isEmpty() || technologicalProcessDetailList.isEmpty()){
                list.stream().forEach(l -> {
                    l.setUploadStatus(0);
                });
            }else{
                list.stream().forEach(l -> {
                    List<BizTechnologicalProcessDetail> processList = technologicalProcessDetailList.stream().filter(v -> v.getTechnologicalProcessId().equals(l.getId())).collect(Collectors.toList());
                    //如果这个工艺没有工序
                    if(processList.isEmpty()){
                        l.setUploadStatus(0);
                    }else{
                        //如果这个工艺有工序，判断这个工艺的工序有没有图纸
                        List<BizTechnologicalProcessDetailDrawing> processDrawingList = technologicalProcessDetailDrawingList.stream().filter(v -> v.getProductVersion().equals(l.getTechnologyVersion())).collect(Collectors.toList());
                        if(processDrawingList.isEmpty()){
                            l.setUploadStatus(0);
                        }else{
                            l.setUploadStatus(1);
                        }
                    }
                });
            }
        }
        return getDataTable(list);
    }
    @Log(title = "产品下标准工艺查询", businessType = BusinessType.SELECT)
    @PostMapping("/getTechnologicalForSupplier")
    public AjaxResult getTechnologicalForSupplier(@RequestBody Map<String, Object> data) {
        Long productId = Long.parseLong(data.get("productId").toString());
        List<BizTechnologicalProcess> list = bizTechnologicalProcessService.query()
                .eq("product_id", productId)
                .list();
        return success(list);
    }

    /**
     * 导出工艺主表列表
     */
//    @PreAuthorize("@ss.hasPermi('business:product:export')")
    @Log(title = "标准工艺导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizTechnologicalProcess bizTechnologicalProcess) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizTechnologicalProcess);
        List<BizTechnologicalProcess> list = bizTechnologicalProcessService.getList(bizTechnologicalProcess);
        ExcelUtil<BizTechnologicalProcess> util = new ExcelUtil<BizTechnologicalProcess>(BizTechnologicalProcess.class);
        util.exportExcel(response, list, "工艺主表数据");
    }

    /**
     * 获取工艺主表详细信息
     */
//    @PreAuthorize("@ss.hasPermi('business:product:query')")
    @Log(title = "标准工艺查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizTechnologicalProcessService.getById(id));
    }

    /**
     * 新增工艺主表
     */
//    @PreAuthorize("@ss.hasPermi('business:product:add, business:product:edit')")
    @Log(title = "标准工艺保存", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BizTechnologicalProcess bizTechnologicalProcess) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizTechnologicalProcess.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizTechnologicalProcessService.saveOrUpdate(bizTechnologicalProcess));
    }

    /**
     * 删除工艺主表
     */
//    @PreAuthorize("@ss.hasPermi('business:product:remove')")
    @Log(title = "标准工艺删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        List<BizTechnologicalProcessDetail> technologicalProcessId = bizTechnologicalProcessDetailService.query().in("technological_process_id", ids).list();
        if (technologicalProcessId.size() > 0) {
            return AjaxResult.error("该工艺主表下存在工艺明细，不能删除！");
        }
        return toAjax(bizTechnologicalProcessService.removeBatchByIds(ids));
    }
}
