package com.shinsoft.sto.service.impl.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinsoft.sto.mapper.main.AreaMapper;
import com.shinsoft.sto.model.main.Area;
import com.shinsoft.sto.service.main.AreaService;
import com.shinsoft.tools.JSONTools;
import com.shinsoft.tools.model.common.ResultJSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 库房分区 服务实现类
 * </p>
 */
@Service
public class AreaServiceImp extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Autowired
    private AreaMapper areaMapper;

    ResultJSON resultJSON;

    @Override
    public ResultJSON query(int page, int rows, String wareId) {
        Page<Area> areaPage = new Page<>(page, rows);
        Page<Area> list = areaMapper.selectAreaPage(areaPage, wareId);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryByPK(String id) {
        Area area = areaMapper.selectById(id);
        resultJSON = JSONTools.toResultJSON(area);
        return resultJSON;
    }

    @Override
    public ResultJSON save(String userId, String json) {
        Date date = new Date();
        Area area = JSON.parseObject(json, new TypeReference<Area>() {
        });
        if (StringUtils.isEmpty(area.getId())) {
            area.setCancelFlag("0");
            area.setAddId(userId);
            area.setAddTime(date);
            areaMapper.insert(area);
        } else {
            area.setModifyId(userId);
            area.setModifyTime(date);
            areaMapper.updateById(area);
        }

        resultJSON = JSONTools.toResultJSON(area);
        return resultJSON;
    }

    @Override
    public ResultJSON remove(String userId, String id) {
        Date date = new Date();
        Area area = areaMapper.selectById(id);
        area.setCancelFlag("1");
        area.setModifyId(userId);
        area.setModifyTime(date);
        areaMapper.updateById(area);
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

    @Override
    public ResultJSON removeBatch(String userId, String ids) {
        Date date = new Date();
        List<String> list = JSON.parseObject(ids, new TypeReference<List<String>>() {
        });
        Area area;
        for (String id : list) {
            area = areaMapper.selectById(id);
            area.setCancelFlag("1");
            area.setModifyId(userId);
            area.setModifyTime(date);
            areaMapper.updateById(area);
        }
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }
}

