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

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.organization.SchoolOrganizationInfo;
import yangtz.cs.liu.campus.domain.schoolEquipment.SchoolEquipmentLedger;
import yangtz.cs.liu.campus.domain.student.SchoolStudentEvaluate;
import yangtz.cs.liu.campus.domain.teacherFiles.SchoolTeacherBasicInformation;
import yangtz.cs.liu.campus.domain.teacherFiles.SchoolTeacherBasiclnExport;
import yangtz.cs.liu.campus.domain.teacherFiles.TeacherFiles;
import yangtz.cs.liu.campus.service.impl.teacherFiles.IdCardNumberUtils;
import yangtz.cs.liu.campus.service.teacherFiles.SchoolTeacherBasichlnformationService;
import yangtz.cs.liu.campus.vo.schoolClass.SchoolClassDrVo;
import yangtz.cs.liu.wechat.controller.api.WxApiController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher/basiclnformation")
public class SchoolTeacherBasiclnformationController extends BaseController {

    private Logger log = LoggerFactory.getLogger(SchoolTeacherBasiclnformationController.class);

    @Autowired
    private SchoolTeacherBasichlnformationService basichlnformationService;


    /**
     * 获取老师基本信息列表
     * @param information
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolTeacherBasicInformation information) throws  Exception{
        startPage();
        List<SchoolTeacherBasicInformation> list = basichlnformationService.list(information);
        return getDataTable(list);
    }

    /**
     * 获取详情
     */
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable("id") Long id ) throws Exception{
        return AjaxResult.success(basichlnformationService.getById(id));
    }

    /**
     * 新增老师信息
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolTeacherBasicInformation information){

        //出生年月日获取
        String birthDayFromIdCard = IdCardNumberUtils.getBirthDayFromIdCard(information.getIdCard());
        information.setBirthDate(birthDayFromIdCard);
        //性别获取
        Map<String, Object> sexFromIdCard = IdCardNumberUtils.getSexFromIdCard(information.getIdCard());
        Integer sex = (Integer) sexFromIdCard.get(IdCardNumberUtils.SEX_BY_INT_MAP_KEY);
        if (sex == 1){
            information.setSex("0");
        }else {
            information.setSex("1");
        }
        return AjaxResult.success(basichlnformationService.save(information));
    }

    /**
     * 修改老师信息
     */
    @PutMapping("/update")
    public AjaxResult update(@RequestBody SchoolTeacherBasicInformation information){
        return AjaxResult.success(basichlnformationService.updateById(information));
    }

    /**
     * 删除信息
     */
    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable Long[] ids){
        List<Long> list = Arrays.asList(ids);
        boolean b = basichlnformationService.removeByIds(list);
        return AjaxResult.success(b);
    }

    @GetMapping(value = "/download")
    public void downloadFile(HttpServletResponse response) throws Exception {
        // 以流的形式下载文件。
        try {
            //读取文件
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/教师基础信息导入模板.xlsx");
            InputStream fis = new BufferedInputStream(resourceAsStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("教师基础信息导入模板.xlsx", "utf-8"));
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        List<SchoolTeacherBasicInformation> schoolTeacherBasicInformations = basichlnformationService.importExcel(file);
        for (SchoolTeacherBasicInformation date : schoolTeacherBasicInformations){
            //1.处理出生日期
            String birthDayFromIdCard = IdCardNumberUtils.getBirthDayFromIdCard(date.getIdCard());
            date.setBirthDate(birthDayFromIdCard);
            //2.处理性别
            Map<String, Object> sexFromIdCard = IdCardNumberUtils.getSexFromIdCard(date.getIdCard());
            Integer sex = (Integer) sexFromIdCard.get(IdCardNumberUtils.SEX_BY_INT_MAP_KEY);
            if (sex == 1){
                date.setSex("0");
            }else {
                date.setSex("1");
            }
        }
        boolean b = basichlnformationService.saveBatch(schoolTeacherBasicInformations);
        return AjaxResult.success(b);
    }


    /**
     * 导出
     *
     * @param
     * @return
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody SchoolTeacherBasiclnExport export ) throws Exception{
        List<SchoolTeacherBasicInformation> list = new ArrayList<>();
        List<SchoolTeacherBasiclnExport> exportList = new ArrayList<>();
        ExcelUtil<SchoolTeacherBasiclnExport> util = new ExcelUtil<>(SchoolTeacherBasiclnExport.class);

        if (null != export.getIds()){
            //1.当前为选中导出
            for (int i = 0 ; i < export.getIds().length;i++){
                SchoolTeacherBasicInformation byId = basichlnformationService.getById(export.getIds()[i]);
                list.add(byId);
            }
            //复制一份
            list.stream().forEach(date->{
                SchoolTeacherBasiclnExport schoolTeacherBasiclnExport = new SchoolTeacherBasiclnExport();
                BeanUtils.copyProperties(date,schoolTeacherBasiclnExport);
                exportList.add(schoolTeacherBasiclnExport);
            });
            util.exportExcel(response, exportList, "教师基本信息");

        }else if (null != export.getId()){
            //单条导出
            SchoolTeacherBasicInformation byId = basichlnformationService.getById(export.getId());
            SchoolTeacherBasiclnExport schoolTeacherBasiclnExport = new SchoolTeacherBasiclnExport();
            BeanUtils.copyProperties(byId,schoolTeacherBasiclnExport);
            exportList.add(schoolTeacherBasiclnExport);
            util.exportExcel(response, exportList, "教师基本信息");
        }else {
            //全部导出，条件导出
            LambdaQueryWrapper<SchoolTeacherBasicInformation> wrapper = Wrappers.lambdaQuery();
            //学科
            wrapper.eq(StringUtils.isNotEmpty(export.getTeachingSubject()),SchoolTeacherBasicInformation::getTeachingSubject,export.getTeachingSubject());
            //姓名
            wrapper.like(StringUtils.isNotEmpty(export.getName()),SchoolTeacherBasicInformation::getName,export.getName());
            //性别
            wrapper.eq(StringUtils.isNotEmpty(export.getSex()),SchoolTeacherBasicInformation::getSex,export.getSex());
            //政治面貌
            wrapper.eq(StringUtils.isNotEmpty(export.getPoliticalLandscape()),SchoolTeacherBasicInformation::getPoliticalLandscape,export.getPoliticalLandscape());
            //现职称
            wrapper.like(StringUtils.isNotEmpty(export.getCurrentProfessionalTitle()),SchoolTeacherBasicInformation::getCurrentProfessionalTitle,export.getCurrentProfessionalTitle());
            //在岗情况
            wrapper.eq(StringUtils.isNotEmpty(export.getOnDutySituation()),SchoolTeacherBasicInformation::getOnDutySituation,export.getOnDutySituation());
            //毕业院校
            if (StringUtils.isNotEmpty(export.getGraduationInstitution1())){
                wrapper.and(w->w.like(SchoolTeacherBasicInformation::getGraduationInstitution1,export.getGraduationInstitution1())
                        .or()
                        .like(SchoolTeacherBasicInformation::getGraduationInstitution2,export.getGraduationInstitution1())
                        .or()
                        .like(SchoolTeacherBasicInformation::getGraduationInstitution3,export.getGraduationInstitution1())
                );
            }
            //学历
            if (StringUtils.isNotEmpty(export.getFirstDegree())) {
                wrapper.and(w->w.like(SchoolTeacherBasicInformation::getFirstDegree,export.getFirstDegree())
                        .or()
                        .like(SchoolTeacherBasicInformation::getLastDegree,export.getFirstDegree()));
            }
            //查询出来结果复制
            List<SchoolTeacherBasicInformation> list1 = basichlnformationService.list(wrapper);
            list1.forEach(date->{
                SchoolTeacherBasiclnExport schoolTeacherBasiclnExport = new SchoolTeacherBasiclnExport();
                BeanUtils.copyProperties(date,schoolTeacherBasiclnExport);
                exportList.add(schoolTeacherBasiclnExport);
            });
            util.exportExcel(response, exportList, "教师基本信息");
        }
    }
}
