package com.neusoft.smart.pos.org.controller;

import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.org.persistent.domain.TableGroups;
import com.neusoft.smart.pos.org.persistent.mapper.TableGroupsMapper;
import com.neusoft.smart.pos.org.persistent.mapper.TablesMapper;
import com.neusoft.smart.pos.org.service.TableGroupService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/tableGroups")
public class TableGroupsController {

    @Resource
    TableGroupsMapper tableGroupsMapper;
    @Resource
    TablesMapper tablesMapper;

    @Resource
    TableGroupService tableGroupService;
    @Value("${smartPosPlatform.tables.wechat-redirect-url}")
    private String jumpUrl;

    @PostMapping
    public ResponseData insert(@RequestBody TableGroups record) {
        if (record.getGroupName().equals("大堂")) {
            return new ResponseData("500", "重复的组别");
        }
        tableGroupService.insert(record);
        return new ResponseData();
    }

    
    @GetMapping("/{id}")
    public ResponseData<TableGroups> selectById(@PathVariable("id") Integer id) {
        return new ResponseData<>(tableGroupsMapper.selectById(id));
    }

    @GetMapping("/shop/{shopId}")
    public ResponseData<List<TableGroups>> selectByShopId(@PathVariable("shopId") Integer shopId) {
        final List<TableGroups> tableGroups = tableGroupsMapper.selectByShopId(shopId);
        tableGroups.add(new TableGroups() {{
            setId(-1);
            setShopId(shopId);
            setGroupName("大堂");
        }});
        return new ResponseData<>(tableGroups);
    }

    @PutMapping
    public ResponseData updateById(TableGroups record) {
        if (record.getGroupName().equals("大堂")) {
            return new ResponseData("500", "重复的组别");
        }
        final int i = tableGroupsMapper.countByGroupName2(record.getGroupName(), record.getShopId(), record.getId());
        if (i > 0)
            return new ResponseData("500", "重复的组别");
        tableGroupsMapper.updateById(record);
        return new ResponseData();
    }

    @DeleteMapping("/{id}")
    public ResponseData deleteById(@PathVariable("id") Integer id) {
        int i = tablesMapper.countByGroup(id);
        if (i > 0) {
            return new ResponseData("500", "请先将桌移动到其他组");
        }
        tableGroupsMapper.deleteById(id);
        return new ResponseData();
    }

    @GetMapping("/jump/{id}")
    public void jump(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        response.sendRedirect(jumpUrl + id);
    }
}
