package com.gyee.frame.controller.ticket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gyee.frame.common.dataSources.DataSource;
import com.gyee.frame.common.dataSources.DataSourceType;
import com.gyee.frame.common.domain.AjaxResult;
import com.gyee.frame.model.ticket.TokenUser;
import com.gyee.frame.model.ticket.Wobugeq;
import com.gyee.frame.service.ticket.ShiroService;
import com.gyee.frame.service.ticket.WobugeqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenmh
 * @since 2020-06-02
 */
@RestController
@RequestMapping("/wobugeq")
public class WobugeqController {

    @Autowired
    WobugeqService wobugeqService;
    @Autowired
    ShiroService shiroService;

    /**
     * 分页查询工作票
     *
     * @param page
     * @return
     */
    @DataSource(value = DataSourceType.TICKET)
    @GetMapping(value = "list")
    public AjaxResult getList(@RequestHeader(value = "token") String header,
                              @RequestParam("page") Optional<Long> page) {
        TokenUser token = shiroService.findToken(header);
        Long pageNum = page.orElse(1L);

        IPage<Wobugeq> ticket = wobugeqService.selectPage(pageNum, token.getDepartment());
        if (ticket == null)
            return AjaxResult.error(4004, "数据读取异常");

        return AjaxResult.successData(ticket);
    }

    /**
     * 根据 id 查询详情
     *
     * @param id
     * @return
     */
    @DataSource(value = DataSourceType.TICKET)
    @GetMapping(value = "item")
    public AjaxResult getTicketItem(@RequestParam("id") String id) {
        Wobugeq ticket = wobugeqService.getById(id);
        if (ticket == null) {
            return AjaxResult.error(4004, "数据读取异常");
        }

        return AjaxResult.successData(ticket);
    }

    /**
     * 编辑ticket
     *
     * @param data
     * @return
     */
    @DataSource(value = DataSourceType.TICKET)
    @PostMapping(value = "edit")
    public AjaxResult editWorkTicket(@RequestParam("data") String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        Wobugeq ticket = JSON.toJavaObject(jsonObject, Wobugeq.class);
        if (ticket == null)
            return AjaxResult.error(4004, "数据更新失败");

        boolean result = wobugeqService.updateById(ticket);
        if (!result)
            return AjaxResult.error(4004, "数据更新失败");

        return AjaxResult.success("数据更新成功");
    }
}

