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

import com.github.pagehelper.Page;
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.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.AddressDevice;
import com.jpsoft.shinestar.modules.base.service.AddressDeviceService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
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 javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/addressDevice")
public class AddressDeviceController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AddressDeviceService addressDeviceService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<AddressDevice> add(@RequestBody AddressDevice addressDevice,@RequestAttribute String subject){
        MessageResult<AddressDevice> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            AddressDevice item = addressDeviceService.findByDeviceIdAndAddressId(addressDevice.getDeviceId(), addressDevice.getAddressId());

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

                affectCount = addressDeviceService.insert(addressDevice);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(addressDevice);
            } 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="获取信息")
    @GetMapping("detail/{id}")
    public MessageResult<AddressDevice> detail(@PathVariable("id") String id){
        MessageResult<AddressDevice> msgResult = new MessageResult<>();

        try {
            AddressDevice addressDevice = addressDeviceService.get(id);

            if (addressDevice != null) {
                msgResult.setResult(true);
                msgResult.setData(addressDevice);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<AddressDevice> update(@ModelAttribute AddressDevice addressDevice){
        MessageResult<AddressDevice> msgResult = new MessageResult<>();

        try {
            int affectCount = addressDeviceService.update(addressDevice);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(addressDevice);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<AddressDevice> delete(@PathVariable("id") String id){
        MessageResult<AddressDevice> msgResult = new MessageResult<>();

        try {
            int affectCount = addressDeviceService.delete(id);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete/{id}")
    public MessageResult<AddressDevice> batchDelete(@PathVariable("id") String id){
        MessageResult<AddressDevice> msgResult = new MessageResult<>();

        msgResult.setResult(false);
        msgResult.setMessage("未实现");

        return msgResult;
    }

    @ApiOperation(value="食堂查询是否绑定设备")
    @RequestMapping(value = "isUnbindDeviceList",method = RequestMethod.POST)
    public MessageResult<Map> isUnbindDeviceList(
            String addressId,
            @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","%3%");//类型为4的设备，为会议用设备

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

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

        if(addressId != null){
            searchParams.put("isBoundAddressId",addressId);
        }

        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;

    }


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

        try {
            int affectCount = 0;

            AddressDevice item = addressDeviceService.findByDeviceIdAndAddressId(addressDevice.getDeviceId(), addressDevice.getAddressId());

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

                affectCount = addressDeviceService.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;
    }
}
