package cn.ezhizao.project.business.resourceGroup.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.equipment.domain.BizEquipmentDetail;
import cn.ezhizao.project.business.equipment.service.IBizEquipmentDetailService;
import cn.ezhizao.project.business.resourceGroup.domain.BizProductionResourceGroup;
import cn.ezhizao.project.business.resourceGroup.domain.BizProductionResourceGroupDetail;
import cn.ezhizao.project.business.resourceGroup.service.IBizProductionResourceGroupDetailService;
import cn.ezhizao.project.business.resourceGroup.service.IBizProductionResourceGroupService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 工段资源组Controller
 *
 * @author ezhizao
 * @date 2024-01-10
 */
@RestController
@RequestMapping("/business/resourceGroup")
public class BizProductionResourceGroupController extends BaseController {
    @Resource
    private IBizProductionResourceGroupService bizProductionResourceGroupService;

    @Resource
    private IBizProductionResourceGroupDetailService bizProductionResourceGroupDetailService;

    @Resource
    private IBizEquipmentDetailService bizEquipmentDetailService;

    /**
     * 查询工段资源组列表
     */
    @Log(title = "工段资源组查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizProductionResourceGroup bizProductionResourceGroup) throws NoSuchFieldException, IllegalAccessException {

        List<BizProductionResourceGroup> list = bizProductionResourceGroupService.getList(bizProductionResourceGroup);

        return getDataTable(list);
    }

    /**
     * 导出工段资源组列表
     */
    @Log(title = "工段资源组导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizProductionResourceGroup bizProductionResourceGroup) throws NoSuchFieldException, IllegalAccessException {
        List<BizProductionResourceGroup> list = bizProductionResourceGroupService.getList(bizProductionResourceGroup);
        ExcelUtil<BizProductionResourceGroup> util = new ExcelUtil<BizProductionResourceGroup>(BizProductionResourceGroup.class);
        util.exportExcel(response, list, "工段资源组数据");
    }

    /**
     * 获取工段资源组详细信息
     */
    @Log(title = "工段资源组查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BizProductionResourceGroup bizProductionResourceGroup = new BizProductionResourceGroup();
        bizProductionResourceGroup.setId(id);
        List<BizProductionResourceGroup> list = bizProductionResourceGroupService.getList(bizProductionResourceGroup);
        list.get(0).setGroupDetailList(list.get(0).getGroupDetailList().stream().filter(item -> item.getProtemDayworkId() == 0).collect(Collectors.toList()));

        return success(list.get(0));
    }

    /**
     * 新增工段资源组
     */
    @Log(title = "工段资源组新增", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public AjaxResult add(@RequestBody BizProductionResourceGroup bizProductionResourceGroup) throws NoSuchFieldException, IllegalAccessException {
        if (bizProductionResourceGroup.getId() == null) {
            List<BizProductionResourceGroup> groupList = bizProductionResourceGroupService.query().eq("dept_id", bizProductionResourceGroup.getDeptId()).eq("code", bizProductionResourceGroup.getCode()).list();
            if (groupList.size() > 0) {
                return error("资源组名称已存在");
            }
            bizProductionResourceGroupService.save(bizProductionResourceGroup);
        } else {
            List<BizProductionResourceGroup> groupList = bizProductionResourceGroupService.query().eq("dept_id", bizProductionResourceGroup.getDeptId()).eq("code", bizProductionResourceGroup.getCode()).list();
            if (groupList.size() > 1) {
                return error("资源组名称已存在");
            }
            bizProductionResourceGroupService.updateById(bizProductionResourceGroup);
        }
        String msg = "";
        bizProductionResourceGroup.getGroupDetailList().stream().forEach(item -> {
            item.setDeptId(bizProductionResourceGroup.getDeptId());
            item.setProductionResourceGroupId(bizProductionResourceGroup.getId());
        });
        //查询非当前资源组下是否该设备已经被绑定了
        List<Long> equipmentListIds = bizProductionResourceGroupDetailService.query().ne("production_resource_group_id", bizProductionResourceGroup.getId()).eq("common_type", "equipmentDetail").eq("deleted", 0).list().stream().map(BizProductionResourceGroupDetail::getCommonId).collect(Collectors.toList());
        for (BizProductionResourceGroupDetail item : bizProductionResourceGroup.getGroupDetailList().stream().filter(item -> "equipmentDetail".equals(item.getCommonType())).collect(Collectors.toList())
        ) {
                for (Long info : equipmentListIds) {
                    if (item.getCommonId().equals(info)) {
                    QueryWrapper<BizEquipmentDetail> wrapper = new QueryWrapper<>();
                    wrapper.eq("id", info);
                    wrapper.eq("is_virtual_equipment", 0);
                    if (bizEquipmentDetailService.list(wrapper).size() > 0) {
                        msg += item.getCommonCode() + ",";
                    }
                }
            }
        }
        if (!msg.equals("")) {
            throw new RuntimeException(msg + "设备已绑定到其他资源组;");
        }

        BizProductionResourceGroupDetail detail = new BizProductionResourceGroupDetail();
        detail.setProductionResourceGroupId(bizProductionResourceGroup.getId());
        detail.setSelStatus("过滤临时人员");
        List<BizProductionResourceGroupDetail> oldList = bizProductionResourceGroupDetailService.getList(detail);
//        List<BizProductionResourceGroupDetail> oldList = bizProductionResourceGroupDetailService.query().eq("production_resource_group_id", bizProductionResourceGroup.getId()).list();
        boolean batch = saveOrUpdateBatch(bizProductionResourceGroupDetailService, bizProductionResourceGroup.getGroupDetailList(), oldList);
        return toAjax(batch);
    }

    /**
     * 修改工段资源组
     */
    @Log(title = "工段资源组修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizProductionResourceGroup bizProductionResourceGroup) throws NoSuchFieldException, IllegalAccessException {
        return toAjax(bizProductionResourceGroupService.updateById(bizProductionResourceGroup));
    }

    /**
     * 删除工段资源组
     */
    @Log(title = "工段资源组删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long ids) {
        List<BizProductionResourceGroupDetail> list = bizProductionResourceGroupDetailService.query().eq("production_resource_group_id", ids).list();
        bizProductionResourceGroupDetailService.removeBatchByIds(list);
//        QueryWrapper<BizProductionResourceGroupDetail> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("production_resource_group_id",ids);
//        queryWrapper.eq("deleted",0);
//
//        if(bizProductionResourceGroupDetailService.list(queryWrapper).size()>0) {
//            return error("该资源组下已绑定明细，不能删除");
//        }
        return toAjax(bizProductionResourceGroupService.removeById(ids));
    }

}
