<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElButton, ElImage, ElTag } from 'element-plus';

import { getCoupon2AuditDetailApi } from '#/api/coupon/coupon2';
import { getDictListApi } from '#/api/dict';
import { getAttachmentListApi } from '#/api/file';
import { getCustomerDetailApi } from '#/api/user';

import EditBuyerInfoModal from './edit-buyer-info-modal.vue';

const data = ref<any>(null);
const loading = ref(false);
const dealerName = ref('');

// 监听data的变化，当data有值且userssuperiorid存在时，获取经销商名称
watch(
  () => data.value,
  async (newData) => {
    if (newData && newData.userssuperiorid) {
      try {
        const res = await getCustomerDetailApi({
          usersid: newData.userssuperiorid,
        });
        dealerName.value = res.usersname || '未知';
      } catch (error) {
        console.error('获取经销商名称失败:', error);
        dealerName.value = '获取失败';
      }
    } else {
      dealerName.value = '';
    }
  },
  { deep: true },
);

// 身份证附件数据
const certificateDataList = ref<any[]>([]);
// 购机者照片数据
const buyerPhotoDataList = ref<any[]>([]);

// 修改购机者信息模态框引用
const editBuyerInfoModalRef = ref<InstanceType<typeof EditBuyerInfoModal>>();

// 申请人信息
const applicantInfo = computed(() => {
  if (!data.value) return [];

  const baseInfo = [
    { label: '姓名', value: data.value.usersname },
    { label: '手机号', value: data.value.usersphone },
    { label: '身份证号', value: data.value.usersidcardnumber },
    { label: '用户类型', value: data.value.userstype },
    { label: '用户性质', value: data.value.usersnature },
    { label: '邮箱', value: data.value.usersemail },
    { label: '地址', value: data.value.usersaddress },
  ];

  // 如果用户类型不是"个人"，显示社会统一信用代码
  if (data.value.userstype !== '个人') {
    baseInfo.push({
      label: '社会统一信用代码',
      value: data.value.usersshtyxydm,
    });
  }

  return baseInfo;
});

// 产品信息
const productInfo = computed(() => {
  if (!data.value) return [];
  return [
    { label: '产品名称', value: data.value.productsname },
    { label: '产品型号', value: data.value.productsmodel },
    { label: '产品类别', value: data.value.productscategory },
    { label: '机具类型', value: data.value.productsjjlx },
    {
      label: '产品价格',
      value: data.value.productsprice ? `¥${data.value.productsprice}` : '',
    },
    {
      label: '推广补贴',
      value: data.value.productstsxzybt ? `¥${data.value.productstsxzybt}` : '',
    },
    {
      label: '中央补贴',
      value: data.value.productszybt ? `¥${data.value.productszybt}` : '',
    },
    { label: '产品序列号', value: data.value.productssn },
    { label: '分档编号', value: data.value.productsfdbh },
    { label: '分档名称', value: data.value.productsfdmc },
    { label: '生产企业', value: data.value.scqyinfomc },
    { label: '企业地址', value: data.value.scqyinfoaddress },
    // { label: '法人姓名', value: data.value.scqyinfofrmc },
    // { label: '销售姓名', value: data.value.scqyinfoxsmc },
    // { label: '销售电话', value: data.value.scqyinfoxsphone },
    // { label: '统一社会信用代码', value: data.value.scqyinfoshtydm },
    // {
    //   label: '注册资本',
    //   value: data.value.scqyinfozczb ? `¥${data.value.scqyinfozczb}` : '',
    // },
  ];
});

// 优惠券状态映射
const getCouponStatusTag = (status: number) => {
  const statusMap = {
    0: { text: '申请中', type: 'info' },
    1: { text: '审核通过', type: 'success' },
    2: { text: '审核不通过', type: 'danger' },
  } as const;
  return (
    statusMap[status as keyof typeof statusMap] || {
      text: '未知',
      type: 'warning',
    }
  );
};

// 使用状态映射
const getUsedStatusTag = (status: number) => {
  const statusMap = {
    0: { text: '未使用', type: 'info' },
    1: { text: '已使用', type: 'success' },
  } as const;
  return (
    statusMap[status as keyof typeof statusMap] || {
      text: '未知',
      type: 'warning',
    }
  );
};

// 优惠券信息
const couponInfo = computed(() => {
  if (!data.value) return [];

  const baseInfo = [
    // { label: '优惠券ID', value: data.value.coupon2sid },
    { label: '优惠券代码', value: data.value.coupon2code },
    { label: '优惠券名称', value: data.value.coupon2mc },
    { label: '申请时间', value: data.value.coupon2adddatetime },
    { label: '审核时间', value: data.value.coupon2reviewdatetime || '未审核' },
    {
      label: '使用状态',
      value: data.value.coupon2isused,
      isTag: true,
      tagType: 'usedStatus',
    },
    {
      label: '优惠券状态',
      value: data.value.coupon2sype,
      isTag: true,
      tagType: 'couponStatus',
    },
    // { label: '可用产品ID', value: data.value.coupon2productids },
    // { label: '关联主券ID', value: data.value.coupon2coupon1id },
    // { label: '订单编号', value: data.value.ordersnumber },
    // {
    //   label: '订单总价',
    //   value: data.value.orderstotalprice
    //     ? `¥${data.value.orderstotalprice}`
    //     : '',
    // },
    // {
    //   label: '优惠价格',
    //   value: data.value.ordersyhprice ? `¥${data.value.ordersyhprice}` : '',
    // },
    // {
    //   label: '折扣价格',
    //   value: data.value.ordersdiscountprice
    //     ? `¥${data.value.ordersdiscountprice}`
    //     : '',
    // },
    // { label: '下单时间', value: data.value.ordersorderdate },
    { label: '经销商名称', value: dealerName.value },
  ];

  // 如果优惠券状态为2（审核不通过），显示审核备注
  if (data.value.coupon2sype === 2) {
    baseInfo.push({ label: '审核备注', value: data.value.coupon2shbz });
  }

  return baseInfo;
});

// 获取文件前缀地址
const getFilePrefix = async () => {
  const filePrefixData = await getDictListApi({
    groupname: 'fileheadurl',
    pageindex: 1,
    rows: 999,
  });

  if (filePrefixData.Data.length > 0) {
    return filePrefixData.Data[0].substance;
  }

  return '';
};

// 获取身份证附件
const getCertificateAttachments = async (
  coupon2sid: string,
  filePrefix: string,
) => {
  try {
    const certificateData = await getAttachmentListApi({
      attlsh: coupon2sid,
      attmodel: 'coupon_identity',
      pageindex: 1,
      rows: 10,
    });

    if (certificateData.Data.length > 0) {
      certificateData.Data.forEach((item: any) => {
        item.url = `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`;
      });
    }

    certificateDataList.value = certificateData.Data;
  } catch (error) {
    console.error('获取身份证附件失败:', error);
    certificateDataList.value = [];
  }
};

// 获取购机者照片附件
const getBuyerPhotoAttachments = async (
  coupon2sid: string,
  filePrefix: string,
) => {
  try {
    const buyerPhotoData = await getAttachmentListApi({
      attlsh: coupon2sid,
      attmodel: 'coupon_buyer',
      pageindex: 1,
      rows: 10,
    });

    if (buyerPhotoData.Data.length > 0) {
      buyerPhotoData.Data.forEach((item: any) => {
        item.url = `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`;
      });
    }

    buyerPhotoDataList.value = buyerPhotoData.Data;
  } catch (error) {
    console.error('获取购机者照片失败:', error);
    buyerPhotoDataList.value = [];
  }
};

const [Modal, modalApi] = useVbenModal({
  title: '优惠券详情',
  class: 'w-10/12 max-w-8xl',
  showCancelButton: false,
  confirmText: '关闭',
  onConfirm() {
    modalApi.close();
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      const modalData = modalApi.getData();

      if (modalData?.row?.coupon2sid) {
        try {
          loading.value = true;

          // 获取文件前缀
          const filePrefix = await getFilePrefix();

          // 并行执行获取详情和附件的操作
          const [detailData] = await Promise.allSettled([
            getCoupon2AuditDetailApi({
              coupon2sid: modalData.row.coupon2sid,
            }),
            getCertificateAttachments(modalData.row.coupon2sid, filePrefix),
            getBuyerPhotoAttachments(modalData.row.coupon2sid, filePrefix),
          ]);

          if (detailData.status === 'fulfilled') {
            data.value = detailData.value;
          }
        } catch (error) {
          console.error('获取优惠券详情失败:', error);
        } finally {
          loading.value = false;
        }
      }
    } else {
      data.value = null;
      certificateDataList.value = [];
      buyerPhotoDataList.value = [];
    }
  },
});

function openDetailModal(rowData: any) {
  modalApi.setData({ row: rowData });
  modalApi.open();
}

// 打开修改购机者信息弹窗
function openEditBuyerInfoModal() {
  if (!data.value) return;

  editBuyerInfoModalRef.value?.openEditBuyerInfoModal({
    coupon2sid: data.value.coupon2sid,
    userstype: data.value.userstype,
    usersname: data.value.usersname,
    usersidcardnumber: data.value.usersidcardnumber,
    usersshtyxydm: data.value.usersshtyxydm,
    usersphone: data.value.usersphone,
  });
}

// 修改完成后的回调
async function handleEditFinish() {
  // 重新获取详情数据
  const modalData = modalApi.getData();
  if (modalData?.row?.coupon2sid) {
    try {
      loading.value = true;

      // 获取文件前缀
      const filePrefix = await getFilePrefix();

      // 并行执行获取详情和附件的操作
      const [detailData] = await Promise.allSettled([
        getCoupon2AuditDetailApi({
          coupon2sid: modalData.row.coupon2sid,
        }),
        getCertificateAttachments(modalData.row.coupon2sid, filePrefix),
        getBuyerPhotoAttachments(modalData.row.coupon2sid, filePrefix),
      ]);

      if (detailData.status === 'fulfilled') {
        data.value = detailData.value;
      }
    } catch (error) {
      console.error('刷新优惠券详情失败:', error);
    } finally {
      loading.value = false;
    }
  }
}

defineExpose({
  openDetailModal,
  openEditBuyerInfoModal,
  handleEditFinish,
});
</script>

<template>
  <Modal>
    <div v-loading="loading" class="space-y-6 p-4">
      <!-- 优惠券信息 -->
      <div>
        <el-divider content-position="left">
          <span class="text-lg font-semibold text-gray-800">优惠券信息</span>
        </el-divider>
        <el-descriptions :column="3" border class="mb-4" label-width="120px">
          <el-descriptions-item
            v-for="item in couponInfo"
            :key="item.label"
            :label="item.label"
            width="20%"
          >
            <!-- 优惠券状态标签 -->
            <ElTag
              v-if="item.isTag && item.tagType === 'couponStatus'"
              :type="getCouponStatusTag(item.value).type"
            >
              {{ getCouponStatusTag(item.value).text }}
            </ElTag>
            <!-- 使用状态标签 -->
            <ElTag
              v-else-if="item.isTag && item.tagType === 'usedStatus'"
              :type="getUsedStatusTag(item.value).type"
            >
              {{ getUsedStatusTag(item.value).text }}
            </ElTag>
            <!-- 审核备注特殊显示 -->
            <div v-else-if="item.label === '审核备注'" class="reject-reason">
              <ElTag type="danger" effect="dark" size="default">
                <i class="el-icon-warning-outline mr-1"></i>
                {{ item.value || '暂无备注' }}
              </ElTag>
            </div>
            <!-- 普通文本 -->
            <span v-else>{{ item.value || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 产品信息 -->
      <div>
        <el-divider content-position="left">
          <span class="text-lg font-semibold text-gray-800">产品信息</span>
        </el-divider>
        <el-descriptions :column="3" border class="mb-4" label-width="120px">
          <el-descriptions-item
            v-for="item in productInfo"
            :key="item.label"
            :label="item.label"
            width="20%"
          >
            {{ item.value || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 购机者信息 -->
      <div>
        <el-divider content-position="left">
          <span class="text-lg font-semibold text-gray-800">购机者信息</span>
          <!-- 当审核状态为2（审核不通过）时显示修改按钮 -->
          <ElButton
            v-if="data && data.coupon2sype === 2"
            type="primary"
            size="small"
            class="ml-4"
            @click="openEditBuyerInfoModal"
          >
            修改购机者信息
          </ElButton>
        </el-divider>
        <el-descriptions :column="3" border class="mb-4" label-width="120px">
          <el-descriptions-item
            v-for="item in applicantInfo"
            :key="item.label"
            :label="item.label"
            width="20%"
          >
            {{ item.value || '-' }}
          </el-descriptions-item>

          <!-- 身份证正面附件 -->
          <el-descriptions-item label="身份证正面" width="20%">
            <div
              v-if="certificateDataList.length > 0"
              class="flex flex-wrap gap-3"
            >
              <ElImage
                v-for="item in certificateDataList"
                :key="item.attname"
                :src="item.url"
                :preview-src-list="certificateDataList.map((i) => i.url)"
                fit="cover"
                style="width: 100px; height: 100px"
                class="rounded border"
                :preview-teleported="true"
              />
            </div>
            <span v-else class="text-gray-500">未上传</span>
          </el-descriptions-item>

          <!-- 购机者照片附件 -->
          <el-descriptions-item label="购机者照片" width="20%">
            <div
              v-if="buyerPhotoDataList.length > 0"
              class="flex flex-wrap gap-3"
            >
              <ElImage
                v-for="item in buyerPhotoDataList"
                :key="item.attname"
                :src="item.url"
                :preview-src-list="buyerPhotoDataList.map((i) => i.url)"
                fit="cover"
                style="width: 100px; height: 100px"
                class="rounded border"
                :preview-teleported="true"
              />
            </div>
            <span v-else class="text-gray-500">未上传</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </Modal>

  <!-- 修改购机者信息模态框 -->
  <EditBuyerInfoModal ref="editBuyerInfoModalRef" @finish="handleEditFinish" />
</template>

<style scoped>
.reject-reason {
  animation: pulse 2s infinite;
}

.reject-reason .el-tag {
  font-weight: bold;
  border: 2px solid #f56c6c;
  box-shadow: 0 2px 8px rgb(245 108 108 / 30%);
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.02);
  }

  100% {
    transform: scale(1);
  }
}
</style>
