package com.ximai.mes.md.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.annotation.Log;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.page.TableDataInfo;
import com.ximai.common.enums.BusinessType;
import com.ximai.common.utils.MessageUtils;
import com.ximai.common.utils.SecurityUtils;
import com.ximai.common.utils.data.ExceptionUtil;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.md.domain.MdWorkunit;
import com.ximai.mes.md.domain.MdWorkunitWorker;
import com.ximai.mes.md.mapper.MdWorkunitMapper;
import com.ximai.mes.md.mapper.MdWorkunitWorkerMapper;
import com.ximai.mes.md.service.IMdWorkunitService;
import com.ximai.mes.md.service.IMdWorkunitWorkerService;
import com.ximai.mes.md.vo.MdWorkunitVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 岗位资源Controller
 *
 * @author generator
 * @date 2024-07-17
 */
@RestController
@RequestMapping("/mes/md/workunitWorker")
public class MdWorkunitWorkerController extends BaseController {
    @Autowired
    private IMdWorkunitWorkerService mdWorkunitWorkerService;

    @Autowired
    private MdWorkunitWorkerMapper mdWorkunitWorkerMapper;

    @Resource
    private MdWorkunitMapper mdWorkunitMapper;
    @Autowired
    private IMdWorkunitService mdWorkunitService;

    /**
     * 查询岗位资源列表
     */
    @PreAuthorize("@ss.hasPermi('md:worker:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdWorkunitWorker mdWorkunitWorker) {
        startPage();
        List<MdWorkunitWorker> list = mdWorkunitWorkerService.selectMdWorkunitWorkerList(mdWorkunitWorker);
        return getDataTable(list);
    }



    /**
     * 查询岗位资源列表
     */
    @PreAuthorize("@ss.hasPermi('md:worker:list')")
    @GetMapping("/getMdWorkunitWorkerByUserName")
    public AjaxResult getMdWorkunitWorkerByUserName( MdWorkunitWorker mdWorkunitWorker) {
        MdWorkunitWorker list = mdWorkunitWorkerService.getMdWorkunitWorkerByUserName(mdWorkunitWorker);
        return  AjaxResult.success("查询成功",list);
    }




    /**
     * 查询工作单元列表
     */
    @ApiOperation(value = "分页查询工作单元")
    @PreAuthorize("@ss.hasPermi('md:workunit:list')")
    @GetMapping("/listByUser")
    public TableDataInfo list(MdWorkunit mdWorkunit) {
        startPage();
        Long userId = mdWorkunit.getUserId();
        if(userId==null){
            userId = SecurityUtils.getUserId();
        }
        QueryWrapper<MdWorkunit> query = new QueryWrapper<MdWorkunit>().eq("user_id", userId);
        query.eq(mdWorkunit.getWorkstationId()!=null,"ws.workstation_id",mdWorkunit.getWorkstationId());
        query.like(StringUtils.isNotNull(mdWorkunit.getWorkunitCode()),"t1.workunit_code",mdWorkunit.getWorkunitCode());
        query.like(StringUtils.isNotNull(mdWorkunit.getWorkunitName()),"t1.workunit_name",mdWorkunit.getWorkunitName());
        List<MdWorkunitVo> list = mdWorkunitService.selectMdWorkunitListByUser(query);
        return getDataTable(list);
    }


    /**
     * 获取岗位资源详细信息
     */
    @PreAuthorize("@ss.hasPermi('md:worker:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(mdWorkunitWorkerService.selectMdWorkunitWorkerById(id));
    }


    /**
     * 新增岗位资源
     */
    @PreAuthorize("@ss.hasPermi('md:worker:add')")
    @Log(title = "岗位资源", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<MdWorkunitWorker> mdWorkunitWorkerData) {
        StringBuilder stringBuilder = new StringBuilder();
        for (MdWorkunitWorker mdWorkunitWorker : mdWorkunitWorkerData){
            QueryWrapper<MdWorkunitWorker> proWorkorderQueryWrapper = new QueryWrapper<>();
            proWorkorderQueryWrapper.eq("t1.user_id", mdWorkunitWorker.getUserId());
            proWorkorderQueryWrapper.eq("t1.workunit_id", mdWorkunitWorker.getWorkunitId());
            List<MdWorkunitWorker> mdWorkunitWorkers = mdWorkunitWorkerMapper.selectListByQw(proWorkorderQueryWrapper);
            if(CollectionUtil.isNotEmpty(mdWorkunitWorkers)){
                stringBuilder.append(mdWorkunitWorker.getWorkunitName()+",");
                continue;
            }
            int rows = mdWorkunitWorkerService.insertObj(mdWorkunitWorker);
        }
        ExceptionUtil.checkTrueThrowException(StringUtils.isNotEmpty(stringBuilder), MessageUtils.message("md.workUnit.error.repeat.bind") + stringBuilder);
        return toAjax(mdWorkunitWorkerData.size());
    }

    /**
     * 修改岗位资源
     */
    @PreAuthorize("@ss.hasPermi('md:worker:edit')")
    @Log(title = "岗位资源", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdWorkunitWorker mdWorkunitWorker) {
        QueryWrapper<MdWorkunitWorker> workunitWorkerQueryWrapper = new QueryWrapper<>();
        workunitWorkerQueryWrapper.eq("t1.user_id", mdWorkunitWorker.getUserId());
        workunitWorkerQueryWrapper.eq("t1.workunit_id", mdWorkunitWorker.getWorkunitId());
        List<MdWorkunitWorker> mdWorkunitWorkers = mdWorkunitWorkerMapper.selectListByQw(workunitWorkerQueryWrapper);
        ExceptionUtil.checkTrueThrowException(CollectionUtil.isNotEmpty(mdWorkunitWorkers) && mdWorkunitWorkers.size() != 1,
                MessageUtils.message("md.workUnit.error.not.exist"));


        return toAjax(mdWorkunitWorkerService.updateObj(mdWorkunitWorker));
    }

    /**
     * 删除岗位资源
     */
    @PreAuthorize("@ss.hasPermi('md:worker:remove')")
    @Log(title = "岗位资源", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(mdWorkunitWorkerService.deleteMdWorkunitWorkerById(id));
    }
}
