package com.ruoyi.project.ehs.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpringContextUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.common.domain.DataEntity;
import com.ruoyi.project.ehs.domain.TJobticket;
import com.ruoyi.project.ehs.mapper.TJobticketMapper;
import com.ruoyi.project.ehs.service.ITJobticketService;
import com.ruoyi.project.invoice.domain.TInvoiceWorkcontent;
import com.ruoyi.project.invoice.mapper.TInvoiceWorkcontentMapper;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 工作票Controller
 *
 * @author ruoyi
 * @date 2020-12-01
 */
@RestController
@RequestMapping("/ehs/jobticket")
public class TJobticketController extends BaseController {
    @Autowired
    private ITJobticketService tJobticketService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Resource
    private TJobticketMapper tJobticketMapper;

    @Resource
    private TInvoiceWorkcontentMapper invoiceWorkcontentMapper;

    /**
     * 查询工作票列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:list')")
    @GetMapping("/list")
    public TableDataInfo list(TJobticket tJobticket) {
        startPage();
        if (tJobticket.getTableType() == 1) {
            List<TJobticket> list = tJobticketService.selectTJobticketList(tJobticket);
            //查询续票
            if (list.size() > 0) {
                //线程池
                ExecutorService executorService = Executors.newFixedThreadPool(20);
                final CountDownLatch latch = new CountDownLatch(list.size()); //相同线程数量的计数
                for (TJobticket t : list
                ) {
                    executorService.submit(() -> {
                        try {
                            //续票列表 -- 业务模块
                            if ("10".equals(t.getXpxp())) {
                                List<TJobticket> cList = tJobticketMapper.selectTJobticketChildren(t);
                                t.setChildren(cList);
                            }
                        } catch (Exception e) {
                            logger.error("e:", e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });
                }
                try {
                    latch.await(); //线程计数完毕后继续执行
                } catch (InterruptedException e) {
                    logger.error("e" ,e);
                }
                executorService.shutdown();
            }
            return getDataTable(list);
        } else {
            List<TJobticket> list = tJobticketService.selectTJobticketList(tJobticket);
            return getDataTable(list);
        }
    }

    //情况统计
    @GetMapping("/fireData")
    public List<DataEntity> fireData(Map param) {
        param.put("params", new HashMap<>());
        List<DataEntity> list = tJobticketMapper.selectFireData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("HPJB");
        for (DataEntity d : list
        ) {
            for (SysDictData s : dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //情况统计
    @GetMapping("/statusData")
    public List<DataEntity> statusData(Map param) {
        param.put("params", new HashMap<>());
        List<DataEntity> list = tJobticketMapper.selectStatusData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("ZYPZT");
        for (DataEntity d : list
        ) {
            for (SysDictData s : dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    /**
     * 导出工作票列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:export')")
    @Log(title = "工作票", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TJobticket tJobticket) {
        List<TJobticket> list = tJobticketService.selectTJobticketList(tJobticket);
        List<TJobticket> exportList = new ArrayList<>();
        //查询续票
        for (TJobticket t : list
        ) {
            exportList.add(t);
            List<TJobticket> cList = tJobticketMapper.selectTJobticketChildren(t);
            if (cList.size() > 0) {
                exportList.addAll(cList);
            }
        }
        ExcelUtil<TJobticket> util = new ExcelUtil<TJobticket>(TJobticket.class);
        return util.exportExcel(exportList, "jobticket");
    }

    /**
     * 获取工作票详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tJobticketService.selectTJobticketById(id));
    }

    /**
     * 新增工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:add')")
    @Log(title = "工作票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TJobticket tJobticket) {
        if (StringUtils.isEmpty(tJobticket.getWhgzxkzh()) && StringUtils.isEmpty(tJobticket.getDhzyxkzh()) && StringUtils.isEmpty(tJobticket.getXzkjxkzh()) && StringUtils.isEmpty(tJobticket.getMbzyxkzh()) && StringUtils.isEmpty(tJobticket.getGczyxkzh())) {
            return AjaxResult.error("票号不能为空");
        }
        if (tJobticket.getXpxp() != null && tJobticket.getXpxp().equals("12")) {
            int i = tJobticketMapper.countXp(tJobticket);
            logger.info("预约票数量:" + i);
            if (i >= 10) {
                return AjaxResult.error("超过预约票数量上限10");
            }
        }
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        StringBuilder contentUserUnit = new StringBuilder();
        if (tJobticket.getUserUnit() != null) {
            contentUserUnit.append(tJobticket.getUserUnit());//用户单位
        }
        if (tJobticket.getUserMg() != null) {
            SysUser sysUser = sysUserService.selectUserById(tJobticket.getUserMg());
            contentUserUnit.append(sysUser.getNickName());
        }
        tJobticket.setByclxr(contentUserUnit.toString());
        tJobticket.setCreaterCode(getUserId().toString());
        return toAjax(tJobticketService.insertTJobticket(tJobticket));
    }


    /**
     * 批量新增工作票
     */
    @Log(title = "工作票", businessType = BusinessType.INSERT)
    @RequestMapping("/batchAddJobticket")
    public AjaxResult batchEdit(@RequestBody List<TInvoiceWorkcontent> dto) {
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        StringBuilder contentUserUnit = new StringBuilder();
        int sameCount = 0;
        int nosanmeCount = 0;
        int noCount = 0;
        //批量插入时 需要查询数据库是否有重复数据 若果有 就不新增
        for (int i = 0; i < dto.size(); i++) {
            if (StringUtils.isEmpty(dto.get(i).getGczyxkzh()) && StringUtils.isEmpty(dto.get(i).getDhzyxkzh()) && StringUtils.isEmpty(dto.get(i).getXzkjxkzh()) && StringUtils.isEmpty(dto.get(i).getMbzyxkzh()) && StringUtils.isEmpty(dto.get(i).getWhgzxkzh())) {
                noCount++;
                continue;
            }
            TJobticket tJobticket = new TJobticket();
            TInvoiceWorkcontent tInvoiceWorkcontent = dto.get(i);
            //部门应该是CBP/C 写死
            tJobticket.setDeptId(103l);

            tJobticket.setContent(tInvoiceWorkcontent.getBookingworkticket().getWorkArea() + tInvoiceWorkcontent.getWorkDescription());
            //byc 联系人 用户主管+用户单位
            if (tInvoiceWorkcontent.getBookingworkticket().getUserUnit() != null) {
                contentUserUnit.append(tInvoiceWorkcontent.getBookingworkticket().getUserUnit());//用户单位
            }
            if (tInvoiceWorkcontent.getBookingworkticket().getUserMg() != null) {
                SysUser sysUser = sysUserService.selectUserById(tInvoiceWorkcontent.getBookingworkticket().getUserMg());
                contentUserUnit.append(sysUser.getNickName());

            }
            tJobticket.setByclxr(contentUserUnit.toString());
            tJobticket.setSgdw(tInvoiceWorkcontent.getBookingworkticket().getWorkUnit());
            tJobticket.setLxr(tInvoiceWorkcontent.getBookingworkticket().getContact());
            tJobticket.setLxdh(tInvoiceWorkcontent.getBookingworkticket().getPhonenumber());
            //各项票号
            tJobticket.setYqxkzh(tInvoiceWorkcontent.getYqxkzh());
            tJobticket.setXzkjxkzh(tInvoiceWorkcontent.getXzkjxkzh());
            tJobticket.setMbzyxkzh(tInvoiceWorkcontent.getMbzyxkzh());
            tJobticket.setWhgzxkzh(tInvoiceWorkcontent.getWhgzxkzh());
            tJobticket.setHpjb(tInvoiceWorkcontent.getHpjb());
            tJobticket.setGczyxkzh(tInvoiceWorkcontent.getGczyxkzh());
            tJobticket.setGczyjb(tInvoiceWorkcontent.getGczyjb());
            tJobticket.setDhzyxkzh(tInvoiceWorkcontent.getDhzyxkzh());
            tJobticket.setUserMg(tInvoiceWorkcontent.getBookingworkticket().getUserMg());
            tJobticket.setUserUnit(tInvoiceWorkcontent.getBookingworkticket().getUserUnit());
            tJobticket.setTag(tInvoiceWorkcontent.getTag());
            tJobticket.setZypzt("10");
            tJobticket.setQfsj("8:30");
            tJobticket.setKprq(tInvoiceWorkcontent.getBookingworkticket().getWorkStartTime());
            tJobticket.setXpxp(tInvoiceWorkcontent.getXpxp());
            //先查询是否重复
            int same = tJobticketService.selectTJobticketSameData(tJobticket);
            if (same > 0) {
                sameCount++;
                tInvoiceWorkcontent.setAddStatus(1);
                invoiceWorkcontentMapper.updateTInvoiceWorkcontent(tInvoiceWorkcontent);
            } else {
                tJobticketService.insertTJobticket(tJobticket);
                nosanmeCount++;
                tInvoiceWorkcontent.setAddStatus(1);
                invoiceWorkcontentMapper.updateTInvoiceWorkcontent(tInvoiceWorkcontent);
            }

            contentUserUnit.delete(0, contentUserUnit.length());
        }
        return AjaxResult.success("成功导入" + nosanmeCount + "条数据，" + "\n" + "未导入重复" + sameCount + "条数据！" + "\n" + "未填写票号" + noCount + "条数据！");
    }

    /**
     * 修改工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:edit')")
    @Log(title = "工作票", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TJobticket tJobticket) {
        if (StringUtils.isEmpty(tJobticket.getWhgzxkzh()) && StringUtils.isEmpty(tJobticket.getDhzyxkzh()) && StringUtils.isEmpty(tJobticket.getXzkjxkzh()) && StringUtils.isEmpty(tJobticket.getMbzyxkzh()) && StringUtils.isEmpty(tJobticket.getGczyxkzh())) {
            return AjaxResult.error("票号不能为空");
        }
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        StringBuilder contentUserUnit = new StringBuilder();
        if (tJobticket.getUserUnit() != null) {
            contentUserUnit.append(tJobticket.getUserUnit());//用户单位
        }
        if (tJobticket.getUserMg() != null) {
            SysUser sysUser = sysUserService.selectUserById(tJobticket.getUserMg());
            contentUserUnit.append(sysUser.getNickName());
        }
        tJobticket.setByclxr(contentUserUnit.toString());
        tJobticket.setUpdaterCode(getUserId().toString());
        tJobticket.setUpdatedate(new Date());
        return toAjax(tJobticketService.updateTJobticket(tJobticket));
    }

    /**
     * 修改工作票状态
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:edit')")
    @Log(title = "工作票状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult editStatus(@RequestBody TJobticket tJobticket) {
        if ("18".equals(tJobticket.getZypzt())) {
            if (StringUtils.isEmpty(tJobticket.getWhgzxkzh()) && StringUtils.isEmpty(tJobticket.getDhzyxkzh()) && StringUtils.isEmpty(tJobticket.getXzkjxkzh()) && StringUtils.isEmpty(tJobticket.getMbzyxkzh()) && StringUtils.isEmpty(tJobticket.getGczyxkzh())) {
                return AjaxResult.error("票号不能为空");
            }
            //批量
            return toAjax(tJobticketMapper.updateTJobticketStatus(tJobticket));
        } else {
            //单个
            return toAjax(tJobticketService.updateTJobticket(tJobticket));
        }
    }

    /**
     * 删除工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:remove')")
    @Log(title = "工作票", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tJobticketService.deleteTJobticketByIds(ids));
    }

    /**
     * 批量导入工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:add')")
    @Log(title = "工作票", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TJobticket> list = new ArrayList<TJobticket>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> qfbz = iSysDictTypeService.selectDictDataByType("QFBZ");
        List<SysDictData> xpxp = iSysDictTypeService.selectDictDataByType("XPXP");
        List<SysDictData> hpjb = iSysDictTypeService.selectDictDataByType("HPJB");
        List<SysDictData> zypzt = iSysDictTypeService.selectDictDataByType("ZYPZT");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TJobticket entity = new TJobticket();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        if (cellValue.length() > 3) {
                            entity.setKprq(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//开票日期
                        }
                    } else if (j == 2) {
                        entity.setQfsj(cellValue);//签发时间
                    } else if (j == 3) {
                        for (SysDictData p : qfbz) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setQfbz(p.getDictValue());//签发班组
                            }
                        }
                    } else if (j == 4) {
                        entity.setQfr(cellValue);//签发人
                    } else if (j == 5) {
                        for (SysDictData p : xpxp) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setXpxp(p.getDictValue());//新票/续票
                            }
                        }
                    } else if (j == 6) {
                        entity.setYqxkzh(cellValue);//延期许可证号
                    } else if (j == 7) {
                        entity.setWhgzxkzh(cellValue);//危害工作许可证号
                    } else if (j == 8) {
                        entity.setDhzyxkzh(cellValue);//未撤销项编号
                    } else if (j == 9) {
                        for (SysDictData p : hpjb) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setHpjb(p.getDictValue());//火票级别
                            }
                        }
                    } else if (j == 10) {
                        entity.setXzkjxkzh(cellValue);//限制空间许可证号
                    } else if (j == 11) {
                        entity.setContent(cellValue);//工作内容
                    } else if (j == 12) {
                        entity.setByclxr(cellValue);//BYC负责单位/联系人
                    } else if (j == 13) {
                        entity.setSgdw(cellValue);//施工单位
                    } else if (j == 14) {
                        entity.setLxr(cellValue);//联系人
                    } else if (j == 15) {
                        entity.setLxdh(cellValue);//联系电话
                    } else if (j == 16) {
                        if (cellValue.length() > 3) {
                            entity.setXpsj(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//销票时间
                        }
                    } else if (j == 17) {
                        for (SysDictData p : zypzt) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setZypzt(p.getDictValue());//作业票状态
                            }
                        }
                    } else if (j == 18) {
                        entity.setJccdr(cellValue);//检查/存档人
                    } else if (j == 19) {
                        entity.setWcxxbh(cellValue);//未撤销项编号
                    } else if (j == 20) {
                        entity.setWcxzt(cellValue);//未撤销状态
                    } else if (j == 21) {
                        if (cellValue.length() > 3) {
                            entity.setCxsj(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//撤销时间
                        }
                    } else if (j == 22) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 23) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TJobticket t : list
        ) {
            failNum++;
            try {
                tJobticketService.insertTJobticket(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
