package cn.ezhizao.project.business.controller;

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

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.BizPackageResourceGroupDetail;
import cn.ezhizao.project.business.service.IBizPackageResourceGroupDetailService;
import cn.ezhizao.project.system.domain.SysRole;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.domain.SysUserRole;
import cn.ezhizao.project.system.service.ISysRoleService;
import cn.ezhizao.project.system.service.ISysUserRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
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.BizPackageResourceGroup;
import cn.ezhizao.project.business.service.IBizPackageResourceGroupService;

/**
 * 包装线Controller
 *
 * @author ezhizao
 * @date 2024-09-03
 */
@RestController
@RequestMapping("/business/packageResourceGroup")
public class BizPackageResourceGroupController extends BaseController
{
    @Resource
    private IBizPackageResourceGroupService bizPackageResourceGroupService;
    @Resource
    private IBizPackageResourceGroupDetailService bizPackageResourceGroupDetailService;
    @Resource
    private ISysUserRoleService sysUserRoleService;
    @Resource
    private ISysRoleService sysRoleService;

    /**
     * 查询包装线列表
     */
//    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizPackageResourceGroup bizPackageResourceGroup) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizPackageResourceGroup);
//        startPage();
        List<BizPackageResourceGroup> list = bizPackageResourceGroupService.getList(bizPackageResourceGroup);
        return getDataTable(list);
    }

    /**
     * 导出包装线列表
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:export')")
    @Log(title = "包装线", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizPackageResourceGroup bizPackageResourceGroup) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizPackageResourceGroup);
        List<BizPackageResourceGroup> list = bizPackageResourceGroupService.getList(bizPackageResourceGroup);
        ExcelUtil<BizPackageResourceGroup> util = new ExcelUtil<BizPackageResourceGroup>(BizPackageResourceGroup.class);
        util.exportExcel(response, list, "包装线数据");
    }

    /**
     * 获取包装线详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizPackageResourceGroupService.getById(id));
    }

    /**
     * 新增包装线
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:add')")
    @Log(title = "包装线", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizPackageResourceGroup bizPackageResourceGroup) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizPackageResourceGroup);
        return toAjax(bizPackageResourceGroupService.save(bizPackageResourceGroup));
    }

    /**
     * 修改包装线
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:edit')")
    @Log(title = "包装线", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizPackageResourceGroup bizPackageResourceGroup) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizPackageResourceGroup);
        return toAjax(bizPackageResourceGroupService.updateById(bizPackageResourceGroup));
    }

    /**
     * 删除包装线
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:remove')")
    @Log(title = "包装线", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        //判断如果该包装线下有员工，则不能删除
        List<BizPackageResourceGroupDetail> list = bizPackageResourceGroupDetailService.query().in("package_resource_group_id", ids).list();
        if(list.size()>0) {
            return error("该包装线下有员工，不能删除！");

        }
        return toAjax(bizPackageResourceGroupService.removeBatchByIds(ids));
    }

    /**
     * 新增包装线
     */
    @PreAuthorize("@ss.hasAnyPermi('business:packageResourceGroup:add,business:packageResourceGroup:edit')")
    @PostMapping("/addDetails")
    @Log(title = "包装线明细新增", businessType = BusinessType.INSERT)
    public AjaxResult addDetails(@RequestBody BizPackageResourceGroup bizPackageResourceGroup) {
        // 判断是否存在其他包装线有该人员
        long count = bizPackageResourceGroupDetailService.query().in("user_id", bizPackageResourceGroup.getEmployees().stream().map(SysUser::getUserId).collect(Collectors.toList())).ne("package_resource_group_id", bizPackageResourceGroup.getId()).count();
        if (count > 0) {
            return error("该人员已存在于其他包装线中，请先删除");
        }
        // 判断是否有包装线权限
        bizPackageResourceGroup.getEmployees().forEach(l -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(l.getUserId());
            List<SysRole> roles = sysUserRoleService.selectRoleListByUserId(userRole);
            SysRole role = sysRoleService.getRoleByKey("certificate");
            if (roles.stream().noneMatch(t -> t.getRoleKey().equals("certificate"))) {
                // 添加权限
                SysUserRole newRole = new SysUserRole();
                newRole.setUserId(l.getUserId());
                newRole.setRoleId(role.getRoleId());
                sysUserRoleService.batchUserRole(Collections.singletonList(newRole));
            }
        });

        // 判断没有则添加
        // 判断已有，不管
        // 判断该人员是否已添加到该包装线假设没有可以新增
        List<BizPackageResourceGroupDetail> existsDetails = bizPackageResourceGroupDetailService.query().eq("package_resource_group_id", bizPackageResourceGroup.getId()).list();
        List<SysUser> employees = bizPackageResourceGroup.getEmployees().stream().filter(t -> existsDetails.stream().noneMatch(e -> e.getUserId().equals(t.getUserId()))).collect(Collectors.toList());
        List<BizPackageResourceGroupDetail> newDetails = new ArrayList<>();
        employees.forEach(v -> {
            BizPackageResourceGroupDetail detail = new BizPackageResourceGroupDetail();
            detail.setPackageResourceGroupId(bizPackageResourceGroup.getId());
            detail.setNickName(v.getNickName());
            detail.setUserId(v.getUserId());
            detail.setUserName(v.getUserName());
            detail.setTenantId(getLoginUser().getTenantId());
            newDetails.add(detail);
        });
        return newDetails.isEmpty() || bizPackageResourceGroupDetailService.saveBatch(newDetails) ? success() : error("保存失败");
    }


    /**
     * 查询包装线明细列表
     */
    @PreAuthorize("@ss.hasPermi('business:packageResourceGroup:list')")
    @GetMapping("/listDetails")
    public TableDataInfo listDetails(BizPackageResourceGroupDetail bizPackageResourceGroupDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizPackageResourceGroupDetail);
        startPage();
        List<BizPackageResourceGroupDetail> list = bizPackageResourceGroupDetailService.getList(bizPackageResourceGroupDetail);
        return getDataTable(list);
    }
}
