package yangtz.cs.liu.campus.controller.studentChange;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.studentChange.StudentInfoChange;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.service.studentChange.IStudentInfoChangeService;

import static yangtz.cs.liu.campus.constant.TurnoverConstant.WTJ;
import static yangtz.cs.liu.campus.constant.TurnoverConstant.YTJ;

/**
 * 学生关键信息变更Controller
 *
 * @author wengxiulin
 * @date 2023-02-20
 */
@RestController
@RequestMapping("/studentChange")
public class StudentInfoChangeController extends BaseController
{
    @Autowired
    private IStudentInfoChangeService studentInfoChangeService;

    @Autowired
    private ISchoolStudentService studentService;

    /**
     * 查询学生关键信息变更列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StudentInfoChange studentInfoChange)
    {
        startPage();
        List<StudentInfoChange> list = studentInfoChangeService.selectStudentInfoChangeList(studentInfoChange);
        return getDataTable(list);
    }

    /**
     * 导出学生关键信息变更列表
     */
    @Log(title = "学生关键信息变更", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentInfoChange studentInfoChange)
    {
        List<StudentInfoChange> list = studentInfoChangeService.selectStudentInfoChangeList(studentInfoChange);
        ExcelUtil<StudentInfoChange> util = new ExcelUtil<StudentInfoChange>(StudentInfoChange.class);
        util.exportExcel(response, list, "学生关键信息变更数据");
    }

    /**
     * 获取学生关键信息变更详细信息
     */
    @GetMapping(value = "/queryById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(studentInfoChangeService.getById(id));
    }

    /**
     * 新增学生关键信息变更
     */
    @Log(title = "学生关键信息变更", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody StudentInfoChange studentInfoChange)
    {
        studentInfoChange.setState(WTJ);
        studentInfoChange.insert();
        return toAjax(studentInfoChangeService.save(studentInfoChange));
    }

    /**
     * 修改学生关键信息变更
     */
    @Log(title = "学生关键信息变更", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody StudentInfoChange studentInfoChange)
    {
        if (StringUtils.isNull(studentInfoChange.getId())){
            throw new ServiceException("id为空");
        }
        return toAjax(studentInfoChangeService.updateStudentInfoChange(studentInfoChange));
    }

    /**
     * 删除学生关键信息变更
     */
    @Log(title = "学生关键信息变更", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(studentInfoChangeService.deleteStudentInfoChangeByIds(ids));
    }

    /**提交*/
    @PutMapping("/submit/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submit(@PathVariable Long id)
    {
        if (StringUtils.isNull(id)){
            throw new ServiceException("id为空");
        }
        LambdaUpdateWrapper<StudentInfoChange> luw = new LambdaUpdateWrapper<>();
        luw.eq(StudentInfoChange::getId,id).set(StudentInfoChange::getState,YTJ).set(StudentInfoChange::getSubmitTime, DateUtils.getNowDate());
        boolean flag = studentInfoChangeService.update(luw);
        if(flag){
            StudentInfoChange change = studentInfoChangeService.getById(id);
            //判断身份证号是都已存在
            LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolStudent::getIdCard,change.getNewIdCard());
            SchoolStudent s = studentService.getOne(lqw);
            if(StringUtils.isNotNull(s)){
                //根据新身份证号可以查出对应学生，判断是本人还是别人
                if(change.getStudentId().equals(s.getId())){
                    //是本人
                    LambdaUpdateWrapper<SchoolStudent> l = new LambdaUpdateWrapper<>();
                    l.eq(SchoolStudent::getId,change.getStudentId())
                            .set(SchoolStudent::getStudentName,change.getNewStudentName())
                            .set(SchoolStudent::getIdCard,change.getNewIdCard())
                            .set(SchoolStudent::getNation,change.getNewNation());
                    return toAjax(studentService.update(l));
                }else {
                    throw new ServiceException("变更后的身份证号与他人重复，请检查");
                }
            }else {
                LambdaUpdateWrapper<SchoolStudent> l = new LambdaUpdateWrapper<>();
                l.eq(SchoolStudent::getId,change.getStudentId())
                        .set(SchoolStudent::getStudentName,change.getNewStudentName())
                        .set(SchoolStudent::getIdCard,change.getNewIdCard())
                        .set(SchoolStudent::getNation,change.getNewNation());
                return toAjax(studentService.update(l));
            }
        }
        return toAjax(flag);
    }

    /**详情页点击文件下载*/
    @PostMapping("/downloadFile/{id}")
    @ResponseBody
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        if (StringUtils.isNull(id)){
            throw new ServiceException("id为空");
        }

        StudentInfoChange change = studentInfoChangeService.getById(id);

        //文件绝对路径
        String filePath = change.getDataUrl();
        String uploadPath = RuoYiConfig.getUploadPath();
        String downPath = (uploadPath+filePath).replaceFirst("upload/profile/","");
        //String localPath = RuoYiConfig.getDownloadPath();
        // 下载名称
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, downPath);
        FileUtils.writeBytes(downPath, response.getOutputStream());
    }
}
