package cn.ezhizao.project.business.technologicalProcessDetailDrawing.controller;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.pdf.PdfUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.config.RuoYiConfig;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.message.domain.BizMessage;
import cn.ezhizao.project.business.message.service.IBizMessageService;
import cn.ezhizao.project.business.personSeal.domain.BizPersonalSeal;
import cn.ezhizao.project.business.personSeal.service.IBizPersonalSealService;
import cn.ezhizao.project.business.publicSeal.domain.BizPublicSeal;
import cn.ezhizao.project.business.publicSeal.service.IBizPublicSealService;
import cn.ezhizao.project.business.technologicalProcessDetailDrawing.domain.BizTechnologicalProcessDetailDrawing;
import cn.ezhizao.project.business.technologicalProcessDetailDrawing.service.IBizTechnologicalProcessDetailDrawingService;
import cn.ezhizao.project.business.technologicalProcessDetailDrawingRecords.domain.BizTechnologicalProcessDetailDrawingRecords;
import cn.ezhizao.project.business.technologicalProcessDetailDrawingRecords.service.IBizTechnologicalProcessDetailDrawingRecordsService;
import cn.ezhizao.project.business.technologicalProcessDetailDrawingUser.domain.BizTechnologicalProcessDetailDrawingUser;
import cn.ezhizao.project.business.technologicalProcessDetailDrawingUser.service.IBizTechnologicalProcessDetailDrawingUserService;
import cn.ezhizao.project.system.domain.SysRole;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.service.ISysRoleService;
import cn.ezhizao.project.system.service.ISysUserService;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 电子图纸Controller
 *
 * @author ezhizao
 * @date 2024-05-30
 */
@RestController
@RequestMapping("/business/drawing")
public class BizTechnologicalProcessDetailDrawingController extends BaseController {

    @Resource
    private IBizTechnologicalProcessDetailDrawingService bizTechnologicalProcessDetailDrawingService;
    @Resource
    private IBizTechnologicalProcessDetailDrawingRecordsService bizTechnologicalProcessDetailDrawingRecordsService;
    @Resource
    private IBizPersonalSealService bizPersonalSealService;
    @Resource
    private IBizPublicSealService bizPublicSealService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IBizMessageService bizMessageService;
    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IBizTechnologicalProcessDetailDrawingUserService bizTechnologicalProcessDetailDrawingUserService;


    @Log(title = "电子图纸导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportDrawing(HttpServletResponse response) {


        BizTechnologicalProcessDetailDrawing item = new BizTechnologicalProcessDetailDrawing();
        List<BizTechnologicalProcessDetailDrawing> list = bizTechnologicalProcessDetailDrawingService.getDrawingListByBasics(item);
        for (BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing : list) {


            bizTechnologicalProcessDetailDrawing.setCompanyAlias(bizTechnologicalProcessDetailDrawing.getProduct().getCompanyAlias());
            bizTechnologicalProcessDetailDrawing.setSpecification(bizTechnologicalProcessDetailDrawing.getProduct().getSpecification());
            bizTechnologicalProcessDetailDrawing.setDescription(bizTechnologicalProcessDetailDrawing.getProduct().getDescription());
        }

        ExcelUtil<BizTechnologicalProcessDetailDrawing> util = new ExcelUtil<BizTechnologicalProcessDetailDrawing>(BizTechnologicalProcessDetailDrawing.class);
        util.exportExcel(response, list, "电子图纸数据");
    }

    @Log(title = "电子图纸导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:workpiece:import')")
    @Transactional
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BizTechnologicalProcessDetailDrawing> util = new ExcelUtil<>(BizTechnologicalProcessDetailDrawing.class);
        List<BizTechnologicalProcessDetailDrawing> bizTechnologicalProcessDetailDrawings = util.importExcel(file.getInputStream());
        List<BizTechnologicalProcessDetailDrawing> noSealUserList = new ArrayList<>();
        for (BizTechnologicalProcessDetailDrawing item : bizTechnologicalProcessDetailDrawings) {
            SysUser userParam = new SysUser();
            SysUser user = new SysUser();
            userParam.setUserName(item.getProducerCode());
            userParam.setNickName(item.getProducer());
            List<SysUser> userList = userService.getListByUserName(userParam);
            if (userList.isEmpty()) {
                item.setMessage("制作人信息录入错误");
                noSealUserList.add(item);
                continue;
            } else {
                user = userList.get(0);
            }
            SysUser Reviewer = new SysUser();
            Reviewer.setUserName(item.getReviewerCode());
            Reviewer.setNickName(item.getReviewer());
            List<SysUser> ReviewerList = userService.getListByUserName(Reviewer);
            if (ReviewerList.isEmpty()) {
                item.setMessage("审核人信息录入错误");
                noSealUserList.add(item);
                continue;
            }
            SysUser Issuer = new SysUser();
            Issuer.setUserName(item.getIssuerCode());
            Issuer.setNickName(item.getIssuer());

            List<SysUser> IssuerList = userService.getListByUserName(Issuer);
            if (IssuerList.isEmpty()) {
                item.setMessage("批准人信息录入错误");
                noSealUserList.add(item);
                continue;
            }
            BizPersonalSeal person = new BizPersonalSeal();
            person.setUserId(user.getUserId());
            String filePath = RuoYiConfig.getProfile();
            List<BizPersonalSeal> personList = bizPersonalSealService.getList(person);
            System.out.println("查询个人章" + person);
            System.out.println("查询个人章是否为空" + personList.isEmpty());
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            // 格式化日期
            String formattedDate = currentDate.format(formatter);
            if (personList.isEmpty()) {
                item.setMessage("没有个人章");
                noSealUserList.add(item);
                continue;
            }
            BizTechnologicalProcessDetailDrawing repeatList = bizTechnologicalProcessDetailDrawingService.query().eq("id", item.getId()).one();
            if (repeatList.getProducerId() != 0 || repeatList.getReviewerId() != 0 || repeatList.getIssuerId() != 0) {
                item.setMessage("该图纸已走会签流程");
                noSealUserList.add(item);
                continue;
            }
            String personalSeal = personList.get(0).getUrl().substring("/profile".length());
            BizTechnologicalProcessDetailDrawing getItem = bizTechnologicalProcessDetailDrawingService.query().eq("id", item.getId()).one();
            getItem.setMarkD(item.getMarkD());
            getItem.setIdentification(item.getIdentification());

            String url = "";
            url = getItem.getUrl();
            url = url.substring("/profile".length());
            getItem.setProducerId(user.getUserId());
            getItem.setProducer(user.getNickName());
            getItem.setStatus(0);

            getItem.setPattern("新产品");
            //上传调整尺寸


            PdfUtils.reSized(filePath + url, filePath + url.substring(0, url.length() - 4) + "制作" + url.substring(url.length() - 4), 100, "height");
            bizTechnologicalProcessDetailDrawingService.addText(filePath + url.substring(0, url.length() - 4) + "制作" + url.substring(url.length() - 4), filePath + url.substring(0, url.length() - 4) + "制作人" + url.substring(url.length() - 4), "制定人：", 550, 75, 12, 270);
            bizTechnologicalProcessDetailDrawingService.addText(filePath + url.substring(0, url.length() - 4) + "制作人" + url.substring(url.length() - 4), filePath + url.substring(0, url.length() - 4) + "制作时间" + url.substring(url.length() - 4), formattedDate, 500, 75, 12, 270);
            bizTechnologicalProcessDetailDrawingService.addImage(filePath + url.substring(0, url.length() - 4) + "制作时间" + url.substring(url.length() - 4), filePath + url.substring(0, url.length() - 4) + "制作完成" + url.substring(url.length() - 4), filePath + personalSeal, 515, 40, 30, 30, 270, 1);
            getItem.setUrl("/profile/" + url.substring(0, url.length() - 4) + "制作完成" + url.substring(url.length() - 4));
            bizTechnologicalProcessDetailDrawingService.updateById(getItem);
            //添加用户记录
            BizTechnologicalProcessDetailDrawingUser drawingUser = new BizTechnologicalProcessDetailDrawingUser();
            drawingUser.setDrawingId(getItem.getId());
            drawingUser.setProcessCode(getItem.getProcessCode());
            drawingUser.setDrawingName(getItem.getDrawingName());
            drawingUser.setType(0);
            drawingUser.setUserId(user.getUserId());
            drawingUser.setNickName(user.getNickName());
            drawingUser.setProductId(getItem.getProductId());
            drawingUser.setProductVersion(getItem.getProductVersion());
            drawingUser.setRecordTime(new Date());
            bizTechnologicalProcessDetailDrawingUserService.save(drawingUser);
            List<BizTechnologicalProcessDetailDrawing> itemList = new ArrayList<>();
            itemList.add(getItem);
            //开始正是走审核流程

            bizTechnologicalProcessDetailDrawingService.saveData(itemList, item.getReviewerCode(), item.getReviewer());
            //批准流程

            bizTechnologicalProcessDetailDrawingService.saveData(itemList, item.getIssuerCode(), item.getIssuer());
        }
        if (!noSealUserList.isEmpty()) {
            System.out.println("11111111111111111111111111111111111111111111111111111");
            System.out.println(noSealUserList);
            String filePath = RuoYiConfig.getProfile();
            String listAsString = String.join(System.lineSeparator(), noSealUserList.stream()
                    .map(BizTechnologicalProcessDetailDrawing::toString) // 假设SysUser有一个toString方法
                    .toArray(String[]::new));

            // 指定文件路径，例如保存在当前项目目录
            String txtFilePath = filePath + "/upload/" + "noSealUserList.txt";

            // 将字符串写入文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(txtFilePath))) {
                writer.write(listAsString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return success(noSealUserList);
        }
        return success(bizTechnologicalProcessDetailDrawings);
    }

    /**
     * 查询电子图纸列表
     */
    @Log(title = "电子图纸查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException {
//        setTenantId(bizTechnologicalProcessDetailDrawing);
        startPage();
        List<BizTechnologicalProcessDetailDrawing> list = bizTechnologicalProcessDetailDrawingService.getList(bizTechnologicalProcessDetailDrawing);
        return getDataTable(list);
    }

    /**
     * 查询电子图纸列表
     */
    @Log(title = "电子图纸查询", businessType = BusinessType.SELECT)
    @GetMapping("/drawingList")
    public TableDataInfo drawingList(BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException {
//        setTenantId(bizTechnologicalProcessDetailDrawing);
        startPage();
        List<BizTechnologicalProcessDetailDrawing> list = bizTechnologicalProcessDetailDrawingService.getDrawingList(bizTechnologicalProcessDetailDrawing);
        return getDataTable(list);
    }

    /**
     * 查询电子图纸列表
     */
    @Log(title = "电子图纸条件查询", businessType = BusinessType.SELECT)
    @GetMapping("/byName")
    public AjaxResult byName(BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException {

        List<BizTechnologicalProcessDetailDrawing> drawingName = bizTechnologicalProcessDetailDrawingService
                .query()
                .eq("drawing_name", bizTechnologicalProcessDetailDrawing.getDrawingName())
                .eq("product_version", bizTechnologicalProcessDetailDrawing.getProductVersion())
                .eq("process_code", bizTechnologicalProcessDetailDrawing.getProcessCode())
                .eq("product_id", bizTechnologicalProcessDetailDrawing.getProductId())
                .list();

        return success(drawingName);
    }

    /**
     * 根据文件名查询列表
     */
    @Log(title = "电子图纸根据文件名查询", businessType = BusinessType.SELECT)
    @GetMapping("/getListByName")
    public AjaxResult getListByName(BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException {

        List<BizTechnologicalProcessDetailDrawing> drawingName = bizTechnologicalProcessDetailDrawingService
                .query()
                .eq("drawing_name", bizTechnologicalProcessDetailDrawing.getDrawingName())
                .eq("product_version", bizTechnologicalProcessDetailDrawing.getProductVersion())
                .eq("process_code", bizTechnologicalProcessDetailDrawing.getProcessCode())
                .eq("product_id", bizTechnologicalProcessDetailDrawing.getProductId())
                .eq("status", 0)
                .list();

        return success(drawingName);
    }
    /**
     * 导出电子图纸列表
     */
//    @PreAuthorize("@ss.hasPermi('business:drawing:export')")
//    @Log(title = "电子图纸", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException
//    {
//        setTenantId(bizTechnologicalProcessDetailDrawing);
//        List<BizTechnologicalProcessDetailDrawing> list = bizTechnologicalProcessDetailDrawingService.getList(bizTechnologicalProcessDetailDrawing);
//        ExcelUtil<BizTechnologicalProcessDetailDrawing> util = new ExcelUtil<BizTechnologicalProcessDetailDrawing>(BizTechnologicalProcessDetailDrawing.class);
//        util.exportExcel(response, list, "电子图纸数据");
//    }

    /**
     * 获取电子图纸详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:drawing:query')")
    @Log(title = "电子图纸查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizTechnologicalProcessDetailDrawingService.getById(id));
    }

    @Log(title = "产品电子图纸查询", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getProcuctDrawing")
    public AjaxResult getProcuctDrawing() {
        return success(bizTechnologicalProcessDetailDrawingService.getProcuctDrawing());
    }

    /**
     * 新增电子图纸会签
     */
    @Log(title = "电子图纸保存", businessType = BusinessType.INSERT)
    @PostMapping("/save")

    public AjaxResult save(@RequestBody List<BizTechnologicalProcessDetailDrawing> bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException, COSVisitorException, DocumentException, IOException {


        int i = bizTechnologicalProcessDetailDrawingService.saveData(bizTechnologicalProcessDetailDrawing, SecurityUtils.getLoginUser().getUser().getUserName(), SecurityUtils.getLoginUser().getUser().getNickName());
        if (i == 3) {
            return error("请先上传个人章");
        } else if (i == 4) {
            return error("未查询到当前员工");
        } else {
            // 给所有有图纸审批权限的人发站内信，通知审批
            sendMessage();
            return success();
        }
    }

    /**
     * 发送审批信息
     */
    private void sendMessage() {
        SysRole role = new SysRole();
        role.setRoleKey("drawingRatify");
        List<SysRole> roles = sysRoleService.selectRoleList(role);
        List<BizMessage> messages = new ArrayList<>();
        roles.forEach(l -> {
            SysUser conditions = new SysUser();
            conditions.setRoleId(l.getRoleId());
            List<SysUser> items = sysUserService.selectAllocatedList(conditions);
            items.forEach(v -> {
                BizMessage message = new BizMessage();
                message.setFromNickName(SecurityUtils.getLoginUser().getUser().getNickName());
                message.setFromUserId(SecurityUtils.getLoginUser().getUser().getUserId());
                message.setFromUserName(SecurityUtils.getLoginUser().getUser().getUserName());
                message.setToNickName(v.getNickName());
                message.setToUserId(v.getUserId());
                message.setToUserName(v.getUserName());
                message.setMessage("您有图纸待批准，请前往【工艺管理】下【等待批准图纸】菜单进行操作。");
                message.setMessageDate(new Date());
                messages.add(message);
            });
        });
        bizMessageService.saveBatch(messages);
    }

    /**
     * 电子图纸作废
     */
    @Log(title = "电子图纸作废", businessType = BusinessType.UPDATE)
    @PutMapping("/drawingNG")
    @Transactional
    public AjaxResult drawingNG(@RequestBody List<BizTechnologicalProcessDetailDrawing> processDetailDrawing) throws NoSuchFieldException, IllegalAccessException, IOException {
        bizTechnologicalProcessDetailDrawingService.drawingNG(processDetailDrawing, SecurityUtils.getLoginUser().getUser().getUserName(), SecurityUtils.getLoginUser().getUser().getNickName());
        sendMessage();
        return success(true);
    }

    @Log(title = "电子图纸作废", businessType = BusinessType.UPDATE)
    @PutMapping("/drawingRemove")
    @Transactional
    public AjaxResult drawingRemove(@RequestBody List<BizTechnologicalProcessDetailDrawing> processDetailDrawing) throws NoSuchFieldException, IllegalAccessException, IOException, DocumentException {
        int i = bizTechnologicalProcessDetailDrawingService.drawingRemove(processDetailDrawing, SecurityUtils.getLoginUser().getUser().getUserName(), SecurityUtils.getLoginUser().getUser().getNickName());
        if (i == 3) {
            return error("请先上传个人章");
        } else if (i == 4) {
            return error("未查询到当前员工");
        } else {
            sendMessage();
            return success();
        }


    }

    /**
     * 电子图纸替换
     */
    @Log(title = "电子图纸替换", businessType = BusinessType.UPDATE)
    @PutMapping("/replaceDrawing")
    @Transactional
    public AjaxResult replace(@RequestBody BizTechnologicalProcessDetailDrawing processDetailDrawing) throws NoSuchFieldException, IllegalAccessException {
        //废弃旧图纸，生成新图纸
        processDetailDrawing.setStatus(3);
        processDetailDrawing.setVoided(SecurityUtils.getLoginUser().getUser().getNickName());
        processDetailDrawing.setVoidedId(SecurityUtils.getLoginUser().getUser().getUserId());
        bizTechnologicalProcessDetailDrawingService.updateById(processDetailDrawing);
        processDetailDrawing.setParentId(processDetailDrawing.getId());
        processDetailDrawing.setId(null);
        processDetailDrawing.setStatus(0);
        processDetailDrawing.setPattern("替换");
        processDetailDrawing.setIssuer(null);
        processDetailDrawing.setReviewer(null);
        processDetailDrawing.setIssuerId(null);
        processDetailDrawing.setReviewerId(null);
        processDetailDrawing.setProducerId(SecurityUtils.getLoginUser().getUser().getUserId());
        processDetailDrawing.setProducer(SecurityUtils.getLoginUser().getUser().getNickName());
        boolean result = bizTechnologicalProcessDetailDrawingService.save(processDetailDrawing);
//        if (result) {
//            sendMessage();
//        }
        return toAjax(result);
    }


    @Log(title = "电子图纸替换", businessType = BusinessType.UPDATE)
    @PutMapping("/replace")
    @Transactional
    public AjaxResult replaceDrawing(@RequestBody BizTechnologicalProcessDetailDrawing processDetailDrawing) throws NoSuchFieldException, IllegalAccessException, COSVisitorException, DocumentException, IOException {
        int i = bizTechnologicalProcessDetailDrawingService.replaceDrawing(processDetailDrawing);
        if (i == 3) {
            return error("请先上传个人章");
        } else {
//            sendMessage();
            return toAjax(i);
        }


    }

    /**
     * 新增电子图纸
     */
    @PreAuthorize("@ss.hasPermi('business:drawing:add')")
    @Log(title = "电子图纸新增", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing) throws NoSuchFieldException, IllegalAccessException {
        //判断覆盖的文件序号最高排到第几个，然后递增
        List<BizTechnologicalProcessDetailDrawing> drawingName = bizTechnologicalProcessDetailDrawingService
                .query()
                .like("drawing_name", bizTechnologicalProcessDetailDrawing.getDrawingName().substring(0, bizTechnologicalProcessDetailDrawing.getDrawingName().length() - 4) + "%")
                .eq("technological_process_detail_id", bizTechnologicalProcessDetailDrawing.getTechnologicalProcessDetailId())
                .list();
        List<Integer> numList = new ArrayList<>();
        if (drawingName.size() > 0) {
            for (BizTechnologicalProcessDetailDrawing item : drawingName
            ) {
                //判断倒数第五第六字符是否是数字,不是数字或者只有一个数字的话都会返回空值
                String lastFifthCharDigit = isLastFifthCharDigit(item.getDrawingName());
                if (!lastFifthCharDigit.equals("")) {

                    numList.add(Integer.parseInt(lastFifthCharDigit));
                }

            }
            //获取最大值
            if (numList.size() > 0) {
                Integer max = Collections.max(numList);
                String str = "";
                if (max < 10) {
                    str = "0" + (max + 1);
                } else {
                    str = "" + (max + 1);
                }
                bizTechnologicalProcessDetailDrawing.setDrawingName(
                        bizTechnologicalProcessDetailDrawing.getDrawingName().substring(0, bizTechnologicalProcessDetailDrawing.getDrawingName().length() - 4)
                                + "_"
                                + str
                                + bizTechnologicalProcessDetailDrawing.getDrawingName().substring(bizTechnologicalProcessDetailDrawing.getDrawingName().length() - 4)
                );
            } else {
                bizTechnologicalProcessDetailDrawing.setDrawingName(
                        bizTechnologicalProcessDetailDrawing.getDrawingName().substring(0, bizTechnologicalProcessDetailDrawing.getDrawingName().length() - 4)
                                + "_01"
                                + bizTechnologicalProcessDetailDrawing.getDrawingName().substring(bizTechnologicalProcessDetailDrawing.getDrawingName().length() - 4)
                );
            }

        }

        bizTechnologicalProcessDetailDrawingService.save(bizTechnologicalProcessDetailDrawing);
        //新增同时增加操作记录,覆盖不增加
        if (!bizTechnologicalProcessDetailDrawing.getType()) {
            BizTechnologicalProcessDetailDrawingRecords drawingRecords = new BizTechnologicalProcessDetailDrawingRecords();
            drawingRecords.setDrawingName(bizTechnologicalProcessDetailDrawing.getDrawingName());
            drawingRecords.setTechnologicalProcessDetailDrawingId(bizTechnologicalProcessDetailDrawing.getId());
            drawingRecords.setProcessCode(bizTechnologicalProcessDetailDrawing.getProcessCode());
            drawingRecords.setProductId(bizTechnologicalProcessDetailDrawing.getProductId());
            drawingRecords.setProductVersion(bizTechnologicalProcessDetailDrawing.getProductVersion());
            drawingRecords.setUserId(SecurityUtils.getUserId());
            drawingRecords.setType("新增");
            bizTechnologicalProcessDetailDrawingRecordsService.save(drawingRecords);
        }
//        sendMessage();
        return success();
    }

    /**
     * 覆盖电子图纸
     */
    @PreAuthorize("@ss.hasPermi('business:drawing:edit')")
    @Log(title = "电子图纸修改", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody BizTechnologicalProcessDetailDrawing processDetailDrawing) throws NoSuchFieldException, IllegalAccessException {


        return toAjax(bizTechnologicalProcessDetailDrawingService.edit(processDetailDrawing));
    }


    /**
     * 计算重名文件后缀
     *
     * @param s
     * @return
     */
    public static String isLastFifthCharDigit(String s) {
        int length = s.length();
        if (s == null || length < 7) {
            return "";
        }
        // 获取倒数第五个到第七字符，查询是不是“_00”格式
        char fifthCharFromEnd = s.charAt(s.length() - 5);
        char sixthCharFromEnd = s.charAt(s.length() - 6);
        char seventhCharFromEnd = s.charAt(s.length() - 7);
        String item = "";
        // 判断字符是否是数字
        if (seventhCharFromEnd == '_') {
            if (Character.isDigit(fifthCharFromEnd)) {
                if (Character.isDigit(sixthCharFromEnd)) {

                    return Character.getNumericValue(sixthCharFromEnd) + "" + Character.getNumericValue(fifthCharFromEnd);
                } else {
                    return "0" + Character.getNumericValue(fifthCharFromEnd);
                }
            } else {
                return "";
            }
        } else {
            return "";
        }


    }

//    public static String isLastFifthCharDigit(String s ) {
//        int length = s.length();
//        if (s == null || length<6){
//            return "";
//        }
//        // 获取倒数第五个字符的位置
//        char fifthCharFromEnd = s.charAt(s.length() - 5);
//        char sixthCharFromEnd = s.charAt(s.length() - 6);
//        String item = "";
//        // 判断字符是否是数字
//        if (Character.isDigit(fifthCharFromEnd)){
//            if (Character.isDigit(sixthCharFromEnd)){
//
//                return  Character.getNumericValue(sixthCharFromEnd) + "" + Character.getNumericValue(fifthCharFromEnd);
//            }else{
//                return Character.getNumericValue(fifthCharFromEnd) +"";
//            }
//        }else {
//            return "";
//        }
//
//    }

    /**
     * 删除电子图纸
     */
    @PreAuthorize("@ss.hasPermi('business:drawing:remove')")
    @Log(title = "电子图纸删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long ids) {
        BizTechnologicalProcessDetailDrawing bizTechnologicalProcessDetailDrawing = bizTechnologicalProcessDetailDrawingService.query().eq("id", ids).one();
        BizTechnologicalProcessDetailDrawingRecords drawingRecords = new BizTechnologicalProcessDetailDrawingRecords();
        drawingRecords.setDrawingName(bizTechnologicalProcessDetailDrawing.getDrawingName());
        drawingRecords.setTechnologicalProcessDetailDrawingId(bizTechnologicalProcessDetailDrawing.getId());
        drawingRecords.setProcessCode(bizTechnologicalProcessDetailDrawing.getProcessCode());
        drawingRecords.setProductId(bizTechnologicalProcessDetailDrawing.getProductId());
        drawingRecords.setProductVersion(bizTechnologicalProcessDetailDrawing.getProductVersion());
        drawingRecords.setUserId(SecurityUtils.getUserId());
        drawingRecords.setType("删除");
        bizTechnologicalProcessDetailDrawingRecordsService.save(drawingRecords);
        return toAjax(bizTechnologicalProcessDetailDrawingService.removeById(ids));
    }


}
