package cn.ezhizao.project.business.controller;

import cn.ezhizao.common.utils.SecurityUtils;
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.domain.*;
import cn.ezhizao.project.business.service.IBizDayworkItemConsultService;
import cn.ezhizao.project.business.service.IBizProcessInspecionService;
import cn.ezhizao.project.business.service.IBizProcessInspectionRelationDetailService;
import cn.ezhizao.project.business.service.IBizProcessInspectionRelationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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


/**
 * 咨询Controller
 *
 * @author ezhizao
 * 日期 2023-11-14
 */
@RestController
@RequestMapping("/business/consult")
public class BizDayworkItemConsultController extends BaseController {
    @Resource
    private IBizDayworkItemConsultService iBizDayworkItemConsultService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private IBizProcessInspecionService bizProcessInspecionService;
    @Resource
    private IBizProcessInspectionRelationService bizProcessInspectionRelationService;
    @Resource
    private IBizProcessInspectionRelationDetailService bizProcessInspectionRelationDetailService;

    @GetMapping("/list")
    @Log(title = "获取报工咨询列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizDayworkItemConsult data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        // 分页
        startPage();
        setTenantId(data);
        if (getUserId() != 1 && data.getConsultDepartment().equals(0)) {
            data.setTechnicianId(getUserId());
        }
        List<BizDayworkItemConsult> list = iBizDayworkItemConsultService.getList(data);
        return getDataTable(list);
    }

    /**
     * 获取咨询详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    @Log(title = "获取咨询详情", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(iBizDayworkItemConsultService.getById(id));
    }

    /**
     * 新增咨询
     */
    @Log(title = "新增咨询", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody BizDayworkItemConsult bizDayworkItemConsult) throws NoSuchFieldException, IllegalAccessException {
        final String tenantId = request.getHeader("tenantId");
        bizDayworkItemConsult.setReviewerId(SecurityUtils.getLoginUser().getUser().getUserId());
        BizDayworkItemConsult consult = iBizDayworkItemConsultService.query().eq("id", bizDayworkItemConsult.getId()).one();
        consult.setTenantId(Long.valueOf(tenantId));
        consult.setReviewerId(SecurityUtils.getLoginUser().getUser().getUserId());
        consult.setStatus(bizDayworkItemConsult.getStatus());
        consult.setConsultResultId(bizDayworkItemConsult.getConsultResultId());
        consult.setConsultResultResult(bizDayworkItemConsult.getConsultResultResult());
        iBizDayworkItemConsultService.saveOrUpdate(consult);
        //判断是否是检查的咨询，如果是检查的咨询，则查出该检查所有的咨询，是否都通过，如果都通过则将process_inspection的status设置为1，有待确认的设置为待确认，没有待确认的，有不合格的设置为不合格
        if (consult.getProcessInspectionId() != 0) {
            List<BizDayworkItemConsult> list = iBizDayworkItemConsultService.query().eq("process_inspection_id", consult.getProcessInspectionId()).list();
            if (list.size() == 1) {
                List<BizProcessInspecion> processInspection = bizProcessInspecionService.query().eq("id", consult.getProcessInspectionId()).list();
                if (!processInspection.isEmpty()) {
                    //判断检查是否是外协检，如果是外协检需要判断是否有关联批次
                    List<BizProcessInspectionRelation> processInspectionRelationList = bizProcessInspectionRelationService.query().eq("process_inspection_id", consult.getProcessInspectionId()).list();
                    if (!processInspectionRelationList.isEmpty()) {
                        //主批关联的批次(不看主批，只看关联批次)
                        List<BizProcessInspectionRelationDetail> processInspectionRelationDetailList = bizProcessInspectionRelationDetailService.query()
                                .eq("process_inspection_relation_id", processInspectionRelationList.get(0).getId()).eq("is_master", 0).list();
                        if (!processInspectionRelationDetailList.isEmpty()) {
                            //关联批次的所有检查id
                            List<Long> processInspecionIds = processInspectionRelationDetailList.stream().map(BizProcessInspectionRelationDetail::getProcessInspectionId).collect(Collectors.toList());
                            //关联批次存在额外的检查
                            if (!processInspecionIds.isEmpty()) {
                                List<BizProcessInspecion> processInspectionList = bizProcessInspecionService.query().in("id", processInspecionIds).list();
                                processInspectionList.forEach(item -> {
                                    item.setStatus(bizDayworkItemConsult.getStatus() == 0 ? 0 : bizDayworkItemConsult.getStatus() == 1 ? 2 : 1);
                                });
                                bizProcessInspecionService.saveOrUpdateBatch(processInspectionList);
                            }
                        }
                    }
                    processInspection.forEach(item -> {
                        item.setStatus(bizDayworkItemConsult.getStatus() == 0 ? 0 : bizDayworkItemConsult.getStatus() == 1 ? 2 : 1);
                        if (item.getType().equals("deliveryInspection")) {
                            item.setAdoptStatus(bizDayworkItemConsult.getStatus() == 0 ? 0 : bizDayworkItemConsult.getStatus() == 1 ? 2 : 1);
                        }
                    });
                    bizProcessInspecionService.saveOrUpdateBatch(processInspection);
                }
            } else {
                //多条咨询
                List<Integer> statusList = list.stream().map(BizDayworkItemConsult::getStatus).collect(Collectors.toList());
                if (statusList.contains(0) || statusList.contains(1)) {
                    //该检查的咨询存在不合格和待确认的
                    List<BizProcessInspecion> processInspection = bizProcessInspecionService.query().eq("id", consult.getProcessInspectionId()).list();
                    if (!processInspection.isEmpty()) {
                        //判断检查是否是外协检，如果是外协检需要判断是否有关联批次
                        List<BizProcessInspectionRelation> processInspectionRelationList = bizProcessInspectionRelationService.query().eq("process_inspection_id", consult.getProcessInspectionId()).list();
                        if (!processInspectionRelationList.isEmpty()) {
                            //主批关联的批次(不看主批，只看关联批次)
                            List<BizProcessInspectionRelationDetail> processInspectionRelationDetailList = bizProcessInspectionRelationDetailService.query()
                                    .eq("process_inspection_relation_id", processInspectionRelationList.get(0).getId()).eq("is_master", 0).list();
                            if (!processInspectionRelationDetailList.isEmpty()) {
                                //关联批次的所有检查id
                                List<Long> processInspecionIds = processInspectionRelationDetailList.stream().map(BizProcessInspectionRelationDetail::getProcessInspectionId).collect(Collectors.toList());
                                //关联批次存在额外的检查
                                if (!processInspecionIds.isEmpty()) {
                                    List<BizProcessInspecion> processInspectionList = bizProcessInspecionService.query().in("id", processInspecionIds).list();
                                    //改为不合格
                                    processInspectionList.forEach(item -> {
                                        //如果有不合格，则为不合格，如果有待确认，则为待确认
                                        item.setStatus(statusList.contains(0) ? 0 : 2);
                                    });
                                    bizProcessInspecionService.saveOrUpdateBatch(processInspectionList);
                                }
                            }
                        }
                        //改为不合格
                        processInspection.forEach(item -> {
                            item.setStatus(statusList.contains(0) ? 0 : 2);
                            if (item.getType().equals("deliveryInspection")) {
                                item.setAdoptStatus(statusList.contains(0) ? 0 : 2);
                            }
                        });
                        bizProcessInspecionService.saveOrUpdateBatch(processInspection);
                    }
                } else {
                    List<BizProcessInspecion> processInspection = bizProcessInspecionService.query().eq("id", consult.getProcessInspectionId()).list();
                    if (!processInspection.isEmpty()) {
                        //判断检查是否是外协检，如果是外协检需要判断是否有关联批次
                        List<BizProcessInspectionRelation> processInspectionRelationList = bizProcessInspectionRelationService.query().eq("process_inspection_id", consult.getProcessInspectionId()).list();
                        if (!processInspectionRelationList.isEmpty()) {
                            //主批关联的批次(不看主批，只看关联批次)
                            List<BizProcessInspectionRelationDetail> processInspectionRelationDetailList = bizProcessInspectionRelationDetailService.query()
                                    .eq("process_inspection_relation_id", processInspectionRelationList.get(0).getId()).eq("is_master", 0).list();
                            if (!processInspectionRelationDetailList.isEmpty()) {
                                //关联批次的所有检查id
                                List<Long> processInspecionIds = processInspectionRelationDetailList.stream().map(BizProcessInspectionRelationDetail::getProcessInspectionId).collect(Collectors.toList());
                                //关联批次存在额外的检查
                                if (!processInspecionIds.isEmpty()) {
                                    List<BizProcessInspecion> processInspectionList = bizProcessInspecionService.query().in("id", processInspecionIds).list();
                                    //改为合格
                                    processInspectionList.forEach(item -> {
                                        item.setStatus(1);
                                    });
                                    bizProcessInspecionService.saveOrUpdateBatch(processInspectionList);
                                }
                            }
                        }
                        //改为不合格
                        processInspection.forEach(item -> {
                            item.setStatus(1);
                            if (item.getType().equals("deliveryInspection")) {
                                item.setAdoptStatus(1);
                            }
                        });
                        bizProcessInspecionService.saveOrUpdateBatch(processInspection);
                    }

                }
            }
        }
        return success();
    }

    /**
     * 删除咨询
     */
    @PreAuthorize("@ss.hasPermi('business:consult:remove')")
    @Log(title = "删除咨询", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(iBizDayworkItemConsultService.removeBatchByIds(ids));
    }
}
