package com.app.service.basics;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.dto.PageResult;
import com.app.dto.basics.ResponseTeacherDto;
import com.app.dto.basics.SaveTeacherDto;
import com.app.dto.basics.search.SaveTeacherTagDto;
import com.app.dto.basics.search.SearchTeacherDto;
import com.app.entity.basics.Teacher;
import com.app.mapper.basics.TeacherMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

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

/**
 * 功能描述：学校
 *
 * @Auther: 梁展鹏
 * @Date: 2018/7/24 11:38
 */
@Slf4j
@Service
public class TeacherService {

    @Autowired
    private TeacherMapper mapper;

    public PageResult<SaveTeacherTagDto> page(SearchTeacherDto params) {
        List<SaveTeacherTagDto> list = new ArrayList();
        IPage<ResponseTeacherDto> page = mapper.getList(params, new Page(params.getPage(), params.getSize()));
        for (ResponseTeacherDto responseTeacherDto : page.getRecords()) {
            SaveTeacherTagDto _responseTeacherPageDto = new SaveTeacherTagDto();
            BeanUtils.copyProperties(responseTeacherDto, _responseTeacherPageDto);
            List<String> strings = JSONObject.parseArray(responseTeacherDto.getTag(), String.class);
            _responseTeacherPageDto.setTag(strings);
            list.add(_responseTeacherPageDto);
        }

        return new PageResult(params.getPage(), params.getSize(), page.getTotal(), list);
    }

    public void saveOrUpdate(SaveTeacherDto teacher) {
        Teacher _teacher = new Teacher();
        BeanUtils.copyProperties(teacher, _teacher);
        if (StringUtils.isEmpty(teacher.getId())) {
            if (!ObjectUtils.isEmpty(teacher.getTag())) {
                JSONArray array = JSONArray.parseArray(JSON.toJSONString(teacher.getTag()));
                _teacher.setTag(array.toString());
            }

            mapper.insert(_teacher);
        } else {
            Teacher teacher1 = mapper.selectById(teacher.getId());
            BeanUtils.copyProperties(teacher, teacher1);
            if (!ObjectUtils.isEmpty(teacher.getTag())) {
                JSONArray array = JSONArray.parseArray(JSON.toJSONString(teacher.getTag()));
                _teacher.setTag(array.toString());
            }

            mapper.updateById(_teacher);
        }
    }

}
