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.dto.RepairGoodsDto;
import com.ym.mec.biz.dal.entity.CooperationOrgan;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.StudentRepair;
import com.ym.mec.biz.dal.page.CooperationOrganQueryInfo;
import com.ym.mec.biz.dal.page.RepairStudentQueryInfo;
import com.ym.mec.biz.service.OrganizationService;
import com.ym.mec.biz.service.StudentRepairService;
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.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.Objects;
import java.util.stream.Collectors;

@RequestMapping("studentRepair")
@Api(tags = "维修服务")
@RestController
public class StudentRepairController extends BaseController {

    @Autowired
    private StudentRepairService studentRepairService;
    @Autowired
    private OrganizationService organizationService;

    @ApiOperation("获取维修列表")
    @GetMapping(value = "/queryPage")
    @PreAuthorize("@pcs.hasPermissions('studentRepair/queryPage')")
    public HttpResponseResult queryPage(RepairStudentQueryInfo queryInfo) {
        queryInfo.setOrganIdList(organizationService.getEmployeeOrgan(queryInfo.getOrganIdList()));
        Date endTime = queryInfo.getEndTime();
        if (endTime != null) {
            queryInfo.setEndTime(DateUtil.getLastTimeWithDay(endTime));
        }
        queryInfo.setPayStatus(2);
        return succeed(studentRepairService.queryPage(queryInfo));
    }


    @ApiOperation("维修完成")
    @PostMapping(value = "/repairSuccess")
    @PreAuthorize("@pcs.hasPermissions('studentRepair/repairSuccess')")
    public HttpResponseResult repairSuccess(Integer id, String description, Integer repairStatus) {
        studentRepairService.repairSuccess(id, description, repairStatus);
        return succeed();
    }

    @ApiOperation(value = "维修记录导出")
    @RequestMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('studentRepair/export')")
    public void export(RepairStudentQueryInfo queryInfo, HttpServletResponse response) throws Exception {
        queryInfo.setOrganIdList(organizationService.getEmployeeOrgan(queryInfo.getOrganIdList()));
        Date endTime = queryInfo.getEndTime();
        if (endTime != null) {
            queryInfo.setEndTime(DateUtil.getLastTimeWithDay(endTime));
        }
        queryInfo.setPayStatus(2);
        queryInfo.setRows(65000);

        PageInfo<StudentRepair> pageList = studentRepairService.queryPage(queryInfo);

        if (pageList.getTotal() <= 0) {
            throw new BizException("没有可导出的记录");
        }
        for (StudentRepair row : pageList.getRows()) {
            if (row.getGoodsJson() == null || row.getGoodsJson().equals("[]")) {
                row.setAmount(row.getAmount().subtract(row.getExemptionAmount()));
                row.setGoodsJson("");
                continue;
            }
            List<RepairGoodsDto> repairGoodsDtos = JSONObject.parseArray(row.getGoodsJson(), RepairGoodsDto.class);
            BigDecimal repairGoodsAmount = repairGoodsDtos.stream().map(RepairGoodsDto::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal goodsRouteAmount = (row.getAmount().add(repairGoodsAmount).subtract(row.getExemptionAmount())).multiply(repairGoodsAmount).divide(row.getAmount().add(repairGoodsAmount), 2, BigDecimal.ROUND_DOWN);
            BigDecimal repairRouteAmount = row.getAmount().add(repairGoodsAmount).subtract(row.getExemptionAmount()).subtract(goodsRouteAmount);
            String goodiesStr = repairGoodsDtos.stream().map(RepairGoodsDto::getName).collect(Collectors.joining(","));
            row.setGoodsJson(goodiesStr);
            row.setRepairGoodsAmount(goodsRouteAmount);
            row.setAmount(repairRouteAmount);
        }

        OutputStream outputStream = response.getOutputStream();
        try {
            String[] header = {"维修单号", "分部", "学生姓名", "学生编号", "维修技师", "维修类型", "维修单名称", "送修日期", "完成日期", "状态", "维修服务费", "商品价格", "销售商品"};
            String[] body = {"transNo", "organName", "studentName", "studentId", "employeeName", "type == 0 ? '线下' : '线上'", "repairName", "createTime", "finishTime", "repairStatus == 0 ? '维修中' : '已完成'", "amount", "repairGoodsAmount", "goodsJson"};
            HSSFWorkbook workbook = POIUtil.exportExcel(header, body, pageList.getRows());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=repairList-" + 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 {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
