package com.th.demo.service.impl.maint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.th.demo.mapping.maint.WareMapper;
import com.th.demo.model.maint.Ware;
import com.th.demo.model.system.Type;
import com.th.demo.service.maint.WareService;
import com.th.demo.tools.JSONTools;
import com.th.demo.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("WareService")
public class WareServiceImpl implements WareService {

    @Autowired//自动注入Mapper
    public WareMapper wareMapper;
    String result = Type.FAIL;
    int num = 0;

    @Override
    public String query(int page, int rows, String query, String userId, String belongId) {
        PageHelper.startPage(page, rows);

        List<Ware> list = wareMapper.select(query, belongId);

        PageInfo<Ware> pageInfo = new PageInfo<>(list);
        result = JSONTools.toString(pageInfo);
        return result;
    }

    @Override
    public String save(String json, String userId, String belongId) {
        result = Type.FAIL;
        Ware ware = JSON.parseObject(json, new TypeReference<Ware>() {
        });
        if (ware.getId() == null || ware.getId().equals("")) {
            ware.setAddId(userId);
            ware.setAddTime(new Date());
            ware.setModifyId(userId);
            ware.setModifyTime(new Date());
            ware.setCancelFlag("0");
            ware.setBelongId(belongId);
            num = wareMapper.insert(ware);
        } else {
            ware.setModifyId(userId);
            ware.setModifyTime(new Date());
            num = wareMapper.updateByPrimaryKey(ware);
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;
    }


    @Override
    public String remove(String id, String userId) {
        Ware ware = wareMapper.selectByPrimaryKey(id);
        ware.setCancelFlag("9");
        ware.setCancelId(userId);
        ware.setCancelTime(new Date());
        num = wareMapper.updateByPrimaryKey(ware);
        result = Tools.moreThanZeroResultJSON(num);
        return result;

    }

    @Override
    public String queryAll(String userId, String belongId) {
        List<Ware> list = wareMapper.selectAll(belongId);
        result = JSONTools.toString(list);
        return result;
    }

    @Override
    public String queryByUserId(String userId, String belongId) {
        List<Ware> list = wareMapper.selectByUserId(userId,belongId);
        result = JSONTools.toString(list);
        return result;
    }

    @Override
    public String queryWare(String userId, String belongId) {
        List<Ware> list = wareMapper.selectWare(userId,belongId);
        result = JSONTools.toString(list);
        return result;
    }
}
