<template>
  <el-form
    style="max-height: 72vh; overflow-y: auto"
    ref="formRef"
    :model="regisForm"
    label-width="120px"
    label-position="right">
    <inforCard title="逝者信息" v-if="showList.includes('逝者信息')">
      <el-row :gutter="20" v-if="!regisForm.deceased">
        <el-col :span="8">
          <el-form-item label="逝者姓名" prop="name">
            <el-input
              v-model="regisForm.name"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="证件号码" prop="idNumber">
            <el-input
              v-model="regisForm.idNumber"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="gender">
            <el-radio-group
              v-model="regisForm.gender"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              ">
              <el-radio-button label="男" value="男"></el-radio-button>
              <el-radio-button label="女" value="女"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="regisForm.age"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-else>
        <el-col :span="8">
          <el-form-item label="逝者姓名" prop="name">
            <el-input
              v-model="regisForm.deceased.name"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="证件号码" prop="idNumber">
            <el-input
              v-model="regisForm.deceased.idNumber"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="gender">
            <el-radio-group
              v-model="regisForm.deceased.gender"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              ">
              <el-radio-button label="男" value="男"></el-radio-button>
              <el-radio-button label="女" value="女"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="regisForm.deceased.age"
              :disabled="
                props.type !== '服务修改' && props.type !== '服务登记'
              " />
          </el-form-item>
        </el-col>
      </el-row>
    </inforCard>

    <inforCard title="购买信息">
      <el-row :gutter="20">
        <el-col :span="8" v-if="props.retailType === 2">
          <el-form-item label="逝者姓名" prop="deceasedName">
            <el-input
              v-model="regisForm.deceasedName"
              placeholder="请输入逝者姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form v-model="regisForm"></el-form>
          <el-form-item label="引导员" prop="guide">
            <GuideList v-model="regisForm.guide"></GuideList>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="购买人" prop="buyer">
            <el-input
              :disabled="
                props.type !== '服务修改' &&
                props.type !== '服务登记' &&
                props.type !== '新增无逝者零售' &&
                props.type !== '修改无逝者登记'
              "
              v-model="regisForm.familyName"
              placeholder="请输入购买人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买人联系电话" prop="buyer">
            <el-input
              :disabled="
                props.type !== '服务修改' &&
                props.type !== '服务登记' &&
                props.type !== '新增无逝者零售' &&
                props.type !== '修改无逝者登记'
              "
              v-model="regisForm.familyPhone"
              placeholder="请输入购买人电话" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="所在区域">
            <el-cascader
              :disabled="
                props.type !== '服务修改' &&
                props.type !== '服务登记' &&
                props.type !== '新增无逝者零售' &&
                props.type !== '修改无逝者登记'
              "
              :options="pcaTextArrData"
              v-model="selectedOptions"
              @change="methods.pcaChange"></el-cascader> </el-form-item
        ></el-col>

        <el-col :span="8">
          <el-form-item label="详细地址">
            <el-input
              v-model="regisForm.address"
              :disabled="
                props.type !== '服务修改' &&
                props.type !== '服务登记' &&
                props.type !== '新增无逝者零售' &&
                props.type !== '修改无逝者登记'
              "
              placeholder="请输入你的地址"></el-input> </el-form-item
        ></el-col>

        <el-col :span="8">
          <el-form-item label="购买日期" prop="purchaseDate">
            <el-date-picker
              v-model="regisForm.purchaseDate"
              type="datetime"
              placeholder="选择日期"
              format="YYYY-MM-DD: HH:mm:ss" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="经办人" prop="handler">
            <el-input
              v-model="regisForm.handler"
              disabled
              placeholder="请输入经办人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售金额" prop="salesAmount">
            <el-input
              v-model.number="regisForm.salesAmount"
              disabled
              type="number">
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </inforCard>

    <inforCard title="已选服务项目">
      <div style="display: flex; align-items: center">
        <el-button
          type="primary"
          size="small"
          @click="methods.addServiceItem"
          v-if="props.type !== '零售结算'"
          >新增项目</el-button
        >
        <el-button
          type="default"
          size="small"
          @click="methods.customInput"
          v-if="props.type !== '零售结算'"
          >手工录入</el-button
        >
      </div>

      <el-table
        :data="regisForm.services"
        :style="{ marginTop: (props.type !== '零售结算' ? 15 : 0) + 'px' }">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="quantity" label="数量" width="80">
          <template #default="{ row }">
            <span v-if="row.name === '殡仪定制服务'">
              <el-input v-model="row.quantity"></el-input>
            </span>
            <span v-else>{{ row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80">
          <template #default="{ row }">
            <span v-if="row.name === '殡仪定制服务'">
              <el-input v-model="row.unit"></el-input>
            </span>
            <span v-else>{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价（元）">
          <template #default="{ row }">
            <span v-if="row.name === '殡仪定制服务'">
              <el-input v-model="row.price"></el-input>
            </span>
            <span v-else>
              {{ row.price }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="总金额">
          <template #default="{ row }">
            {{ row.price * row.quantity }} 元
          </template>
        </el-table-column>
        <el-table-column prop="remark" width="200" label="备注">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.remark"
              placement="top">
              <p
                style="
                  white-space: nowrap; /* 强制不换行 */
                  overflow: hidden; /* 隐藏溢出内容 */
                  text-overflow: ellipsis; /* 显示省略号 */
                ">
                {{ row.remark }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column>
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              v-if="props.showServiceDelBtn"
              @click="methods.removeProduct(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </inforCard>

    <base-curd-dialog
      v-model="customServiceState.show2LevelPage.value"
      title="手工录入服务"
      width="50%"
      @addConfim="addConfim"
      @closeConfirm="handleDialogClose"
      :showPageType="customServiceState.showPageType">
      <template #content>
        <serviceListaddOrEdit
          type="手工录入服务"
          :executeType="customServiceState.executeType.value"
          v-model="currentServiceItem"></serviceListaddOrEdit>
      </template>
      <template #footer>
        <el-button type="primary" @click="methods.confirmCustomService"
          >确定</el-button
        >
      </template>
    </base-curd-dialog>
    <el-drawer
      v-model="serviceItemState.showDrawer"
      size="50%"
      :with-header="false">
      <serviceItemSelect v-model="regisForm.services"></serviceItemSelect>
    </el-drawer>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { userInfor } from "@/store/user/user";
import serviceItemSelect from "./serviceItemSelect.vue";
import dayjs from "dayjs";
import api from "@/lib/request";
import pageVisible from "@/components/curdDialog/pageVisibleState";
import { ElMessage, ElMessageBox } from "element-plus";
import serviceListaddOrEdit from "../../serviceList/serviceItem/page/addOrEdit.vue";
import { defaultRetail } from "@/defaultForm/defaultRetail";
import { defaultServiceItem } from "@/defaultForm/defaultSerivceItem";
import { pcaTextArr } from "element-china-area-data";
import GuideList from "@/components/guideList/guideList.vue";

const formRef = ref();
const userStoreState = userInfor();
const serviceItemState = ref({
  showDrawer: false,
});

const customServiceState = new pageVisible({
  add: "新增服务项目",
  edit: "服务项目编辑",
  view: "服务项目查看",
});

// 表单数据
const regisForm = defineModel<RegisForm>({
  default: defaultRetail(),
});

const selectedOptions = ref([
  regisForm.value.province,
  regisForm.value.city,
  regisForm.value.area,
]);

const pcaTextArrData = ref(pcaTextArr);

const props = withDefaults(
  defineProps<{
    add?: boolean;
    type?: RegistrationType;
    showServiceDelBtn?: boolean;
    retailType?: number;
    showList?: string[];
  }>(),
  {
    add: false,
    showServiceDelBtn: true,
    type: "服务登记",
    retailType: 0,
    showList: () => [],
  }
);

if (["零售登记", "服务登记"].includes(props.type)) {
  regisForm.value.serviceItems = "";
  regisForm.value.services = [];
}

const methods = {
  addServiceItem() {
    if (!regisForm.value.services?.length) {
      regisForm.value.services = [];
    }
    serviceItemState.value.showDrawer = true;
  },
  removeProduct(row: Product) {
    let index = regisForm.value.services?.findIndex(
      (item: any) => item.name === row.name
    );
    regisForm.value.services = regisForm.value.services?.filter(
      (_, i) => i !== index
    );
  },
  customInput() {
    customServiceState.show2LevelPage.value = true;
  },
  async confirmCustomService() {
    if (!currentServiceItem.value.name)
      return ElMessage.warning("服务项目名称不能为空！");
    if (
      currentServiceItem.value.price <= 0 ||
      currentServiceItem.value.quantity <= 0
    ) {
      await ElMessageBox.confirm(
        "该商品售价或商品数量为0，是否继续？",
        "提示",
        {
          type: "warning",
        }
      );
      if (!regisForm.value.services) regisForm.value.services = [];
      regisForm.value.services.push({ ...currentServiceItem.value });
      customServiceState.show2LevelPage.value = false;

      currentServiceItem.value = defaultServiceItem();
      return;
    }
    await ElMessageBox.confirm("确定新增该条信息吗？", "提示", {
      type: "warning",
    });

    if (!regisForm.value.services) regisForm.value.services = [];
    regisForm.value.services.push({ ...currentServiceItem.value });
    customServiceState.show2LevelPage.value = false;

    currentServiceItem.value = defaultServiceItem();
  },
  pcaChange(data: { [key: string]: any }) {
    regisForm.value.province = data[0];
    regisForm.value.city = data[1];
    regisForm.value.area = data[2];
  },
};

onMounted(async () => {
  if (
    !["零售登记", "服务登记"].includes(props.type) &&
    (regisForm.value.deceasedId || regisForm.value.id)
  ) {
    let url =
      "/deceased-retail/selected-service?deceasedId=" +
      (regisForm.value.deceasedId || regisForm.value.id) +
      "&retailType=" +
      props.retailType;

    if (regisForm.value.id && props.retailType === 2) {
      url =
        "/deceased-retail/selected-service?retailId=" +
        regisForm.value.id +
        "&retailType=" +
        props.retailType;
    }

    if (["零售修改", "零售结算"].includes(props.type)) {
      url =
        "/deceased-retail/selected-service?retailId=" +
        regisForm.value.id +
        "&retailType=" +
        props.retailType;
    }

    const selectedService = await api().get(url);

    regisForm.value.services = selectedService.data.list;
  }

  watch(
    () => regisForm.value.services,
    (newVal) => {
      if (newVal) {
        regisForm.value.salesAmount = 0;
        newVal?.forEach(
          (item) => (regisForm.value.salesAmount += item.price * item.quantity)
        );

        if (props.type === "服务登记") {
          regisForm.value.serviceItems = newVal
            .map((item) => item.id)
            .join(",");
        }
      }
    },
    { deep: true }
  );
  regisForm.value = {
    ...regisForm.value,
    handler: regisForm.value.handler || userStoreState.userInfor.name || "",
    purchaseDate:
      regisForm.value.purchaseDate ||
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
  };
});
let currentServiceItem = ref<ServiceItemType>(defaultServiceItem());
async function addConfim() {
  await ElMessageBox.confirm("确定新增该条信息吗？", "提示", {
    type: "warning",
  });
  if (!regisForm.value.services) regisForm.value.services = [];
  regisForm.value.services.push({ ...currentServiceItem.value });

  // await ElMessageBox.confirm("确定新增该条信息吗？", "提示", {
  //   type: "warning",
  // });
  // let res = await api().post("/service-item/add", currentServiceItem.value);
  // if (res.code === 200) {
  //   ElMessage.success("添加成功");
  //   customServiceState.show2LevelPage.value = false;
  // } else {
  //   ElMessage.error(res.msg);
  // }
}

function handleDialogClose() {
  customServiceState.show2LevelPage.value = false;
}
</script>
<style lang="scss" scoped></style>
