package com.huashe.park.application.web.controller.cons;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.huashe.common.domain.AjaxResult;
import com.huashe.park.common.i18n.MessageUtils;
import com.huashe.park.core.redis.RedisProxy;
import com.huashe.park.core.service.IPileHoleIndexRealtimeService;
import com.huashe.park.core.service.IPileMachineInfoService;
import com.huashe.park.domain.dto.cons.MachineBiz;
import com.huashe.park.domain.dto.cons.MachineLogin;
import com.huashe.park.domain.dto.cons.PileMachineVO;
import com.huashe.park.domain.entity.PileMachineInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;

import cn.hutool.core.bean.BeanUtil;

/**
 * 施工桩机信息Controller
 * 
 * @author ruoyi
 * @date 2025-02-12
 */
@RestController
@RequestMapping("/cons/pileMachineInfo")
public class PileMachineInfoController extends BaseController {
    @Autowired
    private IPileMachineInfoService pileMachineInfoService;

    @Autowired
    private IPileHoleIndexRealtimeService pileHoleIndexRealtimeService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisProxy redisProxy;

    /**
     * 查询施工桩机信息列表
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(PileMachineInfo pileMachineInfo) {
        startPage();
        List<PileMachineInfo> list = pileMachineInfoService.selectPileMachineInfoList(pileMachineInfo);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:list')")
    @GetMapping("/list/all")
    public TableDataInfo listAll(PileMachineInfo pileMachineInfo) {
        List<PileMachineInfo> list = pileMachineInfoService.selectPileMachineInfoList(pileMachineInfo);
        return getDataTable(list);
    }

    /**
     * 导出施工桩机信息列表
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:export')")
    @Log(title = "施工桩机信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PileMachineInfo pileMachineInfo) {
        List<PileMachineInfo> list = pileMachineInfoService.selectPileMachineInfoList(pileMachineInfo);
        ExcelUtil<PileMachineInfo> util = new ExcelUtil<PileMachineInfo>(PileMachineInfo.class);
        util.exportExcel(response, list, "施工桩机信息数据");
    }

    /**
     * 获取施工桩机信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(pileMachineInfoService.selectPileMachineInfoById(id));
    }

    /**
     * 新增施工桩机信息
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:add')")
    @Log(title = "施工桩机信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PileMachineInfo pileMachineInfo) {
        return toAjax(pileMachineInfoService.insertPileMachineInfo(pileMachineInfo));
    }

    /**
     * 修改施工桩机信息
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:edit')")
    @Log(title = "施工桩机信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PileMachineInfo pileMachineInfo) {
        return toAjax(pileMachineInfoService.updatePileMachineInfoWidthPwd(pileMachineInfo));
    }

    @PostMapping("/terminal/test")
    @Anonymous
    public void test() {
        redisProxy.putMapToHash("test", BeanUtil.beanToMap(new MachineBiz()), 10000);
        redisProxy.putHash("test", "designId", "123");
    }

    @PostMapping("/terminal/login")
    @Anonymous
    public AjaxResult login(@RequestBody MachineLogin machineAuth) {
        if (StringUtils.isEmpty(machineAuth.getSn()) || StringUtils.isEmpty(machineAuth.getPwd())) {
            return AjaxResult.error(MessageUtils.message("machine.auth.param.error"));
        }
        PileMachineInfo param = new PileMachineInfo();
        param.setSn(machineAuth.getSn());
        if (StringUtils.isNotEmpty(machineAuth.getNo())) {
            param.setNo(machineAuth.getNo());
        }
        List<PileMachineInfo> pileMachineInfos = pileMachineInfoService.selectPileMachineInfoList(param);
        if (CollectionUtils.isEmpty(pileMachineInfos)) {
            return AjaxResult.error(MessageUtils.message("machine.auth.param.none"));
        }
        PileMachineInfo pileMachineInfo = pileMachineInfos.get(0);
        if (!pileMachineInfo.getPwd().equals(machineAuth.getPwd())) {
            return AjaxResult.error(MessageUtils.message("machine.auth.param.none"));
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            pileMachineInfo.getSn(), pileMachineInfo.getPwd());
        authenticationToken.setDetails(pileMachineInfo);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        SysUser sysUser = new SysUser();
        sysUser.setTenantId(pileMachineInfo.getTenantId());
        machineAuth.setUser(sysUser);
        String token = tokenService.createToken(machineAuth);
        pileMachineInfo.setToken(token);
        PileMachineVO pileMachineInfoVo = new PileMachineVO();
        BeanUtil.copyProperties(pileMachineInfo, pileMachineInfoVo);
        // 生成token
        return AjaxResult.success(pileMachineInfoVo);
    }

    @GetMapping("/terminal/workSection")
    public AjaxResult machineWorkSection(@RequestParam String machineId) {
        return AjaxResult.success(pileMachineInfoService.qryMachineAssignedUnit(machineId));
    }

    @GetMapping("/terminal/constructionTargetObject")
    public AjaxResult constructionTargetObject(@RequestParam String machineId, @RequestParam String designId) {
        return AjaxResult.success(pileMachineInfoService.machineUnitPileHole(new MachineBiz() {
            {
                setDesignId(designId);
                setMachineId(machineId);
            }
        }));
    }

    /**
     * Qry machine on offline ajax result.
     *
     * @return the ajax result
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:list')")
    @GetMapping("/screen/onOffline")
    public AjaxResult qryMachineOnOffline() {
        return AjaxResult.success(pileMachineInfoService.cntMachineOnOffline());
    }

    /**
     * Qry machine by cons unit id ajax result.
     *
     * @param consUnitId the cons unit id
     * @return the ajax result
     */
    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:list')")
    @GetMapping("/screen/consunit/machine")
    public AjaxResult qryMachineByConsUnitId(@Param("consUnitId") Long consUnitId) {
        return AjaxResult.success(pileMachineInfoService.selectMachineByConsUnitId(consUnitId));
    }

    @PreAuthorize("@ss.hasPermi('cons:pileMachineInfo:list')")
    @GetMapping("/screen/machine/latest")
    public AjaxResult qryMachineLatestIndex(@Param("machineId") Long machineId) {
        return AjaxResult.success(pileHoleIndexRealtimeService.selectMachineLatestIndex(machineId));
    }

    @Log(title = "施工桩机", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id) {
        return toAjax(pileMachineInfoService.deletePileMachineInfoById(id));
    }
}
