package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.SecurityUtils;
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.domain.BizCheckCategory;
import cn.ezhizao.project.business.domain.BizInspectionStandardsCheck;
import cn.ezhizao.project.business.domain.BizProcessInspectionDetail;
import cn.ezhizao.project.business.service.IBizCheckCategoryService;
import cn.ezhizao.project.business.service.IBizInspectionStandardsCheckService;
import cn.ezhizao.project.business.service.IBizProcessInspectionDetailService;
import cn.ezhizao.project.system.domain.SysRole;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.ezhizao.project.business.domain.BizInspectionStandards;
import cn.ezhizao.project.business.service.IBizInspectionStandardsService;

/**
 * 检查标准Controller
 *
 * @author ezhizao
 * @date 2024-08-05
 */
@RestController
@RequestMapping("/business/standards")
public class BizInspectionStandardsController extends BaseController
{
    @Resource
    private IBizInspectionStandardsService bizInspectionStandardsService;

    @Resource
    private IBizInspectionStandardsCheckService bizInspectionStandardsCheckService;

    @Resource
    private IBizCheckCategoryService bizCheckCategoryService;

    @Resource
    private IBizProcessInspectionDetailService bizProcessInspectionDetailService;

    /**
     * 查询检查标准列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizInspectionStandards bizInspectionStandards) throws NoSuchFieldException, IllegalAccessException
    {

        startPage();
        List<BizInspectionStandards> list = bizInspectionStandardsService.getList(bizInspectionStandards);
        for (BizInspectionStandards item:list){
            for (BizInspectionStandardsCheck check : item.getCheckStandardList()){
                if (check.getInspectionCode().equals("factoryInspection")){
                    item.setFactoryInspection(true);
                }
                if (check.getInspectionCode().equals("deliveryInspection")){
                    item.setDeliveryInspection(true);
                }
                if (check.getInspectionCode().equals("patrolInspection")){
                    item.setPatrolInspection(true);
                }
                if (check.getInspectionCode().equals("instrumentRoomInspection")){
                    item.setInstrumentRoomInspection(true);
                }
                if (check.getInspectionCode().equals("firstArticleInspection")){
                    item.setFirstArticleInspection(true);
                }
                if (check.getInspectionCode().equals("outsourcedInspector")){
                    item.setOutsourcedInspector(true);
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出检查标准列表
     */
    @Log(title = "检查标准", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizInspectionStandards bizInspectionStandards) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizInspectionStandards);
        List<BizInspectionStandards> list = bizInspectionStandardsService.getList(bizInspectionStandards);
        ExcelUtil<BizInspectionStandards> util = new ExcelUtil<BizInspectionStandards>(BizInspectionStandards.class);
        util.exportExcel(response, list, "检查标准数据");
    }

    /**
     * 获取检查标准详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizInspectionStandardsService.getById(id));
    }

    public void saveCheck(String code, BizInspectionStandards bizInspectionStandards){
        if (bizInspectionStandards.getId() !=null){
            //这里的删除是为了不同权限操作时只保留一个
            List<BizInspectionStandardsCheck> standardsId = bizInspectionStandardsCheckService.query().eq("inspection_code", code).eq("standards_id", bizInspectionStandards.getId()).list();
            List<Long>ids = new ArrayList<>();
            for(BizInspectionStandardsCheck item:standardsId){
                ids.add(item.getId());
            }
            bizInspectionStandardsCheckService.removeBatchByIds(ids);
        }
        List<BizCheckCategory> list = bizCheckCategoryService.query().eq("code", code).list();
        BizInspectionStandardsCheck item = new BizInspectionStandardsCheck();
        item.setStandardsId(bizInspectionStandards.getId());
        item.setProcessCode(bizInspectionStandards.getProcessCode());
        item.setProductId(bizInspectionStandards.getProductId());
        item.setProductVersion(bizInspectionStandards.getProductVersion());
        item.setInstrument(bizInspectionStandards.getInstrument());
        item.setProcessId(bizInspectionStandards.getProcessId());
        item.setStandard(bizInspectionStandards.getStandard());
        item.setInspectionId(list.get(0).getId());
        item.setInspectionCode(list.get(0).getCode());
        item.setInspectionName(list.get(0).getName());
        bizInspectionStandardsCheckService.save(item);
    }
    public void removeCheck(String code , BizInspectionStandards bizInspectionStandards){
        List<BizInspectionStandardsCheck> standardsId = bizInspectionStandardsCheckService.query().eq("inspection_code", code).eq("standards_id", bizInspectionStandards.getId()).list();
        if (!standardsId.isEmpty()){
            List<Long>ids = new ArrayList<>();
            for(BizInspectionStandardsCheck item:standardsId){
                ids.add(item.getId());
            }
            bizInspectionStandardsCheckService.removeBatchByIds(ids);
        }
    }
    /**
     * 新增检查标准
     */
    @Log(title = "检查标准", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody BizInspectionStandards bizInspectionStandards) throws NoSuchFieldException, IllegalAccessException
    {
        bizInspectionStandardsService.saveOrUpdate(bizInspectionStandards);

        //判断根据当前人员的权限所能操作的列
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //上下其实都一样，就是过滤掉admin
//        if (userId == 1L){
            if ( bizInspectionStandards.getFactoryInspection() != null && bizInspectionStandards.getFactoryInspection()){
                saveCheck("factoryInspection",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("factoryInspection",bizInspectionStandards);
            }
            if (  bizInspectionStandards.getDeliveryInspection() != null && bizInspectionStandards.getDeliveryInspection()){
                saveCheck("deliveryInspection",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("deliveryInspection",bizInspectionStandards);
            }
            if (bizInspectionStandards.getPatrolInspection() != null && bizInspectionStandards.getPatrolInspection()){
                saveCheck("patrolInspection",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("patrolInspection",bizInspectionStandards);
            }
            if (  bizInspectionStandards.getInstrumentRoomInspection() != null && bizInspectionStandards.getInstrumentRoomInspection()){
                saveCheck("instrumentRoomInspection",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("instrumentRoomInspection",bizInspectionStandards);
            }
            if ( bizInspectionStandards.getFirstArticleInspection() != null && bizInspectionStandards.getFirstArticleInspection()){
                saveCheck("firstArticleInspection",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("firstArticleInspection",bizInspectionStandards);
            }
            if (  bizInspectionStandards.getOutsourcedInspector() != null && bizInspectionStandards.getOutsourcedInspector()){
                saveCheck("outsourcedInspector",bizInspectionStandards);
            }else {
                //更新将取消的删除
                removeCheck("outsourcedInspector",bizInspectionStandards);
            }
//        }else {
//            for(SysRole item:roles){
//                if (item.getRoleKey().equals("factoryInspector")){
//                    if (bizInspectionStandards.getFactoryInspection() != null && bizInspectionStandards.getFactoryInspection()){
//                        saveCheck("factoryInspection",bizInspectionStandards);
//                    }else {
//                        //更新将取消的删除
//                        removeCheck("factoryInspection",bizInspectionStandards);
//                    }
//                }
//                if(item.getRoleKey().equals("deliveryInspection")){
//                    if ( bizInspectionStandards.getDeliveryInspection() != null && bizInspectionStandards.getDeliveryInspection()){
//                        saveCheck("deliveryInspection",bizInspectionStandards);
//                    }else {
//                        //更新将取消的删除
//                        removeCheck("deliveryInspection",bizInspectionStandards);
//                    }
//                }
//
//                if(item.getRoleKey().equals("patrolInspection")){
//                    if ( bizInspectionStandards.getPatrolInspection() != null && bizInspectionStandards.getPatrolInspection()){
//                        saveCheck("patrolInspection",bizInspectionStandards);
//                    }else {
//                        //更新将取消的删除
//                        removeCheck("patrolInspection",bizInspectionStandards);
//                    }
//                }
//                if(item.getRoleKey().equals("instrumentRoomInspection")){
//                    if ( bizInspectionStandards.getInstrumentRoomInspection() != null && bizInspectionStandards.getInstrumentRoomInspection()){
//                        saveCheck("instrumentRoomInspection",bizInspectionStandards);
//                    }else {
//                        //更新将取消的删除
//                        removeCheck("instrumentRoomInspection",bizInspectionStandards);
//                    }
//                }
//               if(item.getRoleKey().equals("firstArticleInspection")){
//                   if ( bizInspectionStandards.getFirstArticleInspection() != null && bizInspectionStandards.getFirstArticleInspection()){
//                       saveCheck("firstArticleInspection",bizInspectionStandards);
//                   }else {
//                       //更新将取消的删除
//                       removeCheck("firstArticleInspection",bizInspectionStandards);
//                   }
//               }
//               if(item.getRoleKey().equals("outsourcedInspector")){
//                   if ( bizInspectionStandards.getOutsourcedInspector() != null && bizInspectionStandards.getOutsourcedInspector()){
//                       saveCheck("outsourcedInspector",bizInspectionStandards);
//                   }else {
//                       //更新将取消的删除
//                       removeCheck("outsourcedInspector",bizInspectionStandards);
//                   }
//               }
//
//            }
//        }


        return success();
    }

    /**
     * 修改检查标准
     */
    @Log(title = "检查标准", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizInspectionStandards bizInspectionStandards) throws NoSuchFieldException, IllegalAccessException
    {
        return toAjax(bizInspectionStandardsService.updateById(bizInspectionStandards));
    }

    /**
     * 删除检查标准
     */
    @Log(title = "检查标准", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        List<BizProcessInspectionDetail> inspecionStandardsId = bizProcessInspectionDetailService.query().in("inspection_standards_id", ids).list();
        if (!inspecionStandardsId.isEmpty()){
            return error("当前检查标准已被使用,不能删除");
        }else {
            return toAjax(bizInspectionStandardsService.removeBatchByIds(ids));
        }

    }
}
