<template>
  <div>
    <el-row>
      <baseTableHeader
        title="殡仪服务"
        @resetSearch="resetSearch"
        @search="search">
        <template #content>
          <el-form
            :model="searchForm"
            :inline="true"
            label-position="right"
            label-width="80px">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="逝者姓名">
                  <el-input
                    v-model="searchForm.name"
                    placeholder="请输入逝者姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别">
                  <el-radio-group v-model="searchForm.gender">
                    <el-radio-button value="男" label="男"></el-radio-button>
                    <el-radio-button value="女" label="女"></el-radio-button>
                  </el-radio-group> </el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item label="购买人">
                  <el-input
                    v-model="searchForm.familyName"
                    placeholder="请输入购买人姓名"></el-input> </el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item label="购买人手机号">
                  <el-input
                    v-model="searchForm.familyPhone"
                    placeholder="请输入购买人手机号"></el-input> </el-form-item
              ></el-col>
              <el-col :span="6"
                ><el-form-item label="引导员">
                  <GuideList
                    v-model="searchForm.guide"></GuideList> </el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item label="录单日期">
                  <el-date-picker
                    v-model="searchForm.createDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="录单日期" /> </el-form-item
              ></el-col>
              <!-- <el-col :span="6">
                <el-form-item label="结账日期">
                  <el-date-picker
                    v-model="searchForm.checkoutDate"
                    type="date"
                    placeholder="结账日期" /></el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item label="录单日期">
                  <el-date-picker
                    v-model="searchForm.purchaseDate"
                    type="datetime"
                    placeholder="录单日期" /></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>
        <template #toolsBar>
          <el-button size="small" type="primary" @click="methods.handleService">
            服务办理</el-button
          >
        </template>
        <template #colunm>
          <el-table-column
            type="index"
            width="60"
            label="序号"
            align="center" />
          <el-table-column
            prop="deceased.name"
            label="逝者姓名"
            align="center" />
          <el-table-column prop="deceased.gender" label="性别" align="center" />
          <el-table-column
            prop="deceased.age"
            label="年龄"
            width="80"
            align="center" />
          <el-table-column
            prop="deceased.familyName"
            label="购买人姓名"
            align="center" />
          <el-table-column
            prop="deceased.familyPhone"
            label="购买人手机号"
            width="180"
            align="center" />
          <el-table-column prop="deceased.name" label="购买人" align="center" />
          <el-table-column
            prop="retail.purchaseDate"
            label="录单日期"
            width="180"
            align="center" />
          <el-table-column prop="handler" label="经办人" align="center" />
          <el-table-column
            prop="retail.salesAmount"
            label="销售金额"
            align="center"
            width="180">
            <template #default="{ row }">
              {{ row.retail.salesAmount || 0 }} 元
            </template>
          </el-table-column>
          <el-table-column
            prop="guide"
            label="引导员"
            width="120"
            align="center" />
          <el-table-column
            label="操作"
            align="center"
            width="350"
            fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="methods.addRetailRegis(row)">
                零售登记
              </el-button>
              <el-button
                v-if="row.retail?.retailState !== 1"
                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
              >
            </template>
          </el-table-column>
        </template>
      </base-table>
    </el-card>

    <baseDialog
      v-model="retailRegisState.showAddRetial"
      top="50px"
      :title="retailTitle"
      @close="methods.addRetialClose">
      <retailRegis
        v-model="retailRegisForm"
        :type="retailRegisState.type"
        :showList="['逝者信息']"></retailRegis>
      <template #footer>
        <el-row justify="center" align="middle" style="margin-top: 15px">
          <el-button type="primary" @click="methods.addConfim">保存</el-button>
          <el-button type="danger" @click="methods.addClose">关闭</el-button>
        </el-row>
      </template>
    </baseDialog>

    <baseDialog
      v-model="retailRegisState.showUpdateDialog"
      top="50px"
      :title="retailRegisState.title"
      @close="methods.resetRegisForm">
      <div
        v-loading="retailRegisState.showLoding"
        element-loading-text="正在处理...">
        <retailRegis
          v-model="regisForm"
          :type="retailRegisState.type"
          :showList="['逝者信息']"></retailRegis>

        <el-row :justify="'center'">
          <el-button type="primary" @click="methods.addConfim">确定</el-button>
          <el-button type="warning" @click="methods.updateClose"
            >关闭</el-button
          >
        </el-row>
      </div>
    </baseDialog>

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

    <retailList
      v-model="showRetailList"
      title="服务清单"
      :option="retailListTable"></retailList>
  </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 retailRegis from "../funeralRetail/publicComponents/retailRegis.vue";
import api from "@/lib/request";
import { tableOptionType } from "@/types/table";
import { defaultRetail } from "@/defaultForm/defaultRetail";
import PrintRetailPage from "@/components/printPage/printRetailPage.vue";
import GuideList from "@/components/guideList/guideList.vue";

interface deceasedForm extends RegisForm {
  deceased: RegisForm;
  retailType: number;
}

const retailRegisState = ref({
  showAddRetial: false,
  title: "服务登记",
  type: "服务登记" as RegistrationType,
  showLoding: false,
  showUpdateDialog: false,
});
const serviceState = ref({
  showDialog: false,
});

let showRetailList = ref(false);

let retailTitle = ref("服务登记");

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

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

const searchForm = reactive({
  name: "", // 逝者姓名
  gender: "", // 性别
  phone: "", // 手机号
  guide: "", // 引导员
  purchaseDate: "", // 购买日期
  createDate: "",
  familyName: "",
  familyPhone: "",
});

const regisForm = ref<deceasedForm>(defaultRetail());
const retailRegisForm = ref<RegisForm>(defaultRetail());

let table = ref();
const tableOption = ref<tableOptionType>({
  url: "/deceased/list", // 获取列表数据的接口
  searchUrl: "/deceased/query", // 搜索接口
  searchParams: searchForm, // 搜索表单数据
  executeType: "list", // 默认执行类型
});

const methods = {
  // 零售登记
  addRetailRegis(item: RegisForm) {
    retailRegisForm.value = {
      ...regisForm.value,
      ...item,
      serviceItems: [],
      services: [],
    };
    retailRegisState.value.title = "零售登记";
    retailRegisState.value.type = "零售登记";
    retailRegisState.value.showAddRetial = true;
    retailTitle.value = "零售登记";
  },

  async print(row: any) {
    deceased.value = row;
    showPrint.value = true;

    serviceUrl.value =
      "/deceased-retail/selected-service?retailType=0&deceasedId=" + row.id;
  },
  drawerClose() {
    showRetailList.value = false;
  },

  async viewProduct(row: RegisForm) {
    retailListTable.value.url =
      "/deceased-retail/selected-service?retailType=0&deceasedId=" + row.id;
    showRetailList.value = true;
  },

  update(row: RegisForm) {
    regisForm.value = row;
    retailTitle.value = "服务修改";
    retailRegisState.value.title = "服务修改";
    retailRegisState.value.type = "服务修改";
    retailRegisState.value.showUpdateDialog = true;
  },

  // 服务办理
  handleService() {
    retailRegisForm.value = defaultRetail();
    serviceState.value.showDialog = true;
    retailRegisState.value.showAddRetial = true;
    retailRegisState.value.title = "服务登记";
    retailRegisState.value.type = "服务登记";
    retailTitle.value = "服务登记";
  },

  // 重置登记表单
  resetRegisForm() {
    regisForm.value = defaultRetail();
  },

  // 取消操作
  cancle() {
    retailRegisState.value.showAddRetial = false;
    methods.resetRegisForm();
  },

  updateClose() {
    retailRegisState.value.showUpdateDialog = false;
  },
  addClose() {
    retailRegisState.value.showAddRetial = false;
    regisForm.value = defaultRetail();
  },

  async confirmUpdate() {
    await ElMessageBox.confirm("确定保存修改吗？", { type: "warning" });
    let sendData = { ...regisForm.value };
    api()
      .post("/deceased-retail/update", sendData)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("修改成功");
          table.value.methods.setDataType("list");
          retailRegisState.value.showAddRetial = false;
          regisForm.value = defaultRetail();
        }
      });
  },

  async addConfim() {
    if (retailRegisState.value.type === "服务登记") {
      if (!retailRegisForm.value.idNumber || !retailRegisForm.value.name) {
        return ElMessage.error("逝者姓名和证件号码不能为空！");
      }
    }

    let confirmContent = "";
    if (retailRegisState.value.type === "服务登记")
      confirmContent = "确定登记该服务吗？";
    if (retailRegisState.value.type === "零售登记")
      confirmContent = "确定登记该信息吗？";
    if (retailRegisState.value.type === "服务修改")
      confirmContent = "确定修改该信息吗？";

    await ElMessageBox.confirm(confirmContent, "提示", {
      type: "warning",
    });

    if (retailRegisState.value.type === "服务登记") {
      let sendData = { ...retailRegisForm.value };
      sendData.retailType = 0;
      api()
        .post("/deceased/add", sendData) // 修改为 Deceased 的接口
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("新增成功！");
            table.value.methods.setDataType("list");
            retailRegisState.value.showAddRetial = false;
            retailRegisState.value.showLoding = false;
            methods.resetRegisForm();
          } else {
            ElMessage.error(res.msg);
          }
        });
    }
    if (retailRegisState.value.type === "零售登记") {
      let sendData = { ...retailRegisForm.value };
      sendData.retailType = 1;

      sendData.deceasedId = sendData.id;

      let url = "/deceased-retail/add?type=1";

      api()
        .post(url, sendData) // 修改为 Deceased 的接口
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("新增成功！");
            table.value.methods.setDataType("list");
            retailRegisState.value.showAddRetial = false;
            retailRegisState.value.showLoding = false;
            methods.resetRegisForm();
          } else {
            ElMessage.error(res.msg);
          }
        });
    }
    if (retailRegisState.value.type === "服务修改") {
      let sendData = { ...regisForm.value };
      sendData.retailType = 0;
      sendData.deceased.familyName = sendData.familyName;
      sendData.deceased.familyPhone = sendData.familyPhone;
      sendData.deceased.address = sendData.address;
      sendData.deceased.area = sendData.area;
      sendData.deceased.province = sendData.province;
      sendData.deceased.city = sendData.city;
      sendData.deceased.guide = sendData.guide;
      api()
        .post("/deceased-retail/updateRetail", sendData) // 修改为 Deceased 的接口
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("修改成功！");
            table.value.methods.setDataType("list");
            retailRegisState.value.showAddRetial = false;
            retailRegisState.value.showLoding = false;
            retailRegisState.value.showUpdateDialog = false;

            methods.resetRegisForm();
          } else {
            ElMessage.error(res.msg);
          }
        });
    }
  },
  addRetialClose() {
    retailRegisState.value.showAddRetial = false;
    regisForm.value = defaultRetail();
  },
};

onMounted(async () => {});

function search() {
  table.value.methods.setDataType("search");
}

function resetSearch() {
  resetParams(searchForm);
  table.value.methods.setDataType("reset");
}
</script>
<style lang="scss" scoped></style>
