package com.bonus.material.ma.controller;

import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.log.enums.OperaType;
import com.bonus.material.basic.domain.BmQrcodeInfo;
import com.bonus.material.codeCollection.domain.WsMaInfo;
import com.bonus.material.common.annotation.PreventRepeatSubmit;
import com.bonus.material.ma.domain.MachineSynch;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.domain.vo.MachineVo;
import com.bonus.material.ma.domain.vo.SampleSync;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.material.ma.domain.Machine;
import com.bonus.material.ma.service.IMachineService;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 机具设备管理Controller
 *
 * @author xsheng
 * @date 2024-09-27
 */
@Api(tags = "机具设备管理接口")
@RestController
@RequestMapping("/ma_machine")
public class MachineController extends BaseController {

    @Autowired
    private IMachineService machineService;

    /**
     * 查询机具设备管理列表
     */
    @ApiOperation(value = "查询机具设备管理列表1")
    //@RequiresPermissions("ma:machine:list")
    @GetMapping("/list")
    public TableDataInfo list(Machine machine) {
        if (machine.getPrefix() == null) {
            startPage();
        }
        List<MachineVo> list = machineService.selectMachineList(machine);
        return getDataTable(list);
    }

    /**
     * todo 查询在库机具编号，存在数据拼接，盘点报废专用
     */
    @ApiOperation(value = "查询在库机具编号")
    //@RequiresPermissions("ma:machine:typeList")
    @GetMapping("/getMachineList")
    public AjaxResult getMachineList(Type type) {
        return machineService.getMachineList(type);
    }

    /**
     * 查询机具设备管理列表
     */
    @ApiOperation(value = "查询机具设备管理列表2")
    //@RequiresPermissions("ma:machine:typeList")
    @GetMapping("/getTypeList")
    public AjaxResult list(Type type) {
        return machineService.selectByTypeList(type);
    }

    /**
     * 导出机具设备管理列表
     */
    @ApiOperation(value = "导出机具设备管理列表")
    @PreventRepeatSubmit
    @RequiresPermissions("ma:machine:export")
    @SysLog(title = "机具设备管理", businessType = OperaType.EXPORT, logType = 1, module = "仓储管理->导出机具设备管理")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Machine machine) {
        List<MachineVo> list = machineService.selectMachineList(machine);
        ExcelUtil<MachineVo> util = new ExcelUtil<MachineVo>(MachineVo.class);
        util.exportExcel(response, list, "机具设备管理数据");
    }

    /**
     * 获取机具设备管理详细信息
     */
    @ApiOperation(value = "获取机具设备管理详细信息")
    @RequiresPermissions("ma:machine:query")
    @GetMapping(value = "/{maId}")
    public AjaxResult getInfo(@PathVariable("maId") Long maId) {
        return AjaxResult.success(machineService.selectMachineByMaId(maId));
    }

    /**
     * 获取机具设备管理详细信息
     *
     * @param machine
     * @return
     */
    @ApiOperation(value = "获取机具设备管理详细信息")
    //@RequiresPermissions("ma:machine:query")
    @GetMapping(value = "/getInfoByCode")
    public AjaxResult getInfoByMaCode(Machine machine) {
        try {
            return AjaxResult.success(machineService.getInfoByMaCode(machine));
        } catch (Exception e) {
            return error("查询失败，请联系管理员");
        }
    }

    /**
     * 新增机具设备管理
     */
    @ApiOperation(value = "新增机具设备管理")
    @PreventRepeatSubmit
    @RequiresPermissions("ma:machine:add")
    @SysLog(title = "机具设备管理", businessType = OperaType.INSERT, logType = 1, module = "仓储管理->新增机具设备管理")
    @PostMapping
    public AjaxResult add(@RequestBody Machine machine) {
        return toAjax(machineService.insertMachine(machine));
    }

    /**
     * 新增机具设备管理
     */
    @ApiOperation(value = "新增机具设备管理")
    @PreventRepeatSubmit
    @SysLog(title = "机具设备管理", businessType = OperaType.INSERT, logType = 1, module = "仓储管理->新增机具设备管理")
    @PostMapping(value = "/addMaMachine")
    public AjaxResult addMaMachine(@RequestBody Machine machine) {
        return machineService.addMaMachine(machine);
    }

    /**
     * 修改机具设备管理
     */
    @ApiOperation(value = "修改机具设备管理")
    @PreventRepeatSubmit
    @RequiresPermissions("ma:machine:edit")
    @SysLog(title = "机具设备管理", businessType = OperaType.UPDATE, logType = 1, module = "仓储管理->修改机具设备管理")
    @PutMapping
    public AjaxResult edit(@RequestBody Machine machine) {
        return machineService.updateMachine(machine);
    }

    /**
     * 修改机具设备状态
     */
    @ApiOperation(value = "修改机具设备状态")
    @PreventRepeatSubmit
//    @RequiresPermissions("ma:machine:editMachineStatus")
    @SysLog(title = "修改机具设备状态", businessType = OperaType.UPDATE, logType = 1, module = "仓储管理->修改机具设备状态")
    @PutMapping("/editMachineStatus")
    public AjaxResult editMachineStatus(@RequestBody Machine machine) {
        return machineService.editMachineStatus(machine);
    }

    /**
     * 删除机具设备管理
     */
    @ApiOperation(value = "删除机具设备管理")
    @PreventRepeatSubmit
    @RequiresPermissions("ma:machine:remove")
    @SysLog(title = "机具设备管理", businessType = OperaType.DELETE, logType = 1, module = "仓储管理->删除机具设备管理")
    @DeleteMapping("/{maId}")
    public AjaxResult remove(@PathVariable Long maId) {
        return machineService.deleteMachineByMaId(maId);
    }


    /**
     * 电子标签查询
     */
    @ApiOperation(value = "电子标签查询")
    @GetMapping("/getElectronicLabel")
    public AjaxResult getElectronicLabel(Machine machine) {
        return machineService.getElectronicLabel(machine);
    }

    /**
     * 电子标签编码查询
     *
     * @param machine
     * @return
     */
    @ApiOperation(value = "电子标签编码查询")
    @GetMapping("/getByMaCode")
    public AjaxResult getByMaCode(Machine machine) {
        try {
            return success(machineService.getByMaCode(machine));
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }
    /**
     * 电子标签编码查询接口
     *
     * @param machine
     * @return
     */
    @ApiOperation(value = "电子标签编码查询接口")
    @GetMapping("/getNewByMaCode")
    public AjaxResult getNewByMaCode(Machine machine) {
        try {
            return success(machineService.getNewByMaCode(machine));
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }
    /**
     * 电子标签编码查询接口
     *
     * @param machine
     * @return
     */
    @ApiOperation(value = "电子标签编码查询接口")
    @GetMapping("/findMaMsgById")
    public AjaxResult findMaMsgById(Machine machine) {
        try {
            return success(machineService.findMaMsgById(machine));
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 根据标签信息查询出库单
     *
     * @param leaseApplyInfo
     * @return
     */
    @ApiOperation(value = "获取领料出库单详细信息")
    //@RequiresPermissions("lease:info:query")
    @GetMapping(value = "/getInfoByMaId")
    public AjaxResult getInfoByMaId(LeaseApplyInfo leaseApplyInfo) {
        return success(machineService.getInfoByMaId(leaseApplyInfo));
    }

    @ApiOperation(value = "获取报告")
    @PostMapping("/getReport")
    public AjaxResult getReport(@RequestBody Machine machine) {
        try {
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建请求参数
            SortedMap<String, String> params = new TreeMap<>();
            params.put("code", "12");
            params.put("timeStamp", "12");
            params.put("reportNum", machine.getReportCode());
            params.put("sign", "12");

            // 创建请求实体
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    "https://skjc.dunchong.cc/skjc/app/doc/getInfoByReportCodeV1",
                    requestEntity,
                    String.class
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                // 将返回的JSON字符串转换为对象
                JSONObject jsonObject = JSON.parseObject(response.getBody());
                // 如果code等于1，返回空的reportResponse
                if ("1".equals(jsonObject.getString("code"))) {
                    return success(new Machine());
                }
                // 创建返回对象
                Machine reportResponse = new Machine();
                reportResponse.setNextCheckTimeSynch(jsonObject.getString("nextCheckTime"));
                reportResponse.setCheckTimeSynch(jsonObject.getString("checkTime"));
                reportResponse.setReportNum(jsonObject.getString("reportNum"));
                reportResponse.setReportName(jsonObject.getString("reportName"));
                reportResponse.setCode(jsonObject.getString("code"));
                reportResponse.setPdf(jsonObject.getString("pdf"));
                reportResponse.setSamples(jsonObject.getJSONArray("samples").toJavaList(SampleSync.class));
                return success(reportResponse);
            } else {
                return error("接口调用失败，状态码：" + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }


    /**
     * 检验报告同步
     */
    @ApiOperation(value = "检验报告同步")
    @PreventRepeatSubmit
    @PostMapping("/synchReport")
    public AjaxResult synchReport(@RequestBody Machine machine) {
        return machineService.synchReport(machine);
    }


    /**
     * 查询检验报告同步记录
     */
    @ApiOperation(value = "查询检验报告同步记录")
    //@RequiresPermissions("ma:machine:list")
    @GetMapping("/getSynchList")
    public TableDataInfo getSynchList(MachineSynch machine) {
            startPage();
        List<MachineSynch> list = machineService.selectSynchList(machine);
        return getDataTable(list);
    }


    @ApiOperation(value = "查询检验报告同步记录")
    //@RequiresPermissions("ma:machine:list")
    @GetMapping("/getSynchDetailList")
    public TableDataInfo getSynchDetailList(MachineSynch machine) {
        startPage();
        List<MachineSynch> list = machineService.selectSynchDetailList(machine);
        return getDataTable(list);
    }

    /**
     * 固定资产编号录入
     */
    @ApiOperation(value = "固定资产编号录入")
    @PreventRepeatSubmit
    @PostMapping("/editAssetsCode")
    public AjaxResult editAssetsCode(@RequestBody Machine machine) {
        return toAjax(machineService.editAssetsCode(machine));
    }

    /**
     * 根据qrcode查询机具历史信息
     *
     * @param machine
     * @return
     */
    @GetMapping("/getHisByQrcode")
    public AjaxResult getHisByQrcode(Machine machine) {
        return machineService.getHisByQrcode(machine);
    }

    /**
     * 根据qrcode查询机具历史信息 -- 外部专用
     */
    @GetMapping("/getHisByQrcodeNetwork")
    public AjaxResult getHisByQrcodeNetwork(Machine machine) {
        return machineService.getHisByQrcode(machine);
    }

    /**
     * 根据qrcode查询机具历史信息
     *
     * @param machine
     * @return
     */
    @GetMapping("/getHisByCode")
    public AjaxResult getHisByCode(Machine machine) {
        return machineService.getHisByCode(machine);
    }

    /**
     * 根据qrcode查询机具历史信息-New查询安全工器具和工器具
     *
     * @param machine
     * @return
     */
    @GetMapping("/getHisByCodeNew")
    public AjaxResult getHisByCodeNew(Machine machine) {
        return machineService.getHisByCodeNew(machine);
    }

    /**
     * 根据类型id获取编码
     *
     * @param machine
     * @return
     */
    @ApiOperation(value = "根据类型id获取编码")
    @GetMapping(value = "/getInfoByTypeId")
    public AjaxResult getInfoByTypeId(Machine machine) {
        try {
            startPage();
            List<Machine> list = machineService.getInfoByTypeId(machine);
            return AjaxResult.success(getDataTable(list));
        } catch (Exception e) {
            return error("查询失败，请联系管理员");
        }
    }

    @ApiOperation(value = "批量更新检验时间")
    @SysLog(title = "批量更新检验时间", businessType = OperaType.UPDATE, logType = 1, module = "设备管理->批量更新检验时间")
    @PostMapping("/updateDate")
    public AjaxResult updateDate(@RequestBody Machine info) {
        return machineService.updateDate(info);
    }
}
