import * as express from "express";
import { getConnection } from "typeorm";
import ServiceItem from "../../entity/ServiceItem";
import curd from "@/lib/curd/curd";
import DeceasedRetail from "@/entity/DeceasedRetail";
import Deceased from "@/entity/Deceased";
import noDeceasedRetail from "@/entity/noDeceasedRetail";
import PaymentRecord from "@/entity/Payment";

const router = express.Router();

async function GetData(result) {
  let paymentIds = result.list
    .filter((item) => item.retailState === 1)
    .map((item) => item.id);
  if (paymentIds.length) {
    let manyResult = await getConnection()
      .getRepository(PaymentRecord)
      .createQueryBuilder("PaymentRecord")
      .where("PaymentRecord.deceased_retail_id IN (:...ids)", {
        ids: paymentIds,
      })
      .getMany();

    result.list = result.list.map((item: any) => {
      return {
        ...item,
        payment: manyResult.find((fitem) => fitem.deceasedRetailId === item.id),
      };
    });
  }
}

router.get("/list", async (req, res) => {
  let retailType = Number(req.query.retailType || 0);

  try {
    let result = await curd({
      entity: DeceasedRetail,
      params: {
        cancelState: 0,
        retailType,
        ...req.body,
      },
      req,
    }).queryList();

    if (retailType === 1) {
      const ids = Array.from(
        new Set(result.list.map((item) => Number(item.deceasedId)))
      );

      if (ids.length) {
        const manyResult = await getConnection()
          .getRepository(Deceased)
          .createQueryBuilder("deceased")
          .where("deceased.id IN (:...ids)", {
            ids,
          })
          .getMany();

        result.list = result.list.map((item: any) => {
          let findData = manyResult.find(
            (fitem: any) => fitem.id === item.deceasedId
          );
          return {
            ...findData,
            ...item,
            deceased: findData,
          };
        });
      }
    }

    await GetData(result);

    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

router.post("/query", async (req, res) => {
  let retailType = Number(req.body.retailType);
  try {
    let result = await curd({
      entity: DeceasedRetail,
      params: {
        cancelState: 0,
        retailType,
        ...req.body,
      },
      req,
    }).queryList();

    if (retailType === 1) {
      const ids = Array.from(
        new Set(result.list.map((item) => Number(item.deceasedId)))
      );

      if (ids.length) {
        const manyResult = await getConnection()
          .getRepository(Deceased)
          .createQueryBuilder("deceased")
          .where("deceased.id IN (:...ids)", {
            ids,
          })
          .getMany();

        result.list = result.list.map((item: any) => {
          let findData = manyResult.find(
            (fitem: any) => fitem.id === item.deceasedId
          );
          return {
            ...findData,
            ...item,
          };
        });
      }
    }

    await GetData(result);

    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

export default router;
