import * as express from "express";
import { getConnection, getRepository } from "typeorm";
import DeceasedRetail from "../../entity/DeceasedRetail";
import curd from "@/lib/curd/curd";
import SeletedServiceList from "@/entity/SeletedServiceList";
import Deceased from "@/entity/Deceased";

const router = express.Router();

async function GetData(result) {
  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,
      };
    });
  }
}

router.post("/query", async (req, res) => {
  try {
    const result = await curd({
      entity: DeceasedRetail,
      req,
      params: {
        retailType: 2,
      },
    }).queryList();
    await GetData(result);
    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: any = await curd({
      entity: DeceasedRetail,
      req,
      params: {
        retailType: 2,
      },
    }).queryList();
    await GetData(result);
    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

router.get("/checkout", async (req, res) => {
  let { id } = req.query;
  if (!id) {
    return res.status(500).send({ code: 500, msg: "未传入结账id" });
  }

  let deceasedRetailRep = getConnection().getRepository(DeceasedRetail);
  let deceasedRetail = await deceasedRetailRep.findOne(Number(id));

  if (!deceasedRetail)
    return res.status(500).send({ code: 500, msg: "该记录不存在" });

  deceasedRetail.retailState = 1;

  await deceasedRetailRep.save(deceasedRetail);

  res.status(200).send({ code: 200, data: deceasedRetail, msg: "结账成功！" });
});

router.post("/add", async (req, res) => {
  delete req.body.id;
  const connection = getConnection();
  try {
    const tempServiceItems = req.body.services.map((item) => {
      delete item.id;

      return item;
    });
    req.body.serviceItems = "";

    const deceasedRetailRep = connection.getRepository(DeceasedRetail);
    let newDeceasedRetail = new DeceasedRetail();

    newDeceasedRetail = Object.assign(newDeceasedRetail, req.body);
    newDeceasedRetail.retailType = 2;

    if (tempServiceItems.length) {
      tempServiceItems.forEach((item) => {
        item.retailId = newDeceasedRetail.id;
        item.hasDeceased = 0;
      });
      let executeData = await connection
        .getRepository(SeletedServiceList)
        .save(tempServiceItems);

      newDeceasedRetail.serviceItems = executeData
        .map((item) => item.id)
        .join(",");

      await deceasedRetailRep.save(newDeceasedRetail);
    }

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

router.post("/update", async (req, res) => {
  const id = Number(req.body.id);

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

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

    const tempServiceItems = req.body.services.map((item) => {
      delete item.id;

      return item;
    });

    let findData = await deceasedRepository.findOne(id);

    const ids = findData.serviceItems.split(",").map((id) => Number(id));
    if (ids.length) {
      await connection
        .getRepository(SeletedServiceList)
        .createQueryBuilder("seleted_service_list")
        .where("seleted_service_list.id IN (:...ids)", {
          ids,
        })
        .delete()
        .execute();
    }
    findData = { ...findData, ...req.body };
    if (tempServiceItems.length) {
      tempServiceItems.forEach((item) => {
        item.retailId = id;
        item.hasDeceased = 0;
        item.updateDate = new Date();
        item.createDate = new Date();
      });
      let executeData = await connection
        .getRepository(SeletedServiceList)
        .save(tempServiceItems);

      findData.serviceItems = executeData.map((item) => item.id).join(",");

      await deceasedRepository.save(findData);
    }

    res.send({ code: 200, msg: "更新成功", data: findData });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

router.get("/delete", async (req, res) => {
  const id = Number(req.query.id);

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

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

    const findData = await deceasedRepository.findOne(id);

    const ids = findData.serviceItems.split(",").map((id) => Number(id));
    if (ids.length) {
      await connection
        .getRepository(SeletedServiceList)
        .createQueryBuilder("seleted_service_list")
        .where("seleted_service_list.id IN (:...ids)", {
          ids,
        })
        .delete()
        .execute();
    }
    await deceasedRepository.remove(findData);

    res.send({ code: 200, msg: "删除成功！" });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

export default router;
