package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.jsc.oscm.entity.TargetSocial;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.TargetSocialService;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class TargetSocialController {

    @Resource
    TargetSocialService targetSocialService;


    @PostMapping({"/target/social/add", "/target/social/update", "/open/target/social/update"})
    public String updateTargetSocial(@RequestBody TargetSocial targetSocial) {
        ReturnT<String> returnT;
        if (targetSocialService.save(targetSocial)) {
            returnT = new ReturnT<>(200, "", "");
        } else {
            returnT = new ReturnT<>(500, "用户信息更新失败", "");
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping({"/target/social/delete"})
    public String deleteTargetSocial(@RequestBody TargetSocial targetSocial) {
        ReturnT<String> returnT;
        if (targetSocialService.deleteById(targetSocial.getId())) {
            returnT = new ReturnT<>(200, "", "");
        } else {
            returnT = new ReturnT<>(500, "用户删除失败", "");
        }
        return JSON.toJSONString(returnT);
    }


    @PostMapping("/open/target/social/queryAll")
    public String queryAll(@RequestBody TargetSocial targetSocial,
                           @Param(value = "sortBy") String sortBy,
                           @Param(value = "shuffleResult") Boolean shuffleResult) {
        ReturnT<List<TargetSocial>> returnT;
        try {
            returnT = new ReturnT<>(200, String.valueOf(targetSocialService.queryCount(targetSocial)),
                    targetSocialService.queryAll(targetSocial, sortBy, shuffleResult));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping({"/target/social/queryPageable/{pageIndex}/{pageSize}"})
    public String queryPageable(@PathVariable(value = "pageIndex") int pageIndex,
                                @PathVariable(value = "pageSize") int pageSize,
                                @RequestBody TargetSocial targetSocial) {
        ReturnT<List<TargetSocial>> returnT;
        try {
            returnT = new ReturnT<>(200, String.valueOf(targetSocialService.queryCount(targetSocial)),
                    targetSocialService.queryPageable(pageIndex, pageSize, targetSocial));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

}
