package com.ruoyi.web.controller.invest;

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

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.FileType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.sms.SmsSenderUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.invest.domain.TProjectCirculation;
import com.ruoyi.invest.domain.TProjectMeeting;
import com.ruoyi.invest.service.ITProjectCirculationService;
import com.ruoyi.invest.service.ITProjectMeetingService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tool.domain.TUnifyFile;
import com.ruoyi.tool.service.ITUnifyFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 会议记录Controller
 * 
 * @author ruoyi
 * @date 2024-02-22
 */
@Api(tags = "会议记录")
@RestController
@RequestMapping("/invest/meeting")
public class TProjectMeetingController extends BaseController
{
    @Autowired
    private ITProjectMeetingService tProjectMeetingService;

    @Autowired
    private ITProjectCirculationService tProjectCirculationService;

    @Autowired
    private ITUnifyFileService tUnifyFileService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询会议记录列表
     */
    @ApiOperation("查询会议记录列表")
    @PreAuthorize("@ss.hasPermi('invest:meeting:list')")
    @GetMapping("/list")
    public TableDataInfo list(TProjectMeeting tProjectMeeting)
    {
        startPage();
        tProjectMeeting.setParticipants(getNickName());
        List<TProjectMeeting> list = tProjectMeetingService.selectTProjectMeetingList(tProjectMeeting);
        return getDataTable(list);
    }

    /**
     * 导出会议记录列表
     */
    @ApiOperation("导出会议记录列表")
    @PreAuthorize("@ss.hasPermi('invest:meeting:export')")
    @Log(title = "会议记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TProjectMeeting tProjectMeeting)
    {
        List<TProjectMeeting> list = tProjectMeetingService.selectTProjectMeetingList(tProjectMeeting)
                .stream().map(n -> {
                    n.setProjectPoolId(n.gettProjectPool().getProjectName());
                    n.setMeetingType(dictDataService.selectDictLabel("MEETING_TYPE",n.getMeetingType()));
                    return n;
                })
                .collect(Collectors.toList());
        ExcelUtil<TProjectMeeting> util = new ExcelUtil<TProjectMeeting>(TProjectMeeting.class);
        util.exportExcel(response, list, "会议记录数据");
    }

    /**
     * 获取会议记录详细信息
     */
    @ApiOperation("获取会议记录详细信息")
    @PreAuthorize("@ss.hasPermi('invest:meeting:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(tProjectMeetingService.selectTProjectMeetingById(id));
    }

    /**
     * 新增会议记录
     */
    @ApiOperation("新增会议记录")
    @PreAuthorize("@ss.hasPermi('invest:meeting:add')")
    @Log(title = "会议记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TProjectMeeting tProjectMeeting)
    {
        tProjectMeeting.setId(IdUtils.fastSimpleUUID());
        tProjectMeeting.setCreateBy(getNickName());

        if(tProjectMeeting.getMeetingType().equals("LX")||tProjectMeeting.getMeetingType().equals("TJ")){
            int number = tProjectMeetingService.selectTProjectMeetingCode(DateUtils.lastTwoDigits()+"-");
            tProjectMeeting.setMeetingCode(tProjectMeeting.getProjectGroup()+"-"+ DateUtils.lastTwoDigits() +"-"+tProjectMeeting.getMeetingType()+"-"+ String.format("%03d",number+1));
        }else{
            int number = tProjectMeetingService.selectTProjectMeetingCode(DateUtils.dateTimeNow("YYYY"));
            tProjectMeeting.setMeetingCode(DateUtils.dateNow()+ String.format("%03d",number+1));
        }
        // todo 保存附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectMeeting.getListFile(),
                tProjectMeeting.getProjectPoolId(),
                tProjectMeeting.getId(),//会议ID
                String.valueOf(FileType.MEETING.ordinal()),//文件类型:会议
                getNickName());

        // todo 增加会议创建记录
        tProjectCirculationService.insertTProjectCirculation(tProjectMeeting.getProjectPoolId(),tProjectMeeting.getMeetingTheme()+"(会议)",getNickName());

        // todo 发送短信-参与人-发起人
        if(tProjectMeeting.getMeetingType().equals("LX") || tProjectMeeting.getMeetingType().equals("TJ")){
            // todo 参与人
            if(StringUtils.isNotEmpty(tProjectMeeting.getParticipantsId())){
                StringUtils.str2List(tProjectMeeting.getParticipantsId(),",",true,true).stream().forEach(str -> {
                    SysUser user = sysUserService.selectUserById(Long.valueOf(str));
                    String contents = "您好，" + user.getNickName() + "，兹定于 " +
                            DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getStartTime()) + "至" + DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getEndTime()) +
                            "在" + tProjectMeeting.getPlace() + "召开" + tProjectMeeting.getMeetingTheme() + "会议,请提前做好准备按时参加。";
                    try {
                        SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                    } catch (IOException e) {
                       logger.error("短信发送失败"+e.getMessage());
                    }
                });
            }

            // todo 发起人
            if(StringUtils.isNotEmpty(tProjectMeeting.getPromoterId())){
                SysUser user = sysUserService.selectUserById(Long.valueOf(tProjectMeeting.getPromoterId()));
                String contents = "您好，" + user.getNickName() + "，兹定于 " +
                        DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getStartTime()) + "至" + DateUtils.parseDateToStr("yyyy/MM/dd HH:mm",tProjectMeeting.getEndTime()) +
                        "在" + tProjectMeeting.getPlace() + "召开" + tProjectMeeting.getMeetingTheme() + "会议,请提前做好准备按时参加。";
                try {
                    SmsSenderUtils.sendSms(user.getPhonenumber(),contents);
                } catch (IOException e) {
                    logger.error("短信发送失败"+e.getMessage());
                }
            }
        }

        return toAjax(tProjectMeetingService.insertTProjectMeeting(tProjectMeeting));
    }

    /**
     * 修改会议记录
     */
    @ApiOperation("修改会议记录")
    @PreAuthorize("@ss.hasPermi('invest:meeting:edit')")
    @Log(title = "会议记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TProjectMeeting tProjectMeeting)
    {
        // todo 保存附件信息
        tUnifyFileService.insertTUnifyFileList(tProjectMeeting.getListFile(),
                tProjectMeeting.getProjectPoolId(),
                tProjectMeeting.getId(),//会议ID
                String.valueOf(FileType.MEETING.ordinal()),//文件类型:会议
                getNickName());

        return toAjax(tProjectMeetingService.updateTProjectMeeting(tProjectMeeting));
    }

    /**
     * 删除会议记录
     */
    @ApiOperation("删除会议记录")
    @PreAuthorize("@ss.hasPermi('invest:meeting:remove')")
    @Log(title = "会议记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        //删除附件
        tUnifyFileService.updateTUnifyFileBusinessIds(ids);
        return toAjax(tProjectMeetingService.updateTProjectMeetingByIds(ids));
    }

    /**
     * 根据项目ID获取会议记录
     */
    @ApiOperation("根据项目ID获取会议记录")
    @PreAuthorize("@ss.hasPermi('invest:meeting:query')")
    @GetMapping(value = "/listProjectPoolId")
    public AjaxResult listProjectPoolId(String projectPoolId)
    {
        return success(tProjectMeetingService.listProjectPoolId(projectPoolId));
    }

}
