package cn.ezhizao.project.business.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.BizOutsourcedRecords;
import cn.ezhizao.project.business.service.IBizOutsourcedRecordsService;
import cn.hutool.core.date.DateTime;
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.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 外协发出单历史记录Controller
 *
 * @author ezhizao
 * @date 2024-06-03
 */
@RestController
@RequestMapping("/business/outsourcedRecords")
public class BizOutsourcedRecordsController extends BaseController
{
    @Resource
    private IBizOutsourcedRecordsService bizOutsourcedRecordsService;

    /**
     * 查询外协发出单历史记录列表
     */

    @GetMapping("/list")
    @Log(title = "查询外协发出单历史记录列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizOutsourcedRecords bizOutsourcedRecords) throws NoSuchFieldException, IllegalAccessException {
        List<BizOutsourcedRecords> list = bizOutsourcedRecordsService.getList(bizOutsourcedRecords);
        // 提取 startTime 并对其进行排序
        List<String> sortedStartTimes = list.stream()
                .map(v -> new DateTime(v.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"))
                .distinct()
                .sorted(Comparator.reverseOrder()) // 默认升序排序，如果要降序，可以使用 sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

// 使用 LinkedHashMap 来保持插入顺序
        Map<String, List<BizOutsourcedRecords>> groupedByTime = new LinkedHashMap<>();

// 遍历排序后的 startTime 列表进行分组
        for (String startTime : sortedStartTimes) {
            groupedByTime.put(startTime, list.stream()
                    .filter(record -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getStartTime()).equals(startTime))
                    .collect(Collectors.toList()));
        }
        List<BizOutsourcedRecords> details = new ArrayList<>();
        for (Map.Entry<String, List<BizOutsourcedRecords>> entry : groupedByTime.entrySet()) {
            BizOutsourcedRecords outsourcedRecords = new BizOutsourcedRecords();
            String startTime = entry.getKey();
            List<BizOutsourcedRecords> info = entry.getValue();

            // 假设每个分组中 userName 是唯一的，我们取第一个记录的 userName
            String userName = info.get(0).getUserName();
            String nickName = info.get(0).getNickName();
            String method = info.get(0).getMethod();
            String formCode = info.get(0).getFormCode();
            String supplierName = info.get(0).getSupplierName();
            List<BizOutsourcedRecords> recordsList = new ArrayList<>();
            String result = info.stream()
                    .map(item -> String.format(
                            "%s,%s,%d,%s,%s",
                            item.getLotCode(),
                            item.getProductDescription(),
                            item.getProductNum(),
                            item.getNewCarrier(),
                            item.getProcessNames()
                    )) // 在每个对象后添加分号
                    .collect(Collectors.joining(";"));
            // 构建格式化字符串
            StringBuilder formattedString = new StringBuilder();
            formattedString.append(userName).append("，");
            formattedString.append(nickName).append("，");
            formattedString.append(startTime).append("，");
            formattedString.append(method).append("，");
            formattedString.append(formCode).append("，");
            formattedString.append(supplierName).append("，");
            formattedString.append("明细:{").append(result).append("}");
            outsourcedRecords.setRecords(String.valueOf(formattedString));
            details.add(outsourcedRecords);
        }
        return getDataTable(details);
    }
    @GetMapping("/innerList")
    @Log(title = "查询外协发出单历史记录列表", businessType = BusinessType.SELECT)
    public TableDataInfo innerList(BizOutsourcedRecords bizOutsourcedRecords) throws NoSuchFieldException, IllegalAccessException {
        List<BizOutsourcedRecords> list = bizOutsourcedRecordsService.getList(bizOutsourcedRecords);
        // 提取 startTime 并对其进行排序
        List<String> sortedStartTimes = list.stream()
                .map(v -> new DateTime(v.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"))
                .distinct()
                .sorted(Comparator.reverseOrder()) // 默认升序排序，如果要降序，可以使用 sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

// 使用 LinkedHashMap 来保持插入顺序
        Map<String, List<BizOutsourcedRecords>> groupedByTime = new LinkedHashMap<>();

// 遍历排序后的 startTime 列表进行分组
        for (String startTime : sortedStartTimes) {
            groupedByTime.put(startTime, list.stream()
                    .filter(record -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getStartTime()).equals(startTime))
                    .collect(Collectors.toList()));
        }
        List<BizOutsourcedRecords> details = new ArrayList<>();
        for (Map.Entry<String, List<BizOutsourcedRecords>> entry : groupedByTime.entrySet()) {
            BizOutsourcedRecords outsourcedRecords = new BizOutsourcedRecords();
            String startTime = entry.getKey();
            List<BizOutsourcedRecords> info = entry.getValue();

            // 假设每个分组中 userName 是唯一的，我们取第一个记录的 userName
            String userName = info.get(0).getUserName();
            String nickName = info.get(0).getNickName();
            String method = info.get(0).getMethod();
            String formCode = info.get(0).getFormCode();
            String supplierName = info.get(0).getSupplierName();
            List<BizOutsourcedRecords> recordsList = new ArrayList<>();
            String result = info.stream()
                    .map(item -> String.format(
                            "%s,%s,%d,%s,%s,%s",
                            item.getLotCode(),
                            item.getProductDescription(),
                            item.getProductNum(),
                            item.getNewCarrier(),
                            item.getProcessNames(),
                            item.getIsPackage() == 0 ? "否" : "是"
                    )) // 在每个对象后添加分号
                    .collect(Collectors.joining(";"));
            // 构建格式化字符串
            StringBuilder formattedString = new StringBuilder();
            formattedString.append(userName).append("，");
            formattedString.append(nickName).append("，");
            formattedString.append(startTime).append("，");
            formattedString.append(method).append("，");
            formattedString.append(formCode).append("，");
            formattedString.append(supplierName).append("，");
            formattedString.append("明细:{").append(result).append("}");
            outsourcedRecords.setRecords(String.valueOf(formattedString));
            details.add(outsourcedRecords);
        }
        return getDataTable(details);
    }
    /**
     * 导出外协发出单历史记录列表
     */
    @Log(title = "导出外协发出单历史记录列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOutsourcedRecords bizOutsourcedRecords) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedRecords);
        List<BizOutsourcedRecords> list = bizOutsourcedRecordsService.getList(bizOutsourcedRecords);
        ExcelUtil<BizOutsourcedRecords> util = new ExcelUtil<BizOutsourcedRecords>(BizOutsourcedRecords.class);
        util.exportExcel(response, list, "外协发出单历史记录数据");
    }

    /**
     * 获取外协发出单历史记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizOutsourcedRecordsService.getById(id));
    }

    /**
     * 新增外协发出单历史记录
     */
    @Log(title = "新增外协发出单历史记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOutsourcedRecords bizOutsourcedRecords) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedRecords);
        return toAjax(bizOutsourcedRecordsService.save(bizOutsourcedRecords));
    }

    /**
     * 修改外协发出单历史记录
     */
    @Log(title = "修改外协发出单历史记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOutsourcedRecords bizOutsourcedRecords) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedRecords);
        return toAjax(bizOutsourcedRecordsService.updateById(bizOutsourcedRecords));
    }

    /**
     * 删除外协发出单历史记录
     */
    @Log(title = "删除外协发出单历史记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizOutsourcedRecordsService.removeBatchByIds(ids));
    }
}
