package com.ruoyi.pda.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.device.domain.BaseInfo;
import com.ruoyi.device.domain.RecordUse;
import com.ruoyi.device.service.IBaseInfoService;
import com.ruoyi.device.service.IRecordUseService;
import com.ruoyi.pda.domain.MyResult;
import com.ruoyi.pda.service.IPdaApiService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/api")
public class PdaApiController {
    @Autowired
    private IPdaApiService service;
    @Autowired
    private IBaseInfoService baseInfoService;

    @Autowired
    private IRecordUseService recordUseService;

    @PostMapping("/home/selectDeviceInfo")
    public AjaxResult selectDeviceInfo(String code) {
        BaseInfo baseInfo = baseInfoService.selectDeviceInfo(code);
        if (baseInfo == null) return error("查询失败,条码扫描错误");
        String deviceState = baseInfo.getDeviceState();
        String deviceName = baseInfo.getDeviceName();
        if (deviceState.equals("0")) return error(deviceName + "已停用，使用其他设备吧");
        if (deviceState.equals("2")) return error(deviceName + "正在维修，使用其他设备吧");
        if (baseInfo.getUseState().equals("1")) return error(deviceName + "在使用中，更换其他设备吧");
        return success(baseInfo);
    }


    @PostMapping("/home/openDeviceLock")
    public AjaxResult openDeviceLock(@RequestBody BaseInfo baseInfo) {
        String deviceCode = baseInfo.getDeviceCode();
        String openPassword = baseInfo.getOpenPassword();

        ResponseEntity<String> response = null;
        try {
            RestTemplate restTemplate = new RestTemplate();
            // String url = "http://127.0.0.1:7789/devcontrolbusiness/unlock?idStr=" + deviceCode + "&password=" + openPassword;
            String url = "http://119.45.202.115:7789/devcontrolbusiness/unlock?idStr=" + deviceCode + "&password=" + openPassword;
            // 根据实际情况调整参数值
            response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                // {"code":200/500,"isSuc":true,"msg":"开锁指令下发成功，已收到设备回复","buffer":null,"data":null}
                MyResult myResult = JSONObject.parseObject(response.getBody(), MyResult.class);
                if (myResult.getCode() == 200) {
                    /**
                     * 插入记录
                     */
                    RecordUse recordUse = new RecordUse();
                    BeanUtils.copyProperties(baseInfo, recordUse);
                    recordUse.setDeviceId(String.valueOf(baseInfo.getObjId()));//设备ID
                    recordUse.setDeviceType(baseInfo.getTypeName());//设备类型
                    recordUse.setChargePrice(baseInfo.getDefaultPrice());//计费价格
                    recordUse.setUseState("1");
                    // 获取当前日期和时间
                    LocalDate now = LocalDate.now();
                    // 从LocalDate获取YearMonth
                    YearMonth currentYearMonth = YearMonth.from(now);
                    // 获取年份和月份
                    recordUse.setQueryYear(String.valueOf(currentYearMonth.getYear()));
                    recordUse.setQueryMonth(String.valueOf(currentYearMonth.getMonthValue()));
                    recordUseService.insertRecordUse(recordUse);
                    /**
                     * 修改基础信息
                     */
                    BaseInfo updateBaseInfo = new BaseInfo();
                    updateBaseInfo.setObjId(baseInfo.getObjId());
                    updateBaseInfo.setUseState("1");
                    baseInfoService.updateBaseInfoForApi(updateBaseInfo);
                    return success("开锁成功");
                } else {
                    return error(myResult.getMsg());
                }
            }
        } catch (RestClientException e) {
            return error("通讯失败");
        }

        return success("开锁成功");
    }

    @PostMapping("/record/selectUseList")
    public AjaxResult selectUseList() {
        List<RecordUse> list=service.selectUseList();
        return success(list);
    }


}
