package com.fs.company.controller.company;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.fs.common.core.domain.R;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.param.CompanyUserDelayTimeParam;
import com.fs.company.service.ICompanyUserService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.voice.utils.StringUtil;
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.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.company.domain.CompanyUserDelayTime;
import com.fs.company.service.ICompanyUserDelayTimeService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

/**
 * 员工发送延时时间关联Controller
 *
 * @author fs
 * @date 2025-06-18
 */
@RestController
@RequestMapping("/company/sendDelayTime")
public class CompanyUserDelayTimeController extends BaseController
{
    @Autowired
    private ICompanyUserDelayTimeService companyUserDelayTimeService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICompanyUserService companyUserService;

    /**
     * 查询员工发送延时时间关联列表
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyUserDelayTime companyUserDelayTime)
    {
        startPage();
        List<CompanyUserDelayTime> list = companyUserDelayTimeService.selectCompanyUserDelayTimeList(companyUserDelayTime);
        return getDataTable(list);
    }

    /**
     * 导出员工发送延时时间关联列表
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:export')")
    @Log(title = "员工发送延时时间关联", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyUserDelayTime companyUserDelayTime)
    {
        List<CompanyUserDelayTime> list = companyUserDelayTimeService.selectCompanyUserDelayTimeList(companyUserDelayTime);
        ExcelUtil<CompanyUserDelayTime> util = new ExcelUtil<CompanyUserDelayTime>(CompanyUserDelayTime.class);
        return util.exportExcel(list, "员工发送延时时间关联数据");
    }

    /**
     * 获取员工发送延时时间关联详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(companyUserDelayTimeService.selectCompanyUserDelayTimeById(id));
    }

    /**
     * 批量绑定发送延时时间关联
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:batchadd')")
    @Log(title = "员工发送延时时间关联", businessType = BusinessType.INSERT)
    @PostMapping("/batchAdd")
    public R batchAdd(@RequestBody CompanyUserDelayTimeParam companyUserDelayTimeParam) {
        // 参数校验
        if (companyUserDelayTimeParam == null || StringUtils.isEmpty(companyUserDelayTimeParam.getId())) {
            return R.error("参数不能为空");
        }

        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null || loginUser.getCompany() == null) {
            return R.error("用户未登录或公司信息不存在");
        }

        // 处理用户ID集合
        Set<String> companyUserIds = Arrays.stream(companyUserDelayTimeParam.getId().split(","))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        if (companyUserIds.isEmpty()) {
            return R.error("用户ID不能为空");
        }

        // 批量处理延迟时间设置
        try {
            companyUserIds.forEach(userId -> {
                CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.valueOf(userId));
                if (companyUser == null) {
                    throw new RuntimeException("用户ID不存在: " + userId);
                }

                CompanyUserDelayTime delayTime = new CompanyUserDelayTime();
                delayTime.setCompanyId(loginUser.getCompany().getCompanyId());
                delayTime.setCompanyUserId(Long.valueOf(userId));
                delayTime.setNickName(companyUser.getNickName());
                delayTime.setRemark(companyUserDelayTimeParam.getRemark());
                delayTime.setCreateBy(loginUser.getUser().getNickName());
                delayTime.setSendDelayTime(Long.valueOf(companyUserDelayTimeParam.getSendDelayTime()));

                CompanyUserDelayTime companyUserDelayTime = companyUserDelayTimeService.selectCompanyUserDelayTimeByCompanyUser(loginUser.getCompany().getCompanyId(),Long.valueOf(userId));
                if (ObjectUtil.isEmpty(companyUserDelayTime)){
                    companyUserDelayTimeService.insertCompanyUserDelayTime(delayTime);
                }else {
                    delayTime.setId(companyUserDelayTime.getId());
                    companyUserDelayTimeService.updateCompanyUserDelayTime(delayTime);
                }
            });
            return R.ok();
        } catch (RuntimeException e) {
            e.fillInStackTrace();
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.fillInStackTrace();
            return R.error("批量设置延迟时间失败");
        }
    }


    /**
     * 新增员工发送延时时间关联
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:add')")
    @Log(title = "员工发送延时时间关联", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@RequestBody CompanyUserDelayTime companyUserDelayTime) {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        // 设置基本信息
        companyUserDelayTime.setCompanyId(companyId);
        companyUserDelayTime.setCreateBy(loginUser.getUser().getNickName());

        // 验证并设置用户信息
        Long companyUserId = companyUserDelayTime.getCompanyUserId();
        CompanyUser companyUser = companyUserService.selectCompanyUserById(companyUserId);
        if (companyUser == null) {
            throw new ServiceException("员工信息不存在");
        }
        companyUserDelayTime.setNickName(companyUser.getNickName());

        // 检查是否已存在延时时间记录
        CompanyUserDelayTime existingDelayTime = companyUserDelayTimeService
                .selectCompanyUserDelayTimeByCompanyUser(companyId, companyUser.getUserId());
        if (existingDelayTime != null) {
            throw new ServiceException("该员工已经绑定过延时时间信息");
        }

        // 插入新记录
        int result = companyUserDelayTimeService.insertCompanyUserDelayTime(companyUserDelayTime);
        return toAjax(result);
    }

    /**
     * 修改员工发送延时时间关联
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:edit')")
    @Log(title = "员工发送延时时间关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CompanyUserDelayTime companyUserDelayTime)
    {
        CompanyUser companyUser = companyUserService.selectCompanyUserById(companyUserDelayTime.getCompanyUserId());
        companyUserDelayTime.setNickName(companyUser.getNickName());
        return toAjax(companyUserDelayTimeService.updateCompanyUserDelayTime(companyUserDelayTime));
    }

    /**
     * 删除员工发送延时时间关联
     */
    @PreAuthorize("@ss.hasPermi('company:sendDelayTime:remove')")
    @Log(title = "员工发送延时时间关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(companyUserDelayTimeService.deleteCompanyUserDelayTimeByIds(ids));
    }
}
