package com.ym.mec.web.controller;


import com.alibaba.fastjson.JSONObject;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
import com.ym.mec.biz.dal.dto.RepairGoodsDto;
import com.ym.mec.biz.dal.dto.StudentInstrumentExportDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.StudentInstrument;
import com.ym.mec.biz.dal.entity.StudentRegistration;
import com.ym.mec.biz.dal.entity.StudentRepair;
import com.ym.mec.biz.dal.page.StudentInstrumentQueryInfo;
import com.ym.mec.biz.service.StudentInstrumentService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("studentInstrument")
@Api(tags = "乐器与乐保服务")
@RestController
public class StudentInstrumentController extends BaseController {
    @Autowired
    private StudentInstrumentService studentInstrumentService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StudentInstrumentDao studentInstrumentDao;


    @ApiOperation(value = "乐器保养列表")
    @GetMapping("/getList")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/getList')")
    public HttpResponseResult<PageInfo<StudentInstrument>> getList(StudentInstrumentQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        if (StringUtils.isEmpty(queryInfo.getOrganId())) {
            queryInfo.setOrganId(employee.getOrganIdList());
        } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
            return failed("用户所在分部异常");
        } else {
            List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
            if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                return failed("非法请求");
            }
        }
        studentInstrumentDao.batchUpdate();
        return succeed(studentInstrumentService.queryPage(queryInfo));
    }

    @ApiOperation(value = "新增乐器")
    @PostMapping("/add")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/add')")
    public HttpResponseResult<StudentInstrument> add(StudentInstrument studentInstrument) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (studentInstrument.getStudentId() == null) {
            return failed("学生id不能为空");
        }
        StudentInstrument oldInstrument = studentInstrumentService.getStudentInstrument(studentInstrument.getStudentId(), studentInstrument.getGoodsId());
        if (oldInstrument != null) {
            return failed("学生乐器信息已存在，请核查");
        }

        Date nowDate = new Date();
        //不是乐保
        if (studentInstrument.getStatus().equals(0)) {
            studentInstrument.setStartTime(null);
            studentInstrument.setEndTime(null);
        }
        if (studentInstrument.getStatus().equals(1)) {
            if (studentInstrument.getStartTime() == null) {
                return failed("乐保开始时间不能为空");
            }
            if (studentInstrument.getEndTime() == null) {
                return failed("乐保结束时间不能为空");
            }
            if (studentInstrument.getStartTime().compareTo(nowDate) > 0) {
                return failed("乐保开始时间不能大于当前时间");
            }
            if (studentInstrument.getEndTime().compareTo(nowDate) <= 0) {
                return failed("乐保结束时间不能小于当前时间");
            }
        }
        studentInstrument.setOperation(sysUser.getId());
        SysUser student = sysUserFeignService.queryUserById(studentInstrument.getStudentId());
        studentInstrument.setOrganId(student.getOrganId());
        return succeed(studentInstrumentService.addStudentInstrument(studentInstrument));
    }


    @ApiOperation(value = "获取乐保信息")
    @GetMapping("/getInfo")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/getInfo')")
    public HttpResponseResult<StudentInstrument> getInfo(Long id, Integer studentId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        StudentInstrument studentInstrument = studentInstrumentService.get(id);
        if (studentInstrument == null || !studentInstrument.getStudentId().equals(studentId)) {
            return failed("学生乐器信息不存在");
        }
        return succeed(studentInstrument);
    }


    @ApiOperation(value = "修改乐保信息")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/update')")
    public HttpResponseResult<StudentInstrument> update(StudentInstrument studentInstrument) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (studentInstrument.getStudentId() == null) {
            return failed("学生id不能为空");
        }
        Date nowDate = new Date();
        //不是乐保
        if (studentInstrument.getStatus().equals(0)) {
            studentInstrument.setStartTime(null);
            studentInstrument.setEndTime(null);
        }
        if (studentInstrument.getStatus().equals(1)) {
            if (studentInstrument.getStartTime() == null) {
                return failed("乐保开始时间不能为空");
            }
            if (studentInstrument.getEndTime() == null) {
                return failed("乐保结束时间不能为空");
            }
            if (studentInstrument.getStartTime().compareTo(nowDate) > 0) {
                return failed("乐保开始时间不能大于当前时间");
            }
            if (studentInstrument.getEndTime().compareTo(nowDate) <= 0) {
                return failed("乐保结束时间不能小于当前时间");
            }
        }
        studentInstrument.setOperation(sysUser.getId());
        SysUser student = sysUserFeignService.queryUserById(studentInstrument.getStudentId());
        studentInstrument.setOrganId(student.getOrganId());
        return succeed(studentInstrumentService.updateStudentInstrument(studentInstrument));
    }

    @ApiOperation(value = "删除学生乐器信息")
    @PostMapping("/del")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/del')")
    public HttpResponseResult<StudentInstrument> del(Long id, Integer studentId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        StudentInstrument studentInstrument = studentInstrumentService.get(id);
        if (studentInstrument == null || !studentInstrument.getStudentId().equals(studentId)) {
            return failed("学生乐器信息不存在");
        }
        studentInstrument.setOperation(sysUser.getId());
        studentInstrument.setDelFlag(1);
        return succeed(studentInstrumentService.updateStudentInstrument(studentInstrument));
    }

    @ApiOperation(value = "导出")
    @GetMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('studentInstrument/export')")
    public void export(Date startTime, Date endTime, HttpServletResponse response) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        String organId = null;
        if (StringUtils.isEmpty(employee.getOrganIdList())) {
            throw new BizException("用户所在分部异常");
        } else {
            organId = employee.getOrganIdList();
        }
        if (startTime != null) {
            startTime = DateUtil.trunc(startTime);
        }
        if (endTime != null) {
            endTime = DateUtil.getLastTimeWithDay(endTime);
        }

        List<StudentInstrumentExportDto> instruments = studentInstrumentDao.getInstruments(startTime, endTime, organId);

        if (instruments.size() <= 0) {
            throw new BizException("没有可导出的记录");
        }
        for (StudentInstrumentExportDto instrument : instruments) {
            StudentRegistration studentMusicGroup = studentInstrumentDao.findStudentMusicGroup(instrument.getStudentId());
            if (studentMusicGroup != null) {
                instrument.setRepairerName(studentMusicGroup.getParentsName());
                instrument.setMusicGroupName(studentMusicGroup.getClassGroupName());
                instrument.setStudentStatus(studentMusicGroup.getMusicGroupStatus());
            }
        }

        OutputStream outputStream = response.getOutputStream();
        HSSFWorkbook workbook = null;
        try {
            String[] header = {"交易流水号", "订单号", "订单日期", "分部", "学员姓名", "学员编号", "所属乐团", "学员状态", "维修技师", "乐器名称", "具体型号", "乐保类型"};
            String[] body = {"transNo", "orderNo", "createTime", "organName", "studentName", "studentId", "musicGroupName", "studentStatus.msg", "repairerName", "goodsName", "specification", "type == '0' ? '新增' : '续费'"};
            workbook = POIUtil.exportExcel(header, body, instruments);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=maintenance-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    workbook.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
