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

import Deceased from "@/entity/Deceased";
import CheckoutPayment from "@/entity/CheckoutPayment";
import DeceasedRetail from "@/entity/DeceasedRetail";
import { Request, Response } from "express";

import parseRangDate, {
  filterObjEmptyVal,
  getPaginationParams,
} from "@/util/globalMethods";
import dayjs from "dayjs";

const router = express.Router();

// 统一查询方法
async function queryRetailRecords(params: {
  req: Request;
  retailState?: number;
  isQuery?: boolean;
}): Promise<{
  list: any[];
  total: number;
  pageSize: number;
  pageNumber: number;
}> {
  const { req, retailState } = params;
  const { pageSize, pageNumber } = getPaginationParams(req);
  const alias = "r";
  const paymentAlias = "p";
  const deceasedAlias = "d";

  let { startDate, endDate } = parseRangDate(req);
  // 初始化查询构造器
  const queryBuilder = getConnection()
    .getRepository(DeceasedRetail)
    .createQueryBuilder(alias)
    .leftJoinAndMapOne(
      `${alias}.paymentRecord`,
      CheckoutPayment,
      paymentAlias,
      `${paymentAlias}.checkout_retail_id = ${alias}.id`
    )
    .leftJoinAndMapOne(
      `${alias}.deceased`,
      Deceased,
      deceasedAlias,
      `${deceasedAlias}.id = ${alias}.deceasedId`
    )
    .where(`${alias}.retailType = 0`)
    .andWhere(`${alias}.cancelState = 0`);

  // 零售状态筛选
  if (typeof retailState === "number") {
    queryBuilder.andWhere(`${alias}.retailState = :retailState`, {
      retailState,
    });
  }

  queryBuilder.andWhere(
    new Brackets((qb) =>
      qb
        .where(`${alias}.serviceItems IS NOT NULL`)
        .andWhere(`${alias}.serviceItems != ''`)
    )
  );

  if (startDate && endDate) {
    queryBuilder
      .andWhere(`p.checkoutDate BETWEEN :start AND :end`)
      .setParameters({ start: startDate, end: endDate });
  }

  // 动态处理查询参数
  const queryParams: any = filterObjEmptyVal(
    req.method === "GET" ? req.query : req.body
  );
  Object.entries(queryParams).forEach(([key, value]) => {
    if (["pageSize", "pageNumber"].includes(key)) return;
    if (value === undefined || value === "") return;

    switch (key) {
      // case "checkoutDate":
      //   queryBuilder.andWhere(`${paymentAlias}.checkoutDate = :checkoutDate`, {
      //     checkoutDate: value,
      //   });
      //   break;
      case "gender":
        queryBuilder.andWhere(`${deceasedAlias}.gender = :gender`, {
          gender: value,
        });
        break;
      case "name":
        queryBuilder.andWhere(`${deceasedAlias}.name LIKE :name`, {
          name: `%${value}%`,
        });
        break;
      default:
        if (key.startsWith("deceased.")) {
          const field = key.split(".")[1];
          queryBuilder.andWhere(`${deceasedAlias}.${field} = :${field}`, {
            [field]: value,
          });
        } else if (
          Object.keys(queryBuilder.expressionMap.parameters).includes(key)
        ) {
          // 处理重复参数名
          const uniqueKey = `${key}_${Date.now()}`;
          queryBuilder.andWhere(`${alias}.${key} = :${uniqueKey}`, {
            [uniqueKey]: value,
          });
        } else {
          if (!["purchaseDate", "startDate", "endDate"].includes(key)) {
            queryBuilder.andWhere(`${alias}.${key} = :${key}`, {
              [key]: value,
            });
          }
        }
    }
  });

  // 执行分页查询
  const [list, total] = await queryBuilder
    .orderBy(`${alias}.createDate`, "DESC")
    .skip((pageNumber - 1) * pageSize)
    .take(pageSize)
    .getManyAndCount();

  return { list, total, pageSize, pageNumber };
}

// 列表接口
router.get("/list", async (req: Request, res: Response) => {
  try {
    const result = await queryRetailRecords({
      req,
      retailState: Number(req.query.retailState),
    });

    res.json({
      code: 200,
      data: {
        list: result.list,
        pageNumber: result.pageNumber,
        pageSize: result.pageSize,
        total: result.total,
      },
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: err.message,
    });
  }
});

// 查询接口
router.post("/query", async (req: Request, res: Response) => {
  try {
    const result = await queryRetailRecords({
      req,
      isQuery: true,
    });

    res.json({
      code: 200,
      data: {
        list: result.list,
        pageNumber: result.pageNumber,
        pageSize: result.pageSize,
        total: result.total,
      },
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: err.message,
    });
  }
});

router.post("/confirmCheckout", 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(CheckoutPayment);

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

    let newPaymentRecord = new CheckoutPayment();

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

    newPaymentRecord = Object.assign({}, req.body.currentPayment);
    newPaymentRecord.checkoutRetailId = deceasedRetail.id;

    await deceasedRetailRep.save(deceasedRetail);
    // await cancelRecordRep.save(newCancleRetail);
    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;
