package com.ruoyi.project.training.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.task.CompanyLevelTask;
import com.ruoyi.project.training.domain.TTrainingHisparticipants;
import com.ruoyi.project.training.domain.TTrainingParticipants;
import com.ruoyi.project.training.mapper.TTrainingCompanylevelMapper;
import com.ruoyi.project.training.mapper.TTrainingHisparticipantsMapper;
import com.ruoyi.project.training.mapper.TTrainingParticipantsMapper;
import com.ruoyi.project.training.service.ITTrainingHisparticipantsService;
import com.ruoyi.project.training.service.ITTrainingParticipantsService;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
import org.springframework.beans.BeanUtils;
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.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.training.domain.TTrainingCompanylevel;
import com.ruoyi.project.training.service.ITTrainingCompanylevelService;
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 javax.annotation.Resource;

/**
 * 公司级培训Controller
 *
 * @author ruoyi
 * @date 2021-05-28
 */
@RestController
@RequestMapping("/training/companylevel")
public class TTrainingCompanylevelController extends BaseController {
    @Autowired
    private ITTrainingCompanylevelService tTrainingCompanylevelService;
    @Resource
    private TTrainingCompanylevelMapper tTrainingCompanylevelMapper;
    @Autowired
    private ITTrainingParticipantsService tTrainingParticipantsService;
    @Autowired
    private ITTrainingHisparticipantsService tTrainingHisparticipantsService;
    @Resource
    private TTrainingParticipantsMapper tTrainingParticipantsMapper;
    @Resource
    private TTrainingHisparticipantsMapper tTrainingHisparticipantsMapper;

    /**
     * 查询公司级培训列表
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingCompanylevel tTrainingCompanylevel) {
        startPage();
        List<TTrainingCompanylevel> list = tTrainingCompanylevelService.selectTTrainingCompanylevelList(tTrainingCompanylevel);
        return getDataTable(list);
    }

    /**
     * 更新培训成绩
     */
    @GetMapping("/updateScore")
    public AjaxResult updateScore(TTrainingCompanylevel tTrainingCompanylevel) {
        List<TTrainingHisparticipants> hislist = tTrainingHisparticipantsMapper.selectTTrainingHisparticipantsListTask(new TTrainingHisparticipants());
        List<TTrainingCompanylevel> companylevels = tTrainingCompanylevelService.selectTTrainingCompanylevelList(new TTrainingCompanylevel());
        //线程池
        ExecutorService executor1 = Executors.newFixedThreadPool(20);
        final CountDownLatch latch1 = new CountDownLatch(hislist.size()); //相同线程数量的计数

        for (TTrainingHisparticipants hisparticipant : hislist) {
            executor1.execute(() -> {
                try {
                    if (hisparticipant.getCompanyId() != null) {
                        TTrainingParticipants t = new TTrainingParticipants();
                        t.setCompanyId(hisparticipant.getCompanyId());
                        t.setStaffId(hisparticipant.getStaffId());
                        t.setBudget(hisparticipant.getBudget());
                        t.setEndDate(hisparticipant.getEndDate());
                        t.setStartDate(hisparticipant.getStartDate());
                        t.setOperationScore(hisparticipant.getOperationScore());
                        t.setScore(hisparticipant.getScore());
                        t.setRemarks(hisparticipant.getRemarks());
                        t.setTrainingCost(hisparticipant.getTrainingCost());
                        t.setTrainingDuration(hisparticipant.getTrainingDuration());
                        t.setTrainingPlace(hisparticipant.getTrainingPlace());
                        t.setDelFlag(0l);
                        int i = 0;
//                        List<TTrainingCompanylevel> companylevelList = new ArrayList<>();
//                        BeanUtils.copyProperties(companylevels, companylevelList);
//                        for (TTrainingCompanylevel companylevel : companylevels) {
                            for (int j = 0; j < companylevels.size(); j++) {
                                TTrainingCompanylevel companylevel = companylevels.get(j);
                            if (companylevel.getId().equals(hisparticipant.getCompanyId())) {
                                if (companylevel.getFrequency() != null) {
                                    Long frequency = Long.parseLong(companylevel.getFrequency()) * 365 * 24 * 3600 * 1000;
                                    Long validPeriod = hisparticipant.getStartDate().getTime() + frequency;
                                    Long nowDate = new Date().getTime();
                                    if (validPeriod <= nowDate) {
                                        TTrainingParticipants delParticipants = new TTrainingParticipants();
                                        delParticipants.setCompanyId(hisparticipant.getCompanyId());
                                        delParticipants.setStaffId(hisparticipant.getStaffId());
                                        delParticipants.setDelFlag(2l);
                                        tTrainingParticipantsMapper.updateTTrainingParticipantsByStaffAndCom(delParticipants);
                                    } else {
                                        i = tTrainingParticipantsMapper.updateTTrainingParticipantsByStaffAndCom(t);
                                        if (i == 0) {
                                            tTrainingParticipantsMapper.insertTTrainingParticipants(t);
                                        }
                                    }
                                } else {
                                    i = tTrainingParticipantsMapper.updateTTrainingParticipantsByStaffAndCom(t);
                                    if (i == 0) {
                                        tTrainingParticipantsMapper.insertTTrainingParticipants(t);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.toString());
                } finally {
                    latch1.countDown(); //线程计数
                }
            });
        }
        try {
            latch1.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor1.shutdown();
        List<TTrainingCompanylevel> list1 = tTrainingCompanylevelService.selectTTrainingCompanylevelList(tTrainingCompanylevel);
        //线程池
        ExecutorService executor2 = Executors.newFixedThreadPool(20);
        final CountDownLatch latch2 = new CountDownLatch(list1.size()); //相同线程数量的计数
        for (TTrainingCompanylevel t : list1) {
            executor2.submit(() -> {
                try {
                    if (t.getStaffId() != null) {
                        String[] newStaffs = t.getStaffId().split(",");
                        for (String s : newStaffs) {
                            TTrainingHisparticipants th = new TTrainingHisparticipants();
                            th.setCompanyId(t.getId());
                            th.setStaffId(s);
                            List<TTrainingHisparticipants> hislist1 = tTrainingHisparticipantsMapper.selectTTrainingHisparticipantsListTask(th);
                            if (hislist1 == null) {
                                TTrainingParticipants tTrainingParticipants = new TTrainingParticipants();
                                tTrainingParticipants.setStaffId(s);
                                tTrainingParticipants.setCompanyId(tTrainingCompanylevel.getId());
                                tTrainingParticipantsService.insertTTrainingParticipants(tTrainingParticipants);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.toString());
                } finally {
                    latch2.countDown();
                }
            });
        }
        try {
            latch2.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor2.shutdown();
        // 去重
        tTrainingParticipantsMapper.duplicateParticipants();
        return AjaxResult.success("公司级培训已同步");
    }

    /**
     * 导出公司级培训列表
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:export')")
    @Log(title = "公司级培训", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingCompanylevel tTrainingCompanylevel) {
        List<TTrainingCompanylevel> list = tTrainingCompanylevelService.selectTTrainingCompanylevelList(tTrainingCompanylevel);
        ExcelUtil<TTrainingCompanylevel> util = new ExcelUtil<TTrainingCompanylevel>(TTrainingCompanylevel.class);
        return util.exportExcel(list, "companylevel");
    }

    /**
     * 获取公司级培训详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTrainingCompanylevelService.selectTTrainingCompanylevelById(id));
    }

    /**
     * 新增公司级培训
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:add')")
    @Log(title = "公司级培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingCompanylevel tTrainingCompanylevel) {
        return toAjax(tTrainingCompanylevelService.insertTTrainingCompanylevel(tTrainingCompanylevel));
    }

    /**
     * 修改公司级培训
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:edit')")
    @Log(title = "公司级培训", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingCompanylevel tTrainingCompanylevel) {
        TTrainingCompanylevel trainingCompanylevel = tTrainingCompanylevelService.selectTTrainingCompanylevelById(tTrainingCompanylevel.getId());
        if (StringUtils.isNotEmpty(tTrainingCompanylevel.getStaffId())) {
            String[] newStaffs = tTrainingCompanylevel.getStaffId().split(",");
            if (trainingCompanylevel.getStaffId() != null) {
                //如果曾经旧名单中选择过数据
                TTrainingParticipants participants = new TTrainingParticipants();
                participants.setCompanyId(trainingCompanylevel.getId());
                //删除原有关系
                tTrainingParticipantsMapper.deleteTParticipantsByCompanyId(trainingCompanylevel.getId());
                for (String n : newStaffs) {
                    participants.setStaffId(n);
                    List<TTrainingParticipants> participantsList = tTrainingParticipantsService.selectTTrainingParticipantsList(participants);
                    if (participantsList.size() == 0) {
                        TTrainingParticipants tTrainingParticipants = new TTrainingParticipants();
                        tTrainingParticipants.setStaffId(n);
                        tTrainingParticipants.setCompanyId(tTrainingCompanylevel.getId());
                        tTrainingParticipantsService.insertTTrainingParticipants(tTrainingParticipants);
                    }
                }
            } else {
                //该类公司级培训曾经没有填写过参会人员名单
                for (String s : newStaffs) {
                    TTrainingParticipants tTrainingParticipants = new TTrainingParticipants();
                    tTrainingParticipants.setStaffId(s);
                    tTrainingParticipants.setCompanyId(tTrainingCompanylevel.getId());
                    tTrainingParticipantsService.insertTTrainingParticipants(tTrainingParticipants);
                }
            }
        }
        return toAjax(tTrainingCompanylevelService.updateTTrainingCompanylevel(tTrainingCompanylevel));
    }

    /**
     * 重置公司级培训
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:remove')")
    @Log(title = "公司级培训", businessType = BusinessType.DELETE)
    @DeleteMapping("/resetAll")
    public AjaxResult resetAll() {
        return toAjax(tTrainingCompanylevelService.resetTTrainingCompanylevel());
    }

    /**
     * 删除公司级培训
     */
    @PreAuthorize("@ss.hasPermi('training:companylevel:remove')")
    @Log(title = "公司级培训", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTrainingCompanylevelService.deleteTTrainingCompanylevelByIds(ids));
    }


}
