package com.jwipc.spe.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageView;
import com.jwipc.query.BasePageQuery;
import com.jwipc.spe.constant.AppraisePlanStatus;
import com.jwipc.spe.constant.QuotaType;
import com.jwipc.spe.dto.PlanFieldDTO;
import com.jwipc.spe.dto.SubmitScoreDTO;
import com.jwipc.spe.dto.SupAppraisePlanBaseDTO;
import com.jwipc.spe.dto.SupAppraisePlanSaveDTO;
import com.jwipc.spe.logic.SupAppraisePlanLogic;
import com.jwipc.spe.logic.SupAppraiseTemplateLogic;
import com.jwipc.spe.model.query.AppraiseSupplierQuery;
import com.jwipc.spe.model.query.SupAppraisePlanQuery;
import com.jwipc.util.EasyExcelImportUtils;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.jwipc.spe.constant.ModuleConst.MODULE_ROOT;

/**
 * <p> 绩效考核相关接口</p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping(MODULE_ROOT + "/supAppraisePlan/rest")
@RequiredArgsConstructor
public class SupAppraisePlanRestController {
    private final SupAppraisePlanLogic supAppraisePlanLogic;
    private final SupAppraiseTemplateLogic supAppraiseTemplateLogic;

    /**
     * 考核管理列表
     *
     * @param query 查询参数
     * @return
     */
    @GetMapping("list")
    public PageView list(SupAppraisePlanQuery query) {
        return supAppraisePlanLogic.list(query);
    }

    /**
     * 考核评分列表接口
     *
     * @param query 查询参数
     * @return
     */
    @GetMapping("listForScoring")
    public PageView listForScoring(SupAppraisePlanQuery query) {
        //需要根据状态查询
        if (StrUtil.isEmpty(query.getStatus())) {
            query.setStatus(StrUtil.format("{},{}", AppraisePlanStatus.SCORE_ING.getIndex(),
                    AppraisePlanStatus.SCORED.getIndex()));
        }
        return supAppraisePlanLogic.list(query);
    }

    /**
     * 考核计划详情接口
     *
     * @param id 考核计划主键
     * @return
     */
    @GetMapping("detail")
    public ResponseEntity detail(Long id) {
        SupAppraisePlanBaseDTO supAppraisePlanBaseDTO = supAppraisePlanLogic.getDetail(id);
        return ResponseEntity.ok(supAppraisePlanBaseDTO);
    }

    /**
     * 保存和修改考核计划
     *
     * @param supAppraisePlanSaveDTO 保存或修改对象
     * @return
     */
    @PostMapping("saveOrUpdate")
    public ResponseEntity saveOrUpdate(@RequestBody SupAppraisePlanSaveDTO supAppraisePlanSaveDTO) {
        supAppraisePlanLogic.saveOrUpdate(supAppraisePlanSaveDTO);
        return ResponseEntity.ok().build();
    }

    /**
     * 考核计划的明细数据
     *
     * @param query 考核计划主键
     * @return
     */
    @GetMapping("detailList")
    public PageView detailList(AppraiseSupplierQuery query) {
        return supAppraisePlanLogic.detailList(query);
    }

    /**
     * 更新考核计划状态
     *
     * @param planId 考核计划主键
     * @return
     */
    @PostMapping("updateStatus")
    public ResponseEntity updateStatus(Long planId) {
        supAppraisePlanLogic.updateStatus(planId);
        return ResponseEntity.ok().build();
    }


    /**
     * 导出评分数据
     *
     * @param response
     * @param planId   考核计划主键
     * @throws IOException
     */
    @GetMapping("exportScore")
    public void exportTemplate(HttpServletResponse response, AppraiseSupplierQuery query) throws IOException {
        final List<PlanFieldDTO> fieldByPlan = supAppraiseTemplateLogic.getFieldByPlan(query.getPlanId());
        List<ExportDataDTO> list = Lists.newArrayList();
        //需要添加固定字段
        ExportDataDTO a = ExportDataDTO.builder().field("date").title("考核期间").header("考核期间")
                .color(IndexedColors.YELLOW.getIndex()).build();
        list.add(a);
        ExportDataDTO b = ExportDataDTO.builder().field("supplierCode").title("供应商编码").header("供应商编码")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(b);
        ExportDataDTO c = ExportDataDTO.builder().field("supplierName").title("供应商名称").header("供应商名称")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(c);
        ExportDataDTO aa = ExportDataDTO.builder().field("purchaseUser").title("采购员").header("采购员")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(aa);
        ExportDataDTO bb = ExportDataDTO.builder().field("sqe").title("SQE").header("SQE")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(bb);
        ExportDataDTO cc = ExportDataDTO.builder().field("ce").title("CE").header("CE")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(cc);
        ExportDataDTO dd = ExportDataDTO.builder().field("purchaseCategoryNames").title("物料类别").header("物料类别")
                .color(IndexedColors.YELLOW.getIndex())
                .build();
        list.add(dd);

        for (PlanFieldDTO temQuotaDTO : fieldByPlan) {
            for (PlanFieldDTO planFieldDTO : temQuotaDTO.getItem()) {
                ExportDataDTO d = ExportDataDTO.builder().field(planFieldDTO.getCode())
                        .title(planFieldDTO.getName()).header(temQuotaDTO.getName()).build();
                final Integer quotaType = planFieldDTO.getType();
                if (quotaType == QuotaType.MANUAL_QUOTA.getValue()) {
                    d.setColor(IndexedColors.YELLOW.getIndex());
                } else {
                    d.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
                }
                list.add(d);
            }
        }
        final List<Map<String, Object>> planDetails = supAppraisePlanLogic.getPlanDetail(query);
        EasyExcelUtils.trendsModelWriteForMap(response,
                "计划评分-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet",
                planDetails, list, true);
    }

    @GetMapping("exportScore1")
    public void exportScore1(HttpServletResponse response, AppraiseSupplierQuery query) throws IOException {
        final List<PlanFieldDTO> fieldByPlan = supAppraiseTemplateLogic.getFieldByPlan(query.getPlanId());
        List<ExportDataDTO> list = Lists.newArrayList();
        //需要添加固定字段
        ExportDataDTO a = ExportDataDTO.builder().field("date").title("考核期间").header("考核期间").build();
        list.add(a);
        ExportDataDTO b = ExportDataDTO.builder().field("supplierCode").title("供应商编码").header("供应商编码")
                .build();
        list.add(b);
        ExportDataDTO c = ExportDataDTO.builder().field("supplierName").title("供应商名称").header("供应商名称")
                .build();
        list.add(c);
        ExportDataDTO aa = ExportDataDTO.builder().field("purchaseUser").title("采购员").header("采购员").build();
        list.add(aa);
        ExportDataDTO bb = ExportDataDTO.builder().field("sqe").title("SQE").header("SQE").build();
        list.add(bb);
        ExportDataDTO cc = ExportDataDTO.builder().field("ce").title("CE").header("CE").build();
        list.add(cc);
        ExportDataDTO dd = ExportDataDTO.builder().field("purchaseCategoryNames").title("物料类别").header("物料类别")
                .build();
        list.add(dd);

        for (PlanFieldDTO temQuotaDTO : fieldByPlan) {
            for (PlanFieldDTO planFieldDTO : temQuotaDTO.getItem()) {
                ExportDataDTO d = ExportDataDTO.builder().field(planFieldDTO.getCode())
                        .title(planFieldDTO.getName()).header(temQuotaDTO.getName()).build();
                list.add(d);
            }
        }
        //动态导出工具类，只需要修改导出excel名称
        final List<Map<String, Object>> planDetails = supAppraisePlanLogic.getPlanDetail(query);
        EasyExcelUtils.trendsModelWriteForMap(response,
                "评分明细-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet",
                planDetails, list, true);
    }

    /**
     * 导入评分数据
     *
     * @param file 评分数据excel
     * @return
     */
    @RequestMapping("importScore")
    public ResponseEntity<Map<String, Map<String, String>>> importScore(@RequestPart("file") MultipartFile file) {
        try {
            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 3);
            //需要按照supplierCode为key
            Map<String, Map<String, String>> resultMap = dataList.stream()
                    .collect(Collectors.toMap(
                            map -> map.get("supplierCode"),
                            map -> map
                    ));
            return ResponseEntity.ok(resultMap);
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

    /**
     * 提交评分数据
     *
     * @param type           0:提交评分,不计算评分;1:提交评分修改评分状态;2:计算总分
     * @param submitScoreDTO 提交数据对象
     * @return
     */
    @PostMapping("submitScore/{type}")
    public ResponseEntity submitScore(
            @PathVariable("type") Integer type, @RequestBody SubmitScoreDTO submitScoreDTO)
    {
        supAppraisePlanLogic.submitScore(type, submitScoreDTO);
        return ResponseEntity.ok().build();
    }

    @PostMapping("remove")
    public ResponseEntity remove(Long id) {
        supAppraisePlanLogic.remove(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("getSupplierAppraisePlan")
    public PageView getSupplierAppraisePlan(BasePageQuery basePageQuery, Long supplierId) {
        return supAppraisePlanLogic.getSupplierAppraisePlan(basePageQuery, supplierId);
    }
}
