package com.jpsoft.shinestar.modules.base.controller;


import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CanteenDevice;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.service.CanteenDeviceService;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/base/canteenDeviceRelation")
@Api(description = "食堂设备关联")
public class CanteenDeviceRelationController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private CanteenDeviceService canteenDeviceService;

    @ApiOperation(value="添加设备和人员绑定")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("add")
    public MessageResult<CanteenDevice> add(@RequestBody CanteenDevice canteenDevice, @RequestAttribute String subject){
        MessageResult<CanteenDevice> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            CanteenDevice item = canteenDeviceService.findByDeviceIdAndCanteenId(canteenDevice.getDeviceId(), canteenDevice.getCanteenId());

            if(item == null) {
                canteenDevice.setId(UUID.randomUUID().toString());
                canteenDevice.setDelFlag(false);
                canteenDevice.setCreateBy(subject);
                canteenDevice.setCreateTime(new Date());

                affectCount = canteenDeviceService.insert(canteenDevice);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(canteenDevice);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(ex.getMessage(),ex);
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="解除关联")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("unbindDevice")
    public MessageResult<Integer> unbindDevice(@RequestBody CanteenDevice canteenDevice,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            CanteenDevice item = canteenDeviceService.findByDeviceIdAndCanteenId(canteenDevice.getDeviceId(), canteenDevice.getCanteenId());

            if(item != null) {
                item.setDelFlag(true);
                item.setUpdateBy(subject);
                item.setUpdateTime(new Date());

                affectCount = canteenDeviceService.update(item);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库修改失败");
            }
        }
        catch(Exception ex){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(ex.getMessage(),ex);
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="食堂查询是否绑定设备")
    @RequestMapping(value = "isUnbindDeviceList",method = RequestMethod.POST)
    public MessageResult<Map> isUnbindDeviceList(
            String canteenId,
            @RequestParam(value="deviceNo",defaultValue="") String deviceNo,
            @RequestParam(value="deviceName",defaultValue="") String deviceName,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,@RequestAttribute String subject){

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        searchParams.put("scene","%4%");//类型为4的设备，为食堂用设备

        if(StringUtils.isNotEmpty(deviceNo)){
            searchParams.put("deviceNo","%" + deviceNo + "%");
        }
        if(StringUtils.isNotEmpty(deviceName)){
            searchParams.put("aliasName","%" + deviceName + "%");
        }

        List<Sort> sortList = new ArrayList<>();

        if(canteenId != null){
            searchParams.put("isBoundCanteenId",canteenId);
        }

        sortList.add(new Sort("is_online","desc"));
        sortList.add(new Sort("create_time","desc"));

        Page<DeviceInfo> page = deviceInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        for (DeviceInfo deviceInfo:page) {
            String typeN = dataDictionaryService.findNameByCatalogNameAndValue("设备类型",deviceInfo.getType());
            deviceInfo.setTypeN(typeN);
        }

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;

    }
}
