package com.gxwebsoft.tower.controller;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaQrcodeServiceImpl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.controller.WxLoginController;
import com.gxwebsoft.tower.entity.TowerEquipment;
import com.gxwebsoft.tower.entity.TowerProject;
import com.gxwebsoft.tower.entity.TowerProjectOrder;
import com.gxwebsoft.tower.param.TowerEquipmentParam;
import com.gxwebsoft.tower.service.TowerEquipmentService;
import com.gxwebsoft.tower.service.TowerProjectOrderService;
import com.gxwebsoft.tower.service.TowerProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 塔吊设备管理控制器
 *
 * @author 科技小王子
 * @since 2023-05-20 15:06:43
 */
@Api(tags = "塔吊设备管理管理")
@RestController
@RequestMapping("/api/tower/tower-equipment")
public class TowerEquipmentController extends BaseController {
    @Resource
    private TowerEquipmentService towerEquipmentService;
    @Resource
    private TowerProjectService projectService;
    @Resource
    private TowerProjectOrderService projectOrderService;

    @Value("${config.upload-path}")
    private String uploadPath;

    @PreAuthorize("hasAuthority('tower:towerEquipment:list')")
    @OperationLog
    @ApiOperation("塔吊设备数据")
    @GetMapping("/data")
    public ApiResult<Map<String, Integer>> data() {
        Map<String, Integer> data = new HashMap<>();
        Integer totalNum = towerEquipmentService.count(
                new LambdaQueryWrapper<TowerEquipment>()
                        .ne(TowerEquipment::getStatus, 3)
        );
        Integer idleNum = towerEquipmentService.count(
                new LambdaQueryWrapper<TowerEquipment>()
                        .eq(TowerEquipment::getStatus, 0)
        );
        Integer scrapNum = towerEquipmentService.count(
                  new LambdaQueryWrapper<TowerEquipment>()
                          .lt(TowerEquipment::getScrapDate, new Date())
          );
        Integer totalNum2 = towerEquipmentService.count(
          new LambdaQueryWrapper<TowerEquipment>()
            .eq(TowerEquipment::getStatus, 2)
        );
        Integer totalNum3 = towerEquipmentService.count(
          new LambdaQueryWrapper<TowerEquipment>()
            .eq(TowerEquipment::getStatus, 3)
        );
        Integer totalNum4 = towerEquipmentService.count(
          new LambdaQueryWrapper<TowerEquipment>()
            .eq(TowerEquipment::getStatus, 4)
        );
        Integer totalNum5 = towerEquipmentService.count(
          new LambdaQueryWrapper<TowerEquipment>()
            .eq(TowerEquipment::getStatus, 5)
        );
        data.put("totalNum", totalNum);
        data.put("idleNum", idleNum);
        data.put("scrapNum", scrapNum);
        data.put("totalNum2", totalNum2);
        data.put("totalNum3", totalNum3);
        data.put("totalNum4", totalNum4);
        data.put("totalNum5", totalNum5);
        return success(data);
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:list')")
    @OperationLog
    @ApiOperation("分页查询塔吊设备管理")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerEquipment>> page(TowerEquipmentParam param) {
        System.out.println("param.getYearFilter(): " + param.getYearFilter());
        List<Integer> equipmentIdList = new ArrayList<>();
        if (param.getIdleOnly() != null && param.getIdleOnly()) {
            // 不在未结案项目的设备列表
            equipmentIdList = towerEquipmentService.list(
                    new LambdaQueryWrapper<TowerEquipment>()
                            .ne(TowerEquipment::getStatus, 4)
            ).stream().map(TowerEquipment::getEquipmentId).collect(Collectors.toList());
        }
        // 使用关联查询
        LambdaQueryWrapper<TowerEquipment> wrapper = new LambdaQueryWrapper<>();
        if (!equipmentIdList.isEmpty()) wrapper.in(TowerEquipment::getEquipmentId, equipmentIdList);
        if (param.getKeywords() != null) {
            wrapper.and(i -> i.like(TowerEquipment::getFilingNo, param.getKeywords()).or()
                    .like(TowerEquipment::getModel, param.getKeywords()).or()
                    .like(TowerEquipment::getName, param.getKeywords()).or()
                    .like(TowerEquipment::getFactoryNo, param.getKeywords()));
        }
        if (param.getYearFilter() != null)
            wrapper.apply("CEIL( DATEDIFF(`scrap_date`, '" + DateUtil.today() + "') / 365) = {0}", param.getYearFilter());
        if (param.getStatus() != null) {
          if(param.getStatus().equals(1)){
            wrapper.lt(TowerEquipment::getScrapDate,DateUtil.today());
          }else {
            wrapper.eq(TowerEquipment::getStatus, param.getStatus());
          }
        };
        IPage<TowerEquipment> page = new PageParam<>(param);
        IPage<TowerEquipment> list = towerEquipmentService.page(page, wrapper);
        for (TowerEquipment equipment : list.getRecords()) {
//            System.out.println("equipment item" + equipment);
            List<TowerProjectOrder> projectOrderList = projectOrderService.list(
                    new LambdaQueryWrapper<TowerProjectOrder>()
                            .eq(TowerProjectOrder::getFilingNo, equipment.getFilingNo())
            );
            if (!projectOrderList.isEmpty()) {
                equipment.setProjectList(
                        projectService.list(
                                new LambdaQueryWrapper<TowerProject>()
                                        .in(TowerProject::getProjectId,
                                                projectOrderList.stream().map(TowerProjectOrder::getProjectId).collect(Collectors.toList())
                                        )
                        )
                );
            }
        }
        return success(list);
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:list')")
    @OperationLog
    @ApiOperation("查询全部塔吊设备管理")
    @GetMapping()
    public ApiResult<List<TowerEquipment>> list(TowerEquipmentParam param) {
        // 使用关联查询
        return success(towerEquipmentService.listRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:list')")
    @OperationLog
    @ApiOperation("根据id查询塔吊设备管理")
    @GetMapping("/{id}")
    public ApiResult<TowerEquipment> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(towerEquipmentService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:save')")
    @OperationLog
    @ApiOperation("添加塔吊设备管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerEquipment towerEquipment) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            towerEquipment.setUserId(loginUser.getUserId());
        }
        if (towerEquipmentService.save(towerEquipment)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:update')")
    @OperationLog
    @ApiOperation("修改塔吊设备管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerEquipment towerEquipment) {
        if (towerEquipmentService.updateById(towerEquipment)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:remove')")
    @OperationLog
    @ApiOperation("删除塔吊设备管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (towerEquipmentService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:save')")
    @OperationLog
    @ApiOperation("批量添加塔吊设备管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<TowerEquipment> list) {
//        for (TowerEquipment equipment : list) {
//            if (equipment.getProjectName() != null) {
//                TowerProject checkProject = projectService.getOne(
//                        new LambdaQueryWrapper<TowerProject>().eq(TowerProject::getProjectName, equipment.getProjectName())
//                );
//                if (checkProject == null) {
//                    TowerProject newProject = new TowerProject();
//                    newProject.setProjectName(equipment.getProjectName());
//                    newProject.setProjectCity(equipment.getCurrentLocation());
//                    newProject.setCompetentDepartment(equipment.getCompetentDepartment());
//                    projectService.save(newProject);
//
//                    TowerProjectOrder newProjectOrder = new TowerProjectOrder();
//                    newProjectOrder.setProjectId(newProjectOrder.getProjectId());
//                    newProjectOrder.setEquipmentName(equipment.getEquipmentName());
//                    newProjectOrder.setEquipmentModel(equipment.getEquipmentModel());
//                    newProjectOrder.setFilingNo(equipment.getFilingNo());
//                    newProjectOrder.setFactoryNo(equipment.getFactoryNo());
//                    newProjectOrder.setSecurityStatus(equipment.getSecurityStatus());
//                    projectOrderService.save(newProjectOrder);
//                } else {
//                    int checkProjectOrder = projectOrderService.count(
//                            new LambdaQueryWrapper<TowerProjectOrder>().eq(TowerProjectOrder::getProjectId, checkProject.getProjectId())
//                                    .eq(TowerProjectOrder::getFilingNo, equipment.getFilingNo())
//                    );
//                    if (checkProjectOrder == 0) {
//                        TowerProjectOrder newProjectOrder = new TowerProjectOrder();
//                        newProjectOrder.setProjectId(newProjectOrder.getProjectId());
//                        newProjectOrder.setEquipmentName(equipment.getEquipmentName());
//                        newProjectOrder.setEquipmentModel(equipment.getEquipmentModel());
//                        newProjectOrder.setFilingNo(equipment.getFilingNo());
//                        newProjectOrder.setFactoryNo(equipment.getFactoryNo());
//                        newProjectOrder.setSecurityStatus(equipment.getSecurityStatus());
//                        projectOrderService.save(newProjectOrder);
//                    }
//                }
//            }
//        }
        if (towerEquipmentService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:update')")
    @OperationLog
    @ApiOperation("批量修改塔吊设备管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerEquipment> batchParam) {
        if (batchParam.update(towerEquipmentService, "equipment_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:remove')")
    @OperationLog
    @ApiOperation("批量删除塔吊设备管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (towerEquipmentService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:update')")
    @OperationLog
    @ApiOperation("批量修改塔吊设备状态")
    @PutMapping("/status")
    public ApiResult<?> statusBatch(@RequestBody List<TowerEquipment> batchParam) {
        if (towerEquipmentService.updateBatchById(batchParam)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerEquipment:list')")
    @OperationLog
    @ApiOperation("设备信息二维码")
    @GetMapping("/qr")
    public ApiResult<?> qr(TowerEquipmentParam equipmentParam) throws IOException, WxErrorException {
//        WxLoginController wxLoginController = new WxLoginController();
//        String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + wxLoginController.getAccessToken();
//        JSONObject paramJson = new JSONObject();
//        paramJson.put("path", "otherPages/pages/equipment");
//        paramJson.put("scene",towerEquipmentParam.getEquipmentId());
//        URL url = new URL(apiUrl);
//        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//        httpURLConnection.setRequestMethod("POST");// 提交模式
//        // 发送POST请求必须设置如下两行
//        httpURLConnection.setDoOutput(true);
//        httpURLConnection.setDoInput(true);
//        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//        printWriter.write(paramJson.toString());
//        // flush输出流的缓冲
//        printWriter.flush();
//        //开始获取数据
//        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//        OutputStream os = new FileOutputStream(new File(savePath));
//        int len;
//        byte[] arr = new byte[1024];
//        while ((len = bis.read(arr)) != -1)
//        {
//            os.write(arr, 0, len);
//            os.flush();
//        }
//        os.close();
//        // 执行post请求
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("path", "otherPages/pages/equipment");
//        paramMap.put("scene", equipmentParam.getEquipmentId());
//        String post = HttpUtil.post(apiUrl, JSON.toJSONString(paramMap));
//        JSONObject json = JSON.parseObject(post);
//        return success(json);
//        if (json.get("errcode").equals(0)) {
//        }
//        return null;
        String filepath = uploadPath + "qr";
        String filename = filepath + "/" + getLoginUserId().toString() + ".png";
        File checkFile = new File(filename);
        if (!checkFile.exists()) {
            WxLoginController wxLoginController = new WxLoginController();
            WxMaService wxMaService = wxLoginController.wxMaService();
            WxMaQrcodeService wxMaQrcodeService = new WxMaQrcodeServiceImpl(wxMaService);
            wxMaQrcodeService.createWxaCodeUnlimit(equipmentParam.getEquipmentId().toString(), "otherPages/pages/equipment", uploadPath);
        }
        return success(filename);
    }

}
