<template>
  <div>
    <el-row>
      <baseTableHeader
        title="无逝者零售"
        @resetSearch="methods.resetSearch"
        @search="methods.search">
        <template #content>
          <el-form :model="searchForm" label-position="right">
            <el-row :gutter="12">
              <el-col :span="6">
                <el-form-item label="逝者姓名">
                  <el-input
                    v-model="searchForm.deceased.name"
                    placeholder="请输入逝者姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="购买人姓名">
                  <el-input
                    v-model="searchForm.retail.familyName"
                    placeholder="请输入购买人姓名"></el-input> </el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item label="引导员">
                  <GuideList v-model="searchForm.retail.guide"></GuideList>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="购买日期">
                  <el-date-picker
                    v-model="searchForm.retail.purchaseDate"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="选择日期"
                    end-placeholder="选择日期"
                    @change="dataChange" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </baseTableHeader>
    </el-row>
    <el-card style="margin-top: 8px">
      <base-table
        :option="tableOption"
        ref="table"
        border
        show-summary
        :summary-method="getSummaries">
        <template #toolsBar>
          <el-button size="small" type="primary" @click="methods.add">
            <template #icon>
              <el-icon>
                <CirclePlus />
              </el-icon> </template
            >新增</el-button
          >
        </template>
        <template #colunm>
          <el-table-column
            type="index"
            width="80"
            fixed="left"
            align="center"></el-table-column>
          <el-table-column label="结账" align="center" width="120" fixed="left">
            <template #default="{ row }">
              <el-tag type="success" v-if="row.retailState === 1"
                >已结账</el-tag
              >
              <el-tag type="danger" v-if="row.retailState === 0">未结账</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="familyName"
            label="购买人"
            align="center"
            fixed="left">
            <template #default="{ row }">
              <span v-if="row.familyName">{{ row.familyName }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="deceasedName"
            label="逝者姓名"
            align="center"
            fixed="left">
            <template #default="{ row }">
              <span v-if="row.deceasedName">{{ row.deceasedName }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createDate"
            label="购买日期"
            width="200"
            align="center" />
          <el-table-column
            prop="createDate"
            label="结算日期"
            width="200"
            align="center">
            <template #default="{ row }">
              <span v-if="row.retailState === 1"> {{ row.checkoutDate }} </span>
              <span v-else style="color: #999; font-style: italic">--</span>
            </template>
          </el-table-column>
          <el-table-column prop="salesAmount" label="销售金额" align="center" />

          <el-table-column
            label="现金支付"
            width="150"
            prop="payment.cashAmount"
            align="center">
            <template #default="{ row }">
              {{ row.payment?.cashAmount || "0.00" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="payment.unionPayAmount"
            label="银联支付"
            width="150"
            align="center">
            <template #default="{ row }">
              {{ row.payment?.unionPayAmount || "0.00" }}
            </template>
          </el-table-column>

          <el-table-column
            prop="payment.cardAmount"
            label="刷卡金额"
            width="150"
            align="center">
            <template #default="{ row }">
              {{ row.payment?.cardAmount || "0.00" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="payment.publicTransferAmount"
            label="对公转账"
            width="150"
            align="center">
            <template #default="{ row }">
              {{ row.payment?.publicTransferAmount || "0.00" }}
            </template>
          </el-table-column>

          <el-table-column
            prop="payment.workshopPayment"
            label="车间支付"
            width="150"
            align="center">
            <template #default="{ row }">
              {{ row.payment?.workshopPayment || "0.00" }}
            </template>
          </el-table-column>
          <el-table-column prop="handler" label="经办人" align="center" />
          <el-table-column prop="guide" label="引导员" align="center" />
          <el-table-column
            width="320"
            label="操作"
            align="center"
            fixed="right">
            <template #default="{ row }">
              <el-row align="middle" justify="center">
                <el-button
                  v-if="row.retailState === 0"
                  size="small"
                  type="primary"
                  @click="methods.update(row)">
                  修改</el-button
                >
                <el-button @click="methods.viewProduct(row)" size="small">
                  零售清单</el-button
                >

                <el-button
                  size="small"
                  type="default"
                  @click="methods.print(row)"
                  >打印</el-button
                >
                <!-- <el-button
                  type="primary"
                  v-if="row.retailState === 0"
                  @click="methods.checkout(row)"
                  >结账</el-button
                > -->
                <el-button
                  size="small"
                  type="danger"
                  v-if="row.retailState !== 1"
                  @click="methods.delete(row)">
                  删除</el-button
                >
              </el-row>
            </template>
          </el-table-column>
        </template>
      </base-table>
    </el-card>

    <retailList v-model="showDialog" :option="retailListTable"></retailList>

    <baseDialog
      v-model="retailRegisState.showDialog"
      top="30px"
      :title="
        handlerType === 'add'
          ? '新增无逝者零售'
          : handlerType === 'update'
          ? '修改无逝者登记'
          : '零售登记'
      "
      @close="methods.dialogClose">
      <retailRegis
        v-model="regisForm"
        :add="handlerType === 'add'"
        :retailType="2"
        :type="
          handlerType === 'add'
            ? '新增无逝者零售'
            : handlerType === 'update'
            ? '修改无逝者登记'
            : '零售登记'
        "></retailRegis>
      <template #footer>
        <el-row justify="center" align="middle" style="margin-top: 15px">
          <el-button type="primary" @click="methods.addConfirm">保存</el-button>
          <el-button type="danger" @click="methods.close">关闭</el-button>
        </el-row>
      </template>
    </baseDialog>

    <printServicesPage
      v-model="showPrint"
      :deceased="deceased"
      :serviceUrl="serviceUrl">
    </printServicesPage>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { resetParams } from "@/util/globalMethods";
import { globalState } from "@/store";
import retailRegis from "../publicComponents/retailRegis.vue";
import api from "@/lib/request";
import { tableOptionType } from "@/types/table";
import { defaultRetail } from "@/defaultForm/defaultRetail";
import printServicesPage from "@/components/printPage/printServicesPage.vue";
import GuideList from "@/components/guideList/guideList.vue";

let retailListTable = ref<tableOptionType>({
  url: "/deceased-retail/selected-service",
  searchUrl: "",
  searchParams: {},
  executeType: "list",
});

let showPrint = ref(false);
let deceased = ref();
let serviceUrl = ref();

const retailRegisState = ref({
  showDialog: false,
});

let currentInfor = ref(undefined);
let showDialog = ref(false);

const handlerType = ref("新增无逝者零售");
const searchForm = reactive({
  deceased: {
    name: "",
  },
  retail: {
    guide: "", // 引导员
    purchaseDate: "", // 购买日期
    retailType: 2,
    familyName: "",
  },
});

const regisForm = ref<RegisForm>();

let table = ref();
let tableOption = ref<tableOptionType>({
  url: "/deceased-retail/list?retailType=2",
  searchUrl: "/deceased-retail/query",
  searchParams: searchForm,
  executeType: "list",
});
const methods = {
  update(row: RegisForm) {
    regisForm.value = row;
    handlerType.value = "update";
    retailRegisState.value.showDialog = true;
  },
  async delete(row: RegisForm) {
    await ElMessageBox.confirm("确定删除该条信息吗？", { type: "warning" });
    const res = await api().get("deceased-retail/delete", {
      params: {
        id: row.id,
      },
    });
    if (res.code === 200) {
      ElMessage.success("删除成功");
      table.value.methods.setDataType("list");
    } else {
      ElMessage.error(res);
    }
  },
  add() {
    retailRegisState.value.showDialog = true;
    handlerType.value = "add";
  },
  viewProduct(row: RegisForm) {
    retailListTable.value.url =
      "/deceased-retail/selected-service?retailType=2&retailId=" + row.id;
    showDialog.value = true;
  },
  drawerClose() {
    currentInfor.value = undefined;
    showDialog.value = false;
  },
  async addConfirm() {
    let url = "/no-deceased-retail/add";
    if (handlerType.value === "update") url = "/no-deceased-retail/update";
    await ElMessageBox.confirm("确定保存吗？", {
      type: "warning",
    });
    let sendData = { ...regisForm.value };
    api()
      .post(url, sendData)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("保存成功！");
          retailRegisState.value.showDialog = false;
          table.value.methods.setDataType("list");
        } else {
          ElMessage.error(res.msg);
        }
      });
  },
  async checkout(row: RegisForm) {
    await ElMessageBox.confirm("确定结账吗？", { type: "warning" });

    api()
      .get("/no-deceased-retail/checkout", {
        params: {
          id: Number(row.id),
        },
      })
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("结账成功！");
          retailRegisState.value.showDialog = false;
          table.value.methods.setDataType("list");
        } else {
          ElMessage.error(res.msg);
        }
      });
  },
  close() {
    retailRegisState.value.showDialog = false;
  },
  async print(row: any) {
    deceased.value = row;
    showPrint.value = true;

    serviceUrl.value =
      "/deceased-retail/selected-service?retailType=2&retailId=" + row.id;
  },
  dialogClose() {
    regisForm.value = defaultRetail();
  },
  search() {
    searchForm.retail.retailType = 2;
    table.value.methods.setDataType("search");
  },

  resetSearch() {
    resetParams(searchForm);
    table.value.methods.setDataType("reset");
  },
};

const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param;
  const sums: any[] = [];
  // 需要统计的字段列表
  const sumKeys = [
    "salesAmount",
    "payment.cashAmount",
    "payment.unionPayAmount",
    "payment.cardAmount",
    "payment.publicTransferAmount",
    "payment.workshopPayment",
  ];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (sumKeys.includes(column.property)) {
      const values = data.map((item) => {
        const keys = column.property.split(".");
        let value = item;
        for (const key of keys) {
          value = value?.[key] || 0;
        }
        return Number(value) || 0;
      });

      if (!values.every((value) => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          return prev + curr;
        }, 0);
        sums[index] = `${sum.toFixed(2)}`;
      } else {
        sums[index] = "0.00 元";
      }
    } else {
      sums[index] = "";
    }
  });

  return sums;
};

function dataChange(val: Date[]) {
  searchForm.retail.startDate = val[0];
  searchForm.retail.endDate = val[1];
}
</script>
<style lang="scss" scoped>
/* 添加汇总行样式 */
:deep(.el-table__footer) {
  .cell {
    font-weight: 600;
    color: #606266;
  }

  td {
    background-color: #f5f7fa !important;
  }
}
</style>
