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

import cn.ezhizao.common.utils.WaterMakerUtils;
import cn.ezhizao.common.utils.ZipUtils;
import cn.ezhizao.common.utils.file.FileUtils;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.task.RyTask;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.domain.watermaker.ImgWaterMarker;
import cn.ezhizao.framework.web.domain.watermaker.TextWaterMarker;
import cn.ezhizao.framework.web.domain.watermaker.WaterMarker;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.equipment.domain.BizEquipmentDetail;
import cn.ezhizao.project.business.equipment.service.IBizEquipmentCategoryService;
import cn.ezhizao.project.business.equipment.service.IBizEquipmentDetailService;
import cn.ezhizao.project.business.equipment.service.IBizEquipmentService;
import cn.ezhizao.project.business.resourceGroup.domain.BizProductionResourceGroupDetail;
import cn.ezhizao.project.business.resourceGroup.service.IBizProductionResourceGroupDetailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 设备档案Controller
 *
 * @author ezhizao
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/business/equipmentDetail")
public class BizEquipmentDetailController extends BaseController {
    @Resource
    private IBizEquipmentDetailService bizEquipmentDetailService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RyTask task;
    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url}")
    private String uploadUrl;

    @Resource
    private IBizEquipmentService bizEquipmentService;
    @Resource
    private IBizEquipmentCategoryService bizEquipmentCategoryService;

    @Resource
    private WaterMakerUtils waterMakerUtils;

    @Resource
    private IBizProductionResourceGroupDetailService bizProductionResourceGroupDetailService;

    /**
     * 查询设备档案列表
     */
    //@PreAuthorize("@ss.hasPermi('business:equipment:list')")
    @PostMapping("/list")
    @Log(title = "设备明细查询", businessType = BusinessType.SELECT)
    public TableDataInfo list(@RequestBody Map<String, Object> data) {
        Integer zero = 0;
//        String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizEquipmentDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        final String param1 = "equipmentId";
        final String param2 = "equipmentCode";
        final String param3 = "usageDeptId";
        long equipmentId = 0L;
        if (data.get(param1) != null) {
            equipmentId = Long.parseLong(data.get(param1).toString());
        }
        if (data.get(param2)!= null && !"".equals(data.get(param2).toString())) {
            queryWrapper.like("equipment_code", data.get(param2).toString());
        }
        queryWrapper.eq("equipment_id", equipmentId);
//        if (tenantId != null && !zero.toString().equals(tenantId)) {
//            queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
//        }
        startPage();
        List<BizEquipmentDetail> list = bizEquipmentDetailService.list(queryWrapper);
        return getDataTable(list);
    }
    /**
     * 查询设备档案列表
     */
    //@PreAuthorize("@ss.hasPermi('business:equipment:list')")
    @Transactional
    @Log(title = "设备档案管理查询", businessType = BusinessType.SELECT)
    @GetMapping("/detailList")
    public TableDataInfo detailList( BizEquipmentDetail data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
//        final String tenantId = request.getHeader("tenantId");
//        data.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizEquipmentDetail> list = bizEquipmentDetailService.getDetailsList(data);
//        for (BizEquipmentDetail item:list
//        ) {
//            if (item.getQcCode().equals("")){
//                task.GenerateQcCode(item);
//            }
//        }
        return getDataTable(list);
    }

    /**
     * 查询设备档案
     */
//    @PreAuthorize("@ss.hasPermi('business:equipment:list')")
    @PostMapping("/resourceAllocation")
    @Log(title = "查询设备档案", businessType = BusinessType.SELECT)
    public TableDataInfo resourceAllocation(@RequestBody BizEquipmentDetail data) throws NoSuchFieldException, IllegalAccessException {
//        final String tenantId = request.getHeader("tenantId");
//        data.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizEquipmentDetail> list = bizEquipmentDetailService.getResourceAllocationList(data);
        return getDataTable(list);
    }
    /**
     * 获取设备档案详细信息
     */
//    @PreAuthorize("@ss.hasPermi('business:equipment:query')")
    @GetMapping(value = "/getInfo/{id}")
    @Log(title = "获取设备档案详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizEquipmentDetailService.getById(id));
    }

    /**
     * 新增设备档案
     */
//    @PreAuthorize("@ss.hasPermi('business:equipment:add, business:equipment:edit')")
    @Log(title = "新增设备档案", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody BizEquipmentDetail bizEquipmentDetail) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
//        final String tenantId = request.getHeader("tenantId");
//        bizEquipmentDetail.setTenantId(Long.valueOf(tenantId));
        boolean bool = bizEquipmentDetailService.saveOrUpdate(bizEquipmentDetail);
//        task.GenerateQcCode(bizEquipmentDetail);
        return bool?success(bizEquipmentDetail):error("操作失败!");
    }


    /**
     * 导出设备二维码
     * @param bizEquipmentDetails
     * @return
     */
    @GetMapping("/downloadQcImgs")
    @Log(title = "导出设备二维码", businessType = BusinessType.OTHER)
    public AjaxResult downloadQcImgs(BizEquipmentDetail bizEquipmentDetails) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        List<BizEquipmentDetail> list = bizEquipmentDetailService.getList(bizEquipmentDetails);
        String urlPrefix = uploadUrl.substring(uploadUrl.indexOf("/")+1,uploadUrl.lastIndexOf("/"));
        WaterMarker waterMarker = new WaterMarker();
        FileUtils.deleteFileDirectory(uploadPath+"/qcCode/equipment/printImages");
        File dir = new File(uploadPath+"/qcCode/equipment/printImages");
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        for(BizEquipmentDetail item:list){
            String equipmentName = item.getEquipmentName()==null?"":item.getEquipmentName().replace("/"," ");
            String equipmentCode = item.getEquipmentCode()==null?"":item.getEquipmentCode().replace("/"," ");
            task.GenerateQcCode(item);
            waterMarker.setBackgroundImgUrl(uploadPath+"/qcCode/equipment.png");
            waterMarker.setResultImgUrl(uploadPath+"/qcCode/equipment/printImages/"+equipmentName+"-"+equipmentCode+".png");
            waterMarker.setResultRelativeUrl(urlPrefix+"/qcCode/equipment/printImages/"+equipmentName+"-"+equipmentCode+".png");
            List<TextWaterMarker> textWaterMarkers = new ArrayList<>();
            // 编号
            TextWaterMarker code = new TextWaterMarker();
            code.setColor(new Color(67,67,67));
            code.setContent(equipmentName);
//            code.setFont(new Font("PingFang-SC-Bold", Font.BOLD, 20));
            code.setFont(new Font("楷体", Font.BOLD, 20));

            code.setX(120);
            code.setY(27);
            textWaterMarkers.add(code);
            // 名称
            TextWaterMarker name = new TextWaterMarker();
            name.setColor(new Color(67,67,67));
            name.setContent(equipmentCode);
//            name.setFont(new Font("PingFang-SC-Bold", Font.BOLD, 20));
            name.setFont(new Font("楷体", Font.BOLD, 20));

            name.setX(120);
            name.setY(73);
            textWaterMarkers.add(name);

            List<ImgWaterMarker> imgWaterMarkers = new ArrayList<>();
            ImgWaterMarker acCode = new ImgWaterMarker();
            acCode.setImgUrl(uploadPath.replace("upload/","")+item.getQcCode());
            acCode.setX(0);
            acCode.setY(50);
            acCode.setIsLocal(true);
            acCode.setIsScale(true);
            acCode.setScaleRate(0.8f);
            imgWaterMarkers.add(acCode);
            waterMarker.setImages(imgWaterMarkers);
            waterMarker.setTexts(textWaterMarkers);
//            waterMakerUtils.imageCombine(waterMarker);
        }
        FileUtils.deleteFile(uploadPath+"/qcCode/equipment/printImages.zip");
        ZipUtils zipUtils = new ZipUtils(new File(uploadPath+"/qcCode/equipment/printImages.zip"));
        zipUtils.zipFiles(dir);
        return success("/" +urlPrefix+"/qcCode/equipment/printImages.zip");
    }

    /**
     * 设备二维码导出
     */
//    @PreAuthorize("@ss.hasPermi('business:equipment:add, business:equipment:edit')")
    @Log(title = "设备档案", businessType = BusinessType.INSERT)
    @PostMapping(value = "/updateBacth")
    public AjaxResult updateBacth(@RequestBody List<BizEquipmentDetail> bizEquipmentDetails) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//      for (BizEquipmentDetail bizEquipmentDetail : bizEquipmentDetails) {
//          bizEquipmentDetail.setTenantId(Long.valueOf(tenantId));
//      }
        boolean batch = bizEquipmentDetailService.updateBatchById(bizEquipmentDetails);
        return toAjax(batch);
    }


    /**
     * 删除设备档案
     */
//    @PreAuthorize("@ss.hasPermi('business:equipment:remove')")
    @Log(title = "删除设备档案", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        //删除设备判断该设备是否添加到资源组了，如果添加了，不能删
        QueryWrapper<BizProductionResourceGroupDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("common_id",ids.get(0));
        if(bizProductionResourceGroupDetailService.list(queryWrapper).size()>0) {
            return error("该设备已添加到资源组，不能删除");
        }
        return toAjax(bizEquipmentDetailService.removeBatchByIds(ids));
    }
}
