import * as express from "express";
import { getConnection } from "typeorm";
import DeceasedRetail from "@/entity/DeceasedRetail";
import PaymentRecord from "@/entity/Payment";

const router = express.Router();

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

  try {
    let connection = getConnection();

    let deceasedRetailRep = connection.getRepository(DeceasedRetail);
    let paymentRecordRep = connection.getRepository(PaymentRecord);

    let deceasedRetail = await deceasedRetailRep.findOne(id);

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

    let newPaymentRecord = await paymentRecordRep.findOne({
      deceasedRetailId: deceasedRetail.id,
    });

    if (!newPaymentRecord) {
      newPaymentRecord = new PaymentRecord();
    }

    deceasedRetail.retailState = 1;
    deceasedRetail.checkoutDate = new Date();

    newPaymentRecord = Object.assign(newPaymentRecord, req.body.currentPayment);
    newPaymentRecord.deceasedRetailId = deceasedRetail.id;

    await deceasedRetailRep.save(deceasedRetail);
    await paymentRecordRep.save(newPaymentRecord);

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

export default router;
