package cn.com.ty.lift.business.evaluation.controller;


import cn.com.ty.lift.business.evaluation.dao.entity.Evaluation;
import cn.com.ty.lift.business.evaluation.service.EvaluationService;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 保养单用户评价 前端控制器
 * </p>
 *
 * @author huangyuan
 * @since 2019-12-31
 */
@Slf4j
@RestController
@RequestMapping("/evaluation")
@AllArgsConstructor
public class EvaluationController {

    private final EvaluationService evaluationService;

    @PostMapping("removeDuplicate")
    public RestResponse removeDuplicate(){
        List<Evaluation> duplicate = evaluationService.listDuplicateForSameRecord();
        if(duplicate.isEmpty()){
            return RestResponse.success(true);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Evaluation evaluation : duplicate) {
            Long recordId = evaluation.getRecordId();
            Integer source = evaluation.getSource();
            log.info("recordId: {}, source: {}", recordId, source);
            List<Long> toDelete = evaluationService.listToDelete(recordId, source);
            stringBuilder.append("-- delete recordId: ").append(recordId).append(", source: ").append(source).append("\n");
            if(toDelete.isEmpty()){
                Long oneToDelete = evaluationService.findOneToDelete(recordId, source);
                stringBuilder.append("DELETE FROM evaluation WHERE id = ").append(oneToDelete).append(";\n");
            }else {
                stringBuilder.append("DELETE FROM evaluation WHERE id IN (").append(StrUtil.join(",", toDelete.toArray())).append(")").append(";\n");
            }
        }
        String deletesql = "./sql/0.delete_duplicate_evaluation.sql";
        log.info("生成delete删除同一record下多余的评价记录：{}", deletesql);
        FileUtil.writeString(stringBuilder.toString(), new File(deletesql), "utf-8");
        return RestResponse.success(true);
    }
}
