import * as express from "express";
import { getConnection } from "typeorm";
import Deceased from "@/entity/Deceased";
import curd from "@/lib/curd/curd";
import DeceasedRetail from "@/entity/DeceasedRetail";
import { SeletedServiceList } from "@/entity/SeletedServiceList";
import { Request } from "express-serve-static-core";
import PaymentRecord from "@/entity/Payment";

const router = express.Router();

// 查询逝者列表（支持分页）
router.post("/query", async (req, res) => {
  try {
    const result = await curd({ entity: Deceased, req }).queryList();
    await getData(result, req);
    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

router.get("/list", async (req, res) => {
  try {
    const result = await curd({ entity: Deceased, req }).queryList();
    await getData(result, req);
    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 添加逝者
router.post("/add", async (req, res) => {
  const { name, idNumber } = req.body;

  if (!name || !idNumber) {
    return res.send({ code: 400, msg: "逝者姓名和证件号码不能为空！" });
  }

  try {
    const connection = getConnection();
    const deceasedRepository = connection.getRepository(Deceased);
    const deceasedRetailRep = connection.getRepository(DeceasedRetail);

    const tempServiceItems = req.body.services.map((item) => {
      delete item.id;
      return {
        ...item,
      };
    });
    req.body.serviceItems = "";

    // 校验是否已存在相同证件号码的逝者
    const existingDeceased = await deceasedRepository.findOne({
      where: { idNumber },
    });

    if (existingDeceased) {
      return res.send({ code: 400, msg: "证件号码已存在，请勿重复添加！" });
    }

    const newDeceased = await curd({ entity: Deceased, req }).add();
    let newDeceasedRetail = await curd({ entity: DeceasedRetail, req }).add();

    if (tempServiceItems.length) {
      tempServiceItems.forEach((item) => {
        item.retailId = newDeceasedRetail.id;

        delete item.id;
      });

      const data = await connection
        .getRepository(SeletedServiceList)
        .save(tempServiceItems);

      newDeceasedRetail.serviceItems = data.map((item) => item.id).join(",");
    }
    newDeceasedRetail.deceasedId = newDeceased.id;

    await deceasedRetailRep.save(newDeceasedRetail);

    res.send({ code: 200, msg: "逝者信息添加成功", data: newDeceased });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 更新逝者信息
router.post("/update", async (req, res) => {
  const { id, idNumber } = req.body;

  if (!id) {
    return res.send({ code: 400, msg: "逝者ID不能为空！" });
  }

  try {
    const connection = getConnection();
    const deceasedRepository = connection.getRepository(Deceased);

    // 校验是否已存在相同证件号码的逝者（排除当前记录）
    if (idNumber) {
      const existingDeceased = await deceasedRepository.findOne({
        where: { idNumber },
      });

      if (existingDeceased && existingDeceased.id !== id) {
        return res.send({ code: 400, msg: "证件号码已存在，请勿重复使用！" });
      }
    }

    const updatedDeceased = await curd({ entity: Deceased, req }).update();
    res.send({ code: 200, msg: "逝者信息更新成功", data: updatedDeceased });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 删除逝者信息
router.get("/delete", async (req, res) => {
  const { id } = req.query;

  if (!id) {
    return res.send({ code: 400, msg: "逝者ID不能为空！" });
  }

  try {
    await curd({ entity: Deceased, req }).delete();
    res.send({ code: 200, msg: "逝者信息删除成功" });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

async function getData(result, req: Request) {
  let type = req.query.type ?? req.body.type;
  if (!type && type !== 0) type = 0;

  const deceasedId = Array.from(
    new Set(result.list.map((item) => Number(item.deceasedId)))
  );

  const deceasedIds = Array.from(
    new Set(result.list.map((item) => Number(item.id)))
  );

  if (deceasedId.length) {
    const reatialList = await getConnection()
      .getRepository(DeceasedRetail)
      .createQueryBuilder("DeceasedRetail")
      .where("DeceasedRetail.deceased_id IN (:...ids)", {
        ids: deceasedIds,
      })
      .andWhere("DeceasedRetail.retail_type = :retailType", {
        retailType: type,
      })
      .getMany();

    if (reatialList.length) {
      result.list = result.list.map((item: any) => {
        return {
          ...item,
          deceased: { ...item },
          retail: reatialList.find(
            (fitem: any) => fitem.deceasedId === item.id
          ),
        };
      });
    }

    let retailIds = reatialList.map((item) => item.id);

    if (retailIds.length) {
      const serviceList = await getConnection()
        .getRepository(SeletedServiceList)
        .createQueryBuilder("SeletedServiceList")
        .where("SeletedServiceList.retail_id IN (:...retailIds)", {
          retailIds: retailIds,
        })
        .getMany();
      if (serviceList.length) {
        result.list = result.list.map((item: any) => {
          let retailId = reatialList.find(
            (fitem) => fitem.deceasedId === item.id
          )?.id;

          let services = serviceList.filter(
            (fitem) => fitem.retailId === retailId
          );
          return {
            ...item,
            serviceItems: services.map((mitem) => mitem.id.toString()),
            services: services,
          };
        });
      }
    }
  }
}

export default router;
