package com.staffing.web.controller.custom;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.staffing.common.core.domain.entity.SysUser;
import com.staffing.common.core.redis.RedisCache;
import com.staffing.common.utils.SecurityUtils;
import com.staffing.custom.domain.StTask;
import com.staffing.custom.domain.StTaskSign;
import com.staffing.custom.mapper.StTaskMapper;
import com.staffing.custom.service.IStTaskService;
import com.staffing.custom.service.IStTaskSignService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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 com.staffing.common.annotation.Log;
import com.staffing.common.core.controller.BaseController;
import com.staffing.common.core.domain.AjaxResult;
import com.staffing.common.enums.BusinessType;
import com.staffing.custom.domain.StEmployee;
import com.staffing.custom.service.IStEmployeeService;
import com.staffing.common.utils.poi.ExcelUtil;
import com.staffing.common.core.page.TableDataInfo;

import static com.staffing.common.constant.Constants.DELETED_USER_KEY;
import static com.staffing.common.utils.PageUtils.startPage;

/**
 * 员工Controller
 * 
 * @author staffing
 * @date 2024-08-27
 */
@RestController
@RequestMapping("/employee/employee")
public class StEmployeeController extends BaseController
{
    @Autowired
    private IStEmployeeService stEmployeeService;
    @Autowired
    private IStTaskSignService taskSignService;
    @Autowired
    private StTaskMapper stTaskMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询员工列表
     */
    @PreAuthorize("@ss.hasPermi('employee:list')")
    @GetMapping("/list")
    public TableDataInfo list(StEmployee stEmployee)
    {
        startPage();
        List<StEmployee> list = stEmployeeService.selectStEmployeeList(stEmployee);
        return getDataTable(list);
    }

    /**
     * 导出员工列表
     */
    @PreAuthorize("@ss.hasPermi('employee:export')")
    @Log(title = "员工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StEmployee stEmployee)
    {
        List<StEmployee> list = stEmployeeService.selectStEmployeeList(stEmployee);
        ExcelUtil<StEmployee> util = new ExcelUtil<StEmployee>(StEmployee.class);
        util.exportExcel(response, list, "员工数据");
    }

    /**
     * 获取员工详细信息
     */
    @PreAuthorize("@ss.hasPermi('employee:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(stEmployeeService.selectStEmployeeById(id));
    }

    /**
     * 新增员工
     */
    @PreAuthorize("@ss.hasPermi('employee:add')")
    @Log(title = "员工", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StEmployee stEmployee)
    {
        StEmployee stEmployee1 = stEmployeeService.selectStEmployeeByPhone(stEmployee.getPhone());
        if (stEmployee1 != null){
            return error("手机号已存在");
        }
        stEmployee.setUpdateTime(new Date());
        return toAjax(stEmployeeService.insertStEmployee(stEmployee));
    }

    /**
     * 修改员工
     */
    @PreAuthorize("@ss.hasPermi('employee:edit')")
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StEmployee stEmployee)
    {
        stEmployee.setUpdateTime(new Date());
        stEmployee.setPhone(null);//不允许修改手机号
        return toAjax(stEmployeeService.updateStEmployeeOrNull(stEmployee));
    }

    /**
     * 删除员工
     */
    @PreAuthorize("@ss.hasPermi('employee:remove')")
    @Log(title = "员工", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        //有报名任务，则不能删除了
        for (Long id : ids) {
            StTaskSign stTaskSign = new StTaskSign();
            stTaskSign.setEmployeeId(id);
            List<StTaskSign> stTaskSigns = taskSignService.selectStTaskSignList(stTaskSign);

            if (!stTaskSigns.isEmpty()){
                StTask stTask = new StTask();
                List<Long> taskIds = stTaskSigns.stream().map(stTask1 -> stTask1.getTaskId()).collect(Collectors.toList());
                stTask.setTaskIds(taskIds);
                List<StTask> stTasks = stTaskMapper.selectStTaskList(stTask);

                if (!stTasks.isEmpty()){
                    return error("该员工已报名了任务["+ stTasks.get(0).getTaskName() +"], 不能删除");
                }
            }
        }
        int i = stEmployeeService.deleteStEmployeeByIds(ids);
        if(i > 0){
            for (Long id : ids) {
                //清除缓存，用户踢下线
                redisCache.setCacheMapValue(DELETED_USER_KEY, id+"", true);
            }
        }
        return toAjax(i);
    }
}
