<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="8">
                <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">
      <div style="margin-bottom: 15px">
        <el-button
          size="small"
          type="primary"
          @click="methods.add"
          v-if="route.path === '/noDepartedSaint'">
          <template #icon>
            <el-icon>
              <CirclePlus />
            </el-icon> </template
          >新增</el-button
        >
      </div>

      <div>
        <base-table
          :option="tableOption"
          ref="table"
          border
          show-summary
          :summary-method="getSummaries">
          <template #toolsBar>
            <el-radio-group
              v-model="searchForm.retail.retailType"
              size="small"
              style="margin-left: 15px">
              <el-radio-button label="逝者零售" :value="1" />
              <el-radio-button label="无逝者零售" :value="2" />
            </el-radio-group>
          </template>
          <template #colunm>
            <el-table-column
              type="index"
              width="80"
              fixed="left"
              align="center"></el-table-column>

            <el-table-column
              prop="deceased.name"
              label="逝者姓名"
              width="100"
              fixed="left"
              v-if="searchForm.retail.retailType === 1"
              align="center">
            </el-table-column>
            <el-table-column
              prop="name"
              label="结账"
              width="100"
              fixed="left"
              align="center">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.retailState === 0
                      ? 'danger'
                      : row.retailState === 1
                      ? 'success'
                      : 'info'
                  ">
                  {{
                    row.retailState === 0
                      ? "未结账"
                      : row.retailState === 1
                      ? "已结账"
                      : "未知"
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="购买人" align="center" fixed="left">
              <template #default="{ row }">
                <span>{{ row.familyName || row.deceased?.name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="familyPhone"
              label="购买人电话"
              width="120"
              align="center">
              <template #default="{ row }">
                <span>{{ row.deceased?.familyPhone || row.familyPhone }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="purchaseDate"
              label="购买日期"
              width="200"
              align="center" />
            <el-table-column
              prop="checkoutDate"
              label="结算日期"
              width="200"
              align="center">
              <template #default="{ row }">
                <span v-if="row.retailState === 1">
                  {{ row.checkoutDate }}
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="handler" label="经办人" align="center" />
            <el-table-column
              width="100"
              prop="salesAmount"
              label="销售金额"
              align="center" />

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

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

            <el-table-column
              prop="payment.workshopPayment"
              label="车间支付"
              width="100"
              align="center">
              <template #default="{ row }">
                {{ row.payment?.workshopPayment || "0.00" }} 元
              </template>
            </el-table-column>
            <el-table-column prop="guide" label="引导员" align="center" />
            <el-table-column
              width="300"
              label="操作"
              align="center"
              fixed="right">
              <template #default="{ row }">
                <el-row align="middle" justify="center">
                  <el-button
                    size="small"
                    type="primary"
                    v-if="row.retailState === 1"
                    @click="methods.hanlderView(row)">
                    查看</el-button
                  >
                  <el-button
                    type="primary"
                    size="small"
                    @click="methods.checkout(row)"
                    v-if="row.retailState === 0"
                    >结账</el-button
                  >
                  <el-button
                    v-if="row.retailState === 1"
                    size="small"
                    type="default"
                    @click="methods.cancel(row)">
                    作废
                  </el-button>
                  <el-button @click="methods.viewProduct(row)" size="small">
                    零售清单</el-button
                  >
                  <el-button @click="methods.print(row)" size="small"
                    >打印</el-button
                  >
                </el-row>
              </template>
            </el-table-column>
          </template>
        </base-table>
      </div>
    </el-card>

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

    <baseDialog
      v-model="retailRegisState.showDialog"
      top="50px"
      title="零售结算">
      <retailRegis
        v-model="regisForm"
        :retailType="searchForm.retail.retailType"
        :showServiceDelBtn="handlerType !== 'view'"
        :add="handlerType === 'add'"
        type="零售结算"></retailRegis>
      <template #footer>
        <el-row justify="center" align="middle" style="margin-top: 15px">
          <el-button type="danger" @click="methods.close">关闭</el-button>
        </el-row>
      </template>
    </baseDialog>
    <base-curd-dialog
      v-model="pageVisibleState.show2LevelPage.value"
      :title="pageVisibleState.dialogTitle.value"
      width="70%"
      :before-close="methods.handleDialogClose"
      @addConfim="methods.addConfim"
      @closeConfirm="methods.handleDialogClose"
      confirmText="结账"
      destroy-on-close
      :showPageType="pageVisibleState.showPageType">
      <template #content>
        <checkoutAddOrEdit
          :executeType="pageVisibleState.executeType.value"
          :deceased="currentData"
          v-model="currentPayment">
        </checkoutAddOrEdit>
      </template>
      <template #footer>
        <el-button type="primary" @click="methods.addConfim"
          >确定结账</el-button
        ></template
      >
    </base-curd-dialog>

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

    <base-dialog
      v-model="cancelState.showDialog"
      title="账单作废"
      width="50%"
      @closeConfirm="methods.cancleClose">
      <el-form :model="cancelForm" label-width="120px" style="padding: 20px">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 注销申请人 -->
            <el-form-item label="作废申请人">
              <el-input disabled v-model="cancelForm.cancelPerson" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 注销日期 -->
            <el-form-item label="作废日期">
              <el-date-picker
                disabled
                v-model="cancelForm.cancelDate"
                type="date" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 注销原因 -->
            <el-form-item label="作废原因">
              <el-input
                v-model="cancelForm.cancelReason"
                type="textarea"
                placeholder="请输入作废原因" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="flex-center">
          <el-button type="primary" @click="methods.submitCancel"
            >作废</el-button
          >
          <el-button @click="methods.resetCancel">取消</el-button>
        </div>
      </template>
    </base-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch, nextTick } from "vue";
import { dayjs, 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 { useRoute } from "vue-router";
import pageVisible from "@/components/curdDialog/pageVisibleState";
import { defaultPaymentForm } from "@/defaultForm/defaultPaymentForm";
import checkoutAddOrEdit from "./page/checkoutAddOrEdit.vue";
import printServicesPage from "@/components/printPage/printServicesPage.vue";
import { defaultRetail } from "@/defaultForm/defaultRetail";
import { userInfor } from "@/store/user/user";
import GuideList from "@/components/guideList/guideList.vue";

const pageVisibleState = new pageVisible({
  add: "结账登记",
  edit: "登记修改",
  view: "查看登记",
});

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

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

let currentRetail = ref<RegisForm>(defaultRetail());

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

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

const handlerType = ref("");
const searchForm = ref({
  retail: {
    guide: "", // 引导员
    startDate: "",
    endDate: "",
    purchaseDate: ["", ""],
    retailType: 1,
    familyName: "",
  },
  deceased: {
    name: "", // 逝者姓名
    familyName: "",
  },
});

let currentPayment = ref<PaymentForm>(defaultPaymentForm());
let currentData = ref();

const route = useRoute();

const regisForm = ref<RegisForm>();
const cancelState = ref({
  showDialog: false,
});
const globaUser = userInfor().userInfor;
const cancelForm = ref({
  cancelPerson: globaUser.name,
  cancelDate: dayjs().format(),
  cancelReason: "",
});

let table = ref();
let tableOption = ref<tableOptionType>({
  url: "/deceased-retail/list?retailType=" + searchForm.value.retail.retailType,
  searchUrl: "/deceased-retail/query",
  searchParams: searchForm.value,
  executeType: "list",
});
const methods = {
  add() {
    retailRegisState.value.showDialog = true;
    handlerType.value = "add";
  },
  cancel(row: RegisForm) {
    currentRetail.value = row;
    cancelState.value.showDialog = true;
  },
  viewProduct(row: RegisForm) {
    retailListTable.value.url =
      "/deceased-retail/selected-service?retailId=" + row.id;
    showDialog.value = true;
  },
  drawerClose() {
    currentInfor.value = undefined;
    showDialog.value = false;
  },
  async checkout(row: RegisForm) {
    currentData.value = row;
    pageVisibleState.dialogTitle.value = "零售结算";

    pageVisibleState.show2LevelPage.value = true;
  },
  async hanlderView(row: RegisForm) {
    // await ElMessageBox.confirm("确定结账吗？");
    regisForm.value = row;
    retailRegisState.value.showDialog = true;
    handlerType.value = "view";

    pageVisibleState.dialogTitle.value = "零售查看";
  },
  close() {
    retailRegisState.value.showDialog = false;
  },
  async cancle() {
    await ElMessageBox.confirm("确定作废该条吗？", { type: "error" });
    retailRegisState.value.showDialog = false;
    ElMessage.success("作废成功！");
  },
  print(row: RegisForm) {
    deceased.value = row;
    serviceUrl.value = `/deceased-retail/selected-service?retailType=${searchForm.value.retail.retailType}&retailId=${row.id}`;

    nextTick(() => {
      showPrint.value = true;
    });
  },
  search() {
    table.value.methods.setDataType("search");
  },

  resetSearch() {
    searchForm.value = {
      retail: {
        guide: "", // 引导员
        startDate: "",
        endDate: "",
        purchaseDate: ["", ""],
        retailType: 1,
        familyName: "",
      },
      deceased: {
        name: "", // 逝者姓名
        familyName: "",
      },
    };
    tableOption.value.searchParams = searchForm.value;
    nextTick(() => {
      table.value.methods.setDataType("search");
    });
  },

  async addConfim() {
    await ElMessageBox.confirm("确定结账吗？", { type: "warning" });

    let sendData = {
      deceased: {
        ...currentData.value,
      },
      currentPayment: {
        ...currentPayment.value,
      },
      id: currentData.value.id,
    };
    let url = "/checkout/deceasedCheckout";

    const res = await api().post(url, sendData);
    if (res.code === 200) {
      ElMessage.success("结账成功！");
      pageVisibleState.show2LevelPage.value = false;
      nextTick(() => {
        table.value.methods.setDataType("search");
        currentPayment.value = defaultPaymentForm();
        currentData.value = undefined;
      });
    } else {
      ElMessage.error(res.msg);
    }
  },

  handleDialogClose() {
    pageVisibleState.show2LevelPage.value = false;
    currentData.value = undefined;
    currentPayment.value = defaultPaymentForm();
  },
  cancleClose() {
    cancelForm.value = {
      cancelPerson: globaUser.name,
      cancelDate: dayjs().format(),
      cancelReason: "",
    };
  },

  async submitCancel() {
    if (!cancelForm.value.cancelReason) {
      return ElMessage.error("请输入作废原因");
    }
    await ElMessageBox.confirm("确定作废吗？", { type: "warning" });

    let sendData = {
      deceasedRetailId: currentRetail.value.id,
      cancelForm: { ...cancelForm.value },
      cancelType: 0,
    };

    api()
      .post("/cancel/cancel", sendData)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("作废提交成功！");
          methods.resetCancel();
          cancelForm.value = {
            cancelPerson: globaUser.name,
            cancelDate: dayjs().format(),
            cancelReason: "",
          };
          table.value.methods.setDataType("search");
        } else {
          ElMessage.error(res.msg);
        }
      });
  },
  resetCancel() {
    cancelForm.value = {
      cancelPerson: globaUser.name,
      cancelDate: dayjs().format(),
      cancelReason: "",
    };
    cancelState.value.showDialog = false;
  },
};

watch(
  () => searchForm.value.retail.retailType,
  () => {
    table.value.methods.setDataType("search");
  }
);

function dataChange(val: Date[]) {
  searchForm.value.retail.startDate = val[0];
  searchForm.value.retail.endDate = val[1];
}

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;
};
</script>
<style lang="scss" scoped>
/* 添加汇总行样式 */
:deep(.el-table__footer) {
  .cell {
    font-weight: 600;
    color: #606266;
  }

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