import * as express from "express";
import { getConnection } from "typeorm";

import curd from "@/lib/curd/curd";
import DeceasedRetail from "@/entity/DeceasedRetail";
import CancelRetail from "@/entity/CancelRetail";
import Deceased from "@/entity/Deceased";
import PaymentRecord from "@/entity/Payment";
import CheckoutRetail from "@/entity/CheckoutRetail";
import CheckoutPaymentRecords from "@/entity/CheckoutPayment";
import CancelPayment from "@/entity/CancelPayment";

const router = express.Router();
async function getMoreInfor(result, type = 0) {
  const deceasedRetailIds = result.list
    .filter((item) => item.deceasedRetailId)
    .map((item) => Number(item.deceasedRetailId));

  const checkoutRetailIds = result.list
    .filter((item) => item.checkoutRetailId)
    .map((item) => Number(item.checkoutRetailId));

  if (deceasedRetailIds.length) {
    const deceasedRetails = await getConnection()
      .getRepository(DeceasedRetail)
      .createQueryBuilder("deceased_retail")
      .where("deceased_retail.id IN (:...ids)", {
        ids: deceasedRetailIds,
      })
      .getMany();

    const deceasedIds = Array.from(
      new Set(deceasedRetails.map((item) => Number(item.deceasedId)))
    );
    let deceaseds = [];

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

    let paymentRecords = [];

    if (type === 0) {
      paymentRecords = await getConnection()
        .getRepository(CheckoutPaymentRecords)
        .createQueryBuilder("paymentRecord")
        .where("paymentRecord.checkout_retail_id IN (:...ids)", {
          ids: deceasedRetailIds,
        })
        .getMany();

      let tempRec = await getConnection()
        .getRepository(PaymentRecord)
        .createQueryBuilder("paymentRecord")
        .where("paymentRecord.deceased_retail_id IN (:...ids)", {
          ids: deceasedRetailIds,
        })
        .getMany();

      paymentRecords = [...paymentRecords, ...tempRec];
    } else {
      let retailIds = result.list.map((item) => Number(item.id));

      paymentRecords = await getConnection()
        .getRepository(CancelPayment)
        .createQueryBuilder("paymentRecord")
        .where("paymentRecord.retail_id IN (:...ids)", {
          ids: retailIds,
        })
        .getMany();
    }
    result.list = result.list.map((item: any) => {
      let retail = deceasedRetails.find(
        (fitem: any) => fitem.id === item.deceasedRetailId
      );

      let deceased = {};
      if (retail) {
        deceased = deceaseds.find((fitem) => fitem.id === retail.deceasedId);
      }
      let payment =
        paymentRecords.find(
          (fitem) => fitem.checkoutRetailId === item.deceasedRetailId
        ) ||
        paymentRecords.find((fitem) => fitem.retailId === item.id) ||
        paymentRecords.find(
          (fitem) => fitem.deceasedRetailId === item.deceasedRetailId
        );

      return {
        retail,
        deceased,
        payment,
        ...item,
      };
    });
  }
  if (checkoutRetailIds.length) {
    const checkouitRetails = await getConnection()
      .getRepository(CheckoutRetail)
      .createQueryBuilder("checkout_retail")
      .where("checkout_retail.id IN (:...ids)", {
        ids: checkoutRetailIds,
      })
      .getMany();

    let deceaseds = [];

    if (checkouitRetails.length) {
      const checkoutRetailsIds = Array.from(
        new Set(checkouitRetails.map((item) => Number(item.deceasedId)))
      );

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

      const paymentRecords = await getConnection()
        .getRepository(CheckoutPaymentRecords)
        .createQueryBuilder("paymentRecord")
        .where("paymentRecord.checkoutRetailId IN (:...ids)", {
          ids: checkoutRetailIds,
        })
        .getMany();

      result.list = result.list.map((item: any) => {
        let retail = checkouitRetails.find(
          (fitem: any) => fitem.id === item.checkoutRetailId
        );

        let deceased = deceaseds.find(
          (fitem) => fitem.id === retail.deceasedId
        );

        let payment = paymentRecords.find(
          (fitem) => fitem.checkoutRetailId === item.checkoutRetailId
        );

        return {
          ...item,
          retail,
          deceased,
          payment,
        };
      });
    }
  }
}

router.get("/list", async (req, res) => {
  try {
    const result: any = await curd({
      entity: CancelRetail,
      req,
      params: {
        examineState: 0,
      },
    }).queryList();

    // console.log(result);

    await getMoreInfor(result);

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

// 查询逝者列表（支持分页）
router.post("/query", async (req, res) => {
  try {
    const result = await curd({
      entity: CancelRetail,
      req,
      params: {
        ...req.body,
      },
    }).queryList();

    await getMoreInfor(result, 1);

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

router.post("/cancel", async (req, res) => {
  try {
    const connection = getConnection();
    const deceaseRetailRep = connection.getRepository(DeceasedRetail);
    const cancelRetailRep = connection.getRepository(CancelRetail);

    let findDeceaseRetail = await deceaseRetailRep.findOne(
      Number(req.body.deceasedRetailId)
    );
    let cancelRetail = new CancelRetail();

    findDeceaseRetail.cancelState = 1;

    cancelRetail = {
      ...cancelRetail,
      ...req.body.cancelForm,
    };

    // 结账处理
    cancelRetail.deceasedRetailId = findDeceaseRetail.id;
    cancelRetail.cancelDate = new Date();

    await deceaseRetailRep.save(findDeceaseRetail);
    await cancelRetailRep.save(cancelRetail);

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

router.post("/examine", async (req, res) => {
  let examineState = req.body.examineState;
  let id = req.body.id;
  let connection = getConnection();

  if (examineState === 1) {
    try {
      let cancleRetailRep = connection.getRepository(CancelRetail);
      let cancleRetail = await cancleRetailRep.findOne(id);

      let cancelPaymentRep = connection.getRepository(CancelPayment);
      let cancelPayment = new CancelPayment();

      cancelPayment = { ...req.body.payment };
      delete cancelPayment.id;
      cancelPayment.retailId = cancleRetail.id;

      await cancelPaymentRep.save(cancelPayment);

      cancleRetail.examineState = 1;
      cancleRetail.examineDate = new Date();

      if (req.body.checkoutRetailId) {
        let checkoutRetailRep = connection.getRepository(CheckoutRetail);
        let checkoutRetail = await checkoutRetailRep.findOne(
          req.body.checkoutRetailId
        );
        checkoutRetail.cancelState = 1;

        await checkoutRetailRep.save(checkoutRetail);
      }

      if (req.body.deceasedRetailId) {
        let deceasedRetailRep = connection.getRepository(DeceasedRetail);
        let deceasedRetail = await deceasedRetailRep.findOne(
          req.body.deceasedRetailId
        );
        deceasedRetail.cancelState = 0;
        deceasedRetail.retailState = 0;

        await deceasedRetailRep.save(deceasedRetail);
      }
      await cancleRetailRep.save(cancleRetail);

      let paymentRep = connection.getRepository(PaymentRecord);
      let findPaymeny = await paymentRep.findOne(req.body.payment.id);

      if (findPaymeny) {
        findPaymeny.cashAmount = 0;
        findPaymeny.unionPayAmount = 0;
        findPaymeny.cardAmount = 0;
        findPaymeny.publicTransferAmount = 0;
        findPaymeny.workshopPayment = 0;
        await paymentRep.save(findPaymeny);
      }

      res.send({ code: 200, data: cancleRetail });
    } catch (err) {
      res.status(500).send({ code: 500, msg: err.message });
    }
  }
  if (examineState === 2) {
    try {
      let cancleRetailRep = getConnection().getRepository(CancelRetail);
      let cancleRetail = await cancleRetailRep.findOne(id);

      if (req.body.checkoutRetailId) {
        let checkoutRetailRep = getConnection().getRepository(CheckoutRetail);
        let checkoutRetail = await checkoutRetailRep.findOne(
          req.body.checkoutRetailId
        );
        checkoutRetail.cancelState = 1;

        await checkoutRetailRep.save(checkoutRetail);
      }

      if (req.body.deceasedRetailId) {
        let deceasedRetailRep = getConnection().getRepository(DeceasedRetail);
        let deceasedRetail = await deceasedRetailRep.findOne(
          req.body.deceasedRetailId
        );
        deceasedRetail.cancelState = 0;
        deceasedRetail.retailState = 1;

        await deceasedRetailRep.save(deceasedRetail);
      }

      await cancleRetailRep.remove(cancleRetail);

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

export default router;
