package com.ruoyi.project.training.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.training.bccnew.domain.TTsFirstplanTmpl;
import com.ruoyi.project.training.domain.TTrainingDevice;
import com.ruoyi.project.training.domain.TTrainingbccDevice;
import com.ruoyi.project.training.mapper.TTrainingbccDeviceMapper;
import com.ruoyi.project.training.mapper.TTrainingbccMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.training.domain.TTrainingbcc;
import com.ruoyi.project.training.service.ITTrainingbccService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 装置培训跟踪bController
 *
 * @author ssy
 * @date 2024-06-19
 */
@RestController
@RequestMapping("/training/trainingbcc")
public class TTrainingbccController extends BaseController
{
    @Autowired
    private ITTrainingbccService tTrainingbccService;
    @Resource
    private TTrainingbccDeviceMapper tTrainingbccDeviceMapper;
    @Resource
    private TTrainingbccMapper tTrainingbccMapper;
    @Autowired
    private ITStaffmgrService tStaffmgrService;
    /**
     * 查询装置培训跟踪b列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingbcc tTrainingbcc)
    {
        startPage();
        List<TTrainingbcc> list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc);
        for (TTrainingbcc t: list
             ) {
            TTrainingbccDevice device = new TTrainingbccDevice();
            device.setRegularId(t.getId());
            int all = tTrainingbccDeviceMapper.countTraining(device);

            device.setExamState(1l);
            int finish = tTrainingbccDeviceMapper.countTraining(device);
            t.setHaveTraining(finish);
            t.setMustTraining(all);
            if (all != 0) {
                String per = String.valueOf(finish* 100 / all);
                t.setTrainingPercent(per);
            }else {
                t.setTrainingPercent("0");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出装置培训跟踪b列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:export')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingbcc tTrainingbcc)
    {
        List<TTrainingbcc> list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc);
        ExcelUtil<TTrainingbcc> util = new ExcelUtil<TTrainingbcc>(TTrainingbcc.class);
        return util.exportExcel(list, "trainingbcc");
    }

    /**
     * 获取装置培训跟踪b详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTrainingbccService.selectTTrainingbccById(id));
    }

    /**
     * 获取装置培训跟踪b详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')")
    @GetMapping(value = "/staffIds/{id}")
    public AjaxResult getStaffIds(@PathVariable("id") Long id)
    {
        TTrainingbcc tTrainingbcc = tTrainingbccService.selectTTrainingbccById(id);
        TTrainingbccDevice param = new TTrainingbccDevice();
        param.setRegularId(id);
        List<TTrainingbccDevice> list = tTrainingbccDeviceMapper.selectTTrainingbccDeviceList(param);
        String staffIds = "";
        for (TTrainingbccDevice t : list
             ) {
            staffIds = staffIds + "," + t.getStaffId();
        }
        tTrainingbcc.setStaffIds(staffIds);
        return AjaxResult.success(tTrainingbcc);
    }


    /**
     * 新增装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:add')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingbcc tTrainingbcc)
    {
        tTrainingbccService.insertTTrainingbcc(tTrainingbcc);
        //培训岗位人员
        if (tTrainingbcc.getPosition() != null) {
            TStaffmgr s = new TStaffmgr();
            s.setActualposts(tTrainingbcc.getPosition());
            List<TStaffmgr> trainingStaff = tStaffmgrService.selectAllTStaffmgrList(s);
            try {
                //判断离职
                if (!org.apache.commons.lang.StringUtils.isEmpty(tTrainingbcc.getYears())) {
                    Iterator<TStaffmgr> iterator = trainingStaff.iterator();
                    while (iterator.hasNext()) {
                        TStaffmgr t = iterator.next();
                        if (t.getLeftDate() != null && t.getDelFlag() == 9) {
                            if (t.getLeftDate().getTime() - tTrainingbcc.getStartDate().getTime() < 0l) {
                                logger.debug(t.getName() + "离职时间小于培训时间");
                                iterator.remove();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.toString());
            }
            for (TStaffmgr staff : trainingStaff) {
                TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                tTrainingDevice.setStaffId(staff.getStaffid());
                tTrainingDevice.setRegularId(tTrainingbcc.getId());
                tTrainingDevice.setStartDate(tTrainingbcc.getCourseStartdate());
                tTrainingDevice.setSupplementary("0");
                tTrainingbccDeviceMapper.insertTTrainingbccDevice(tTrainingDevice);
            }
        }
        return toAjax(1);
    }

    /**
     * 修改装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingbcc tTrainingbcc)
    {
        return toAjax(tTrainingbccService.updateTTrainingbcc(tTrainingbcc));
    }

    /**
     * 修改装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateStaffIds")
    public AjaxResult updateStaffIds(@RequestBody TTrainingbcc tTrainingbcc)
    {
        return toAjax(tTrainingbccService.updateStaffIds(tTrainingbcc));
    }


    /**
     * 删除装置培训跟踪b
     */
    @PreAuthorize("@ss.hasPermi('training:trainingbcc:remove')")
    @Log(title = "装置培训跟踪b", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id: ids
             ) {
            tTrainingbccDeviceMapper.deleteTTrainingbccDeviceByTrainingbcc(ids);
        }

        return toAjax(tTrainingbccService.deleteTTrainingbccByIds(ids));
    }

    @Log(title = "附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile/{id}")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @PathVariable Long id) throws IOException {
        if (!file.isEmpty()) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取年份
            int year = currentDate.getYear();
            // 获取月份
            int month = currentDate.getMonthValue();
            String dir = "/elearn/" + year ;
            String url = FileUploadUtils.upload(RuoYiConfig.getFilePath(dir), file);
            TTrainingbcc entity = tTrainingbccService.selectTTrainingbccById(id);
            entity.setFileUrl(url);
            entity.setFileName(file.getOriginalFilename());
            tTrainingbccService.updateTTrainingbcc(entity);
            return AjaxResult.success(id);
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }
}
