package thyyxxk.webserver.controller.utilities;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import thyyxxk.webserver.dao.his.utilities.ItemApplyDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.utilities.itemapply.request.QuerySupplies;
import thyyxxk.webserver.entity.utilities.itemapply.request.SubmitSuppliesBody;
import thyyxxk.webserver.entity.utilities.itemapply.response.ItemApply;
import thyyxxk.webserver.service.utilities.CreateExcelFileService;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/itemApply")
public class ItemApplyController {
    private final ItemApplyDao dao;
    private final CreateExcelFileService service;

    @Autowired
    public ItemApplyController(ItemApplyDao dao, CreateExcelFileService service) {
        this.dao = dao;
        this.service = service;
    }

    @PostMapping("/selectApplyItems")
    public ResultVo<List<ItemApply>> selectApplyItems(@RequestBody QuerySupplies querySupplies) {
        String statement;
        if (querySupplies.getMethod().equals("alpha")) {
            statement = "py_code like '%" + querySupplies.getContent().toUpperCase() + "%'";
        } else {
            statement = "name like '%" + querySupplies.getContent() + "%'";
        }
        return ResultVoUtil.success(dao.selectSupplies(querySupplies.getType(), statement));
    }

    @PostMapping("/submitSupplies")
    public ResultVo<String> submitSupplies(@RequestBody SubmitSuppliesBody body) {
        List<ItemApply> applies = body.getSupplies();
        List<Map<String, String>> mapList = new ArrayList<>();

        for (int i = 0; i < applies.size(); i++) {
            Map<String, String> map = makeExcelDataMap(body, i, applies);
            mapList.add(map);
        }

        Map<String, List<Map<String, String>>> result = new HashMap<>();
        result.put("物料申领", mapList);

        try {
            service.executeWriteExcel(body.getCodeRs(), result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVoUtil.success();
    }

    @NotNull
    private static Map<String, String> makeExcelDataMap(SubmitSuppliesBody body, int i, List<ItemApply> applies) {
        Map<String, String> map = new HashMap<>();
        if (i == 0) {
            map.put("申请人", body.getUserName());
            map.put("申请科室", body.getDeptName());
            map.put("特殊情况", body.getSpecialRemark());
        }
        ItemApply item = applies.get(i);
        map.put("库存编号", item.getCode());
        map.put("名称", item.getName());
        map.put("规格", item.getSize());
        map.put("数量", String.valueOf(item.getQuantity()));
        map.put("单位", item.getUnit());
        return map;
    }
}
