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

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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.io.resource.ClassPathResource;
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 com.ruoyi.common.utils.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.studentChange.StudentInfoChange;
import yangtz.cs.liu.campus.domain.studentTurnover.StudentTurnover;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.service.studentTurnover.IStudentTurnoverService;
import yangtz.cs.liu.campus.util.TemplateExcelUtils;
import yangtz.cs.liu.campus.vo.schoolDuty.DownVacation;
import yangtz.cs.liu.campus.vo.studentTurnover.TurnoverVo;

import static yangtz.cs.liu.campus.constant.TurnoverConstant.*;

/**
 * 异动管理Controller
 *
 * @author wengxiulin
 * @date 2023-02-20
 */
@RestController
@RequestMapping("/studentTurnover")
public class StudentTurnoverController extends BaseController
{
    @Autowired
    private IStudentTurnoverService studentTurnoverService;

    @Autowired
    private ISchoolClassService classService;

    @Autowired
    private ISchoolStudentService studentService;

    /**
     * 查询异动管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StudentTurnover studentTurnover)
    {
        startPage();
        List<StudentTurnover> list = studentTurnoverService.selectStudentTurnoverList(studentTurnover);
        return getDataTable(list);
    }

    /**
     * 导出异动管理列表
     */
    @Log(title = "异动管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentTurnover studentTurnover)
    {
        List<StudentTurnover> list = studentTurnoverService.selectStudentTurnoverList(studentTurnover);
        ExcelUtil<StudentTurnover> util = new ExcelUtil<StudentTurnover>(StudentTurnover.class);
        util.exportExcel(response, list, "异动管理数据");
    }

    /**
     * 获取异动管理详细信息
     */
    @GetMapping(value = "/queryById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        return AjaxResult.success(studentTurnoverService.queryInfo(id));
    }

    /**
     * 新增异动管理
     */
    @Log(title = "异动管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody StudentTurnover studentTurnover)
    {
        studentTurnover.setState(SPZ);
        studentTurnover.insert();
        return toAjax(studentTurnoverService.save(studentTurnover));
    }

    /**
     * 修改异动管理
     */
    @Log(title = "异动管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody StudentTurnover studentTurnover)
    {
        return toAjax(studentTurnoverService.updateStudentTurnover(studentTurnover));
    }

    /**
     * 删除异动管理
     */
    @Log(title = "异动管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(studentTurnoverService.deleteStudentTurnoverByIds(ids));
    }

    /**
     * 终止
     */
    @Log(title = "异动管理", businessType = BusinessType.UPDATE)
    @PutMapping("/termination/{id}")
    public AjaxResult termination(@PathVariable Long id)
    {
        LambdaUpdateWrapper<StudentTurnover> luw = new LambdaUpdateWrapper<>();
        luw.eq(StudentTurnover :: getId,id).set(StudentTurnover::getState,ZZ);
        return toAjax(studentTurnoverService.update(luw));
    }

    /**
     * 办结
     */
    @Log(title = "异动管理", businessType = BusinessType.UPDATE)
    @PutMapping("/finish/{id}")
    public AjaxResult finish(@PathVariable Long id,  String dataUrl,String dataName)
    {
        /*if(StringUtils.isNull(dataUrl)){
            throw new ServiceException("图片路径为空");
        }
        if(StringUtils.isNull(dataName)){
            throw new ServiceException("图片名称为空");
        }*/
        LambdaUpdateWrapper<StudentTurnover> luw = new LambdaUpdateWrapper<>();
        luw
                .eq(StudentTurnover :: getId,id)
                .set(StudentTurnover::getState,BJ)
                .set(StudentTurnover::getDataUrl,dataUrl)
                .set(StudentTurnover::getDataName,dataName)
                .set(StudentTurnover::getEndTime, DateUtils.getNowDate());
        studentTurnoverService.update(luw);
        //学生异动信息
        StudentTurnover turnover = studentTurnoverService.getById(id);
         //已办结则修改对应学生的状态
        SchoolStudent student = studentService.getById(turnover.getStudentId());
        //如果是转出或转出借读
        if("2".equals(turnover.getChangeType()) || "3".equals(turnover.getChangeType())){
            //修改学生状态为其他
            student.setStudentStatus("6");
        }
        //如果是退学/注销学籍
        if("4".equals(turnover.getChangeType())){
            student.setStudentStatus("5");
        }
        //如果是退学/注销学籍
        if("5".equals(turnover.getChangeType())){
            student.setStudentStatus("2");
        }
        //如果是退学/注销学籍
        if("6".equals(turnover.getChangeType())){
            student.setStudentStatus("1");
        }
        return toAjax(studentService.updateById(student));
    }

    /**
     * 下载
     */
    @PostMapping("/download/{id}")
    public void download(@PathVariable Long id,HttpServletResponse response)
    {
        StudentTurnover turnover = studentTurnoverService.getById(id);
        //处理申请时间
        String dateString = DateUtils.formatDate(turnover.getApplyTime());
        //处理出生年月
        String birth = DateUtils.formatDate(turnover.getBirthday());
        //处理性别
        if("0".equals(turnover.getSex())){
            turnover.setSex("男");
        }else{
            turnover.setSex("女");
        }
        //处理变更类型
        if("0".equals(turnover.getChangeType())){
            turnover.setChangeType("A转入");
        } else if ("1".equals(turnover.getChangeType())) {
            turnover.setChangeType("B转入借读");
        }else if ("2".equals(turnover.getChangeType())) {
            turnover.setChangeType("C转出");
        }else if ("3".equals(turnover.getChangeType())) {
            turnover.setChangeType("D转出借读");
        }else if ("4".equals(turnover.getChangeType())) {
            turnover.setChangeType("E退学");
        }else if ("5".equals(turnover.getChangeType())) {
            turnover.setChangeType("F休学");
        }else if ("6".equals(turnover.getChangeType())) {
            turnover.setChangeType("G复学");
        }
        //处理是否保留学籍
        if("0".equals(turnover.getIsSave())){
            turnover.setIsSave("是");
        }else{
            turnover.setIsSave("否");
        }
        //获取班级
        SchoolClass c = classService.getById(turnover.getClassId());
        Workbook workbook = null;
        try {
            TemplateExportParams params = new TemplateExportParams(TemplateExcelUtils.convertTemplatePath("template/turnover.xlsx"));

            Map<String, Object> finalMap = new HashMap<String, Object>();
            finalMap.put("dateString",dateString);
            finalMap.put("studentName",turnover.getStudentName());
            finalMap.put("sex",turnover.getSex());
            finalMap.put("birth",birth);
            finalMap.put("classAlias",c.getClassAlias());
            finalMap.put("nationalNumber",turnover.getNationalNumber());
            finalMap.put("idCard",turnover.getIdCard());
            finalMap.put("parentName",turnover.getParentName());
            finalMap.put("homeAddress",turnover.getHomeAddress());
            finalMap.put("telephone",turnover.getTelephone());
            finalMap.put("changeType",turnover.getChangeType());
            finalMap.put("turnSchool",turnover.getTurnSchool());
            finalMap.put("isSave",turnover.getIsSave());

            workbook = ExcelExportUtil.exportExcel(params, finalMap);
            // 设置字符编码
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
            // 设置文本内省
            response.setContentType("application/vnd.ms-excel");
            response.flushBuffer();
            workbook.write(response.getOutputStream());
            response.setHeader("Content-Length", String.valueOf(response.getOutputStream().toString().length()));
        } catch (Exception e) {
            throw new ServiceException("下载出错");
        }finally {
            if (workbook!=null){
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**查看页面 下载上传的图片*/
    @PostMapping("/downloadPic/{id}")
    @ResponseBody
    public void downloadPic(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        StudentTurnover turnover = studentTurnoverService.getById(id);

        //文件绝对路径
        String filePath = turnover.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());
    }
}
