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.CustomerAddressMapper;
import com.th.demo.mapping.maint.CustomerMapper;
import com.th.demo.mapping.maint.TransportMapper;
import com.th.demo.model.maint.Customer;
import com.th.demo.model.maint.CustomerAddress;
import com.th.demo.model.maint.Transport;
import com.th.demo.model.system.Type;
import com.th.demo.service.maint.TransportService;
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 org.springframework.transaction.annotation.Transactional;

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

@Service("TransportService")
public class TransportServiceImpl implements TransportService {

    @Autowired
    public TransportMapper transportMapper;


    String result = Type.FAIL;
    int num = 0;

    @Override
    public String query(int page, int rows, String query, String userId, String belongId) {
        List<Transport> list = new ArrayList<Transport>();

        list = transportMapper.selectByName(query, belongId);
        if(page ==-1 && rows==-1){
            result = JSONTools.toString(list);
        }else {
            PageHelper.startPage(page, rows);
            PageInfo<Transport> pageInfo = new PageInfo<>(list);
            result = JSONTools.toString(pageInfo);
        }

        return result;
    }

    @Override
    public String save(String json, String userId, String belongId) {
        result = Type.FAIL;
        Transport transport = JSON.parseObject(json, new TypeReference<Transport>() {
        });
        if (transport.getId() == null || transport.getId().equals("")) {
            List<Transport> transportList = transportMapper.selectByName(transport.getName(),belongId);
            if(transportList.size() == 0){
                transport.setCancelFlag("0");
                transport.setBelongId(belongId);
                num = transportMapper.insert(transport);
            }else {
                return JSONTools.toString(1,"承运单位已存在");
            }

        } else {

            num = transportMapper.updateByPrimaryKey(transport);
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;
    }


    @Override
    public String remove(String id, String userId) {

        num = transportMapper.deleteByPrimaryKey(id);
        result = Tools.moreThanZeroResultJSON(num);
        return result;

    }

}
