<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';

import {
  computed,
  defineEmits,
  defineExpose,
  onMounted,
  reactive,
  ref,
} from 'vue';

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

import { ElMessage } from 'element-plus';

import {
  getCoupon1DetailApi,
  getCoupon1ListApi,
  receiveCouponApi,
} from '#/api/coupon/coupon1';
import { getProductDetailApi, getProductListApi } from '#/api/product';
import { getCustomerListApi } from '#/api/user';
import UploadFile from '#/components/upload-file/index.vue';

const emit = defineEmits(['finish', 'cancel']);

const localCouponId = ref('');
const localProductId = ref('');
const localMerchantId = ref('');

// 添加经销商和产品选择相关数据
const merchantOptions = ref<{ label: string; value: string }[]>([]);
const productOptions = ref<{ label: string; value: string }[]>([]);
const merchantLoading = ref(false);
const productLoading = ref(false);

// 添加优惠券选择相关数据
const couponOptions = ref<{ label: string; value: string }[]>([]);
const couponLoading = ref(false);

// 添加产品详细信息状态
const selectedProductInfo = ref<any>(null);
const productInfoLoading = ref(false);

// 添加优惠券详细信息状态
const selectedCouponInfo = ref<any>(null);
const couponInfoLoading = ref(false);

const formRef = ref<FormInstance>();
const formData = reactive({
  merchantId: '', // 经销商ID
  productId: '', // 产品ID
  couponId: '', // 优惠券ID
  userstype: '个人',
  usersname: '',
  idNumber: '',
  idCardEpFiles: [] as any[],
  businessLicenseEpFiles: [] as any[],
  buyerPhotoEpFiles: [] as any[],
  idCardIds: [] as { id: string; name?: string; url: string }[],
  businessLicenseIds: [] as { id: string; name?: string; url: string }[],
  buyerPhotoIds: [] as { id: string; name?: string; url: string }[],
  phone: '',
});

const usersnameLabel = computed(() =>
  formData.userstype === '个人' ? '姓名' : '企业名称',
);
const idNumberLabel = computed(() =>
  formData.userstype === '个人' ? '身份证号' : '统一社会信用代码',
);
const idPhotoLabel = computed(() =>
  formData.userstype === '个人' ? '身份证正面' : '营业执照',
);

// 判断经销商字段是否禁用（当外部传入merchantId时禁用）
const isMerchantDisabled = computed(() => {
  return !!localMerchantId.value;
});

const submitLoading = ref(false);

const formRules = computed<FormRules>(() => ({
  merchantId: [{ required: true, message: '请选择经销商', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'blur' }],
  couponId: [{ required: true, message: '请选择优惠券', trigger: 'blur' }],
  userstype: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
  usersname: [
    {
      required: true,
      message: `请输入${usersnameLabel.value}`,
      trigger: 'blur',
    },
  ],
  idNumber: [
    {
      required: true,
      message: `请输入${idNumberLabel.value}`,
      trigger: 'blur',
    },
  ],
  idCardIds: [
    {
      required: true,
      validator: (_rule, value, callback) => {
        if (formData.userstype === '个人' && (!value || value.length === 0)) {
          callback(new Error('请上传身份证正面照片'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  businessLicenseIds: [
    {
      required: true,
      validator: (_rule, value, callback) => {
        if (formData.userstype === '企业' && (!value || value.length === 0)) {
          callback(new Error('请上传营业执照照片'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
}));

// 获取经销商列表
async function fetchMerchantOptions() {
  try {
    merchantLoading.value = true;
    const response = await getCustomerListApi({
      'usersnature.value': '经销商',
      pageindex: 1,
      rows: 100,
    });

    if (response && response.Data && Array.isArray(response.Data)) {
      merchantOptions.value = response.Data.map((item: any) => ({
        label: item.usersname || '未命名经销商',
        value: item.usersid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取经销商列表失败', error);
    ElMessage.error('获取经销商列表失败');
  } finally {
    merchantLoading.value = false;
  }
}

// 获取产品列表
async function fetchProductOptions(merchantId: string) {
  if (!merchantId) {
    productOptions.value = [];
    return;
  }

  try {
    productLoading.value = true;
    const response = await getProductListApi({
      productsmerchantid: merchantId,
      pageindex: 1,
      rows: 100,
    });

    if (response && response.Data && Array.isArray(response.Data)) {
      productOptions.value = response.Data.map((item: any) => ({
        label: item.productsname || '未命名产品',
        value: item.productsid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取产品列表失败', error);
    ElMessage.error('获取产品列表失败');
  } finally {
    productLoading.value = false;
  }
}

// 获取优惠券列表
async function fetchCouponOptions(productId: string) {
  if (!productId) {
    couponOptions.value = [];
    return;
  }

  try {
    couponLoading.value = true;
    const response = await getCoupon1ListApi({
      couponproductids: productId,
      couponsfky: 1, // 只获取可用的优惠券
      pageindex: 1,
      rows: 100,
    });

    if (response && response.Data && Array.isArray(response.Data)) {
      couponOptions.value = response.Data.map((item: any) => ({
        label: item.couponmc || '未命名优惠券',
        value: item.couponid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取优惠券列表失败', error);
    ElMessage.error('获取优惠券列表失败');
  } finally {
    couponLoading.value = false;
  }
}

// 经销商选择变化时的处理
function handleMerchantChange(merchantId: string) {
  formData.productId = ''; // 清空产品选择
  localMerchantId.value = merchantId;
  if (merchantId) {
    fetchProductOptions(merchantId);
  } else {
    productOptions.value = [];
  }
}

// 产品选择变化时的处理
function handleProductChange(productId: string) {
  localProductId.value = productId;
  formData.couponId = ''; // 清空优惠券选择
  selectedCouponInfo.value = null; // 清空优惠券信息

  if (productId) {
    fetchProductInfo(productId);
    fetchCouponOptions(productId);
  } else {
    selectedProductInfo.value = null;
    couponOptions.value = [];
  }
}

// 获取产品详细信息
async function fetchProductInfo(productId: string) {
  if (!productId) {
    selectedProductInfo.value = null;
    return;
  }

  try {
    productInfoLoading.value = true;
    const response = await getProductDetailApi({
      productsid: productId,
    });

    if (response && Object.keys(response).length > 0) {
      selectedProductInfo.value = response;
    }
  } catch (error) {
    console.error('获取产品详细信息失败', error);
    ElMessage.error('获取产品详细信息失败');
    selectedProductInfo.value = null;
  } finally {
    productInfoLoading.value = false;
  }
}

// 优惠券选择变化时的处理
function handleCouponChange(couponId: string) {
  localCouponId.value = couponId;
  if (couponId) {
    fetchCouponInfo(couponId);
  } else {
    selectedCouponInfo.value = null;
  }
}

// 获取优惠券详细信息
async function fetchCouponInfo(couponId: string) {
  if (!couponId) {
    selectedCouponInfo.value = null;
    return;
  }

  try {
    couponInfoLoading.value = true;
    const response = await getCoupon1DetailApi({
      couponid: couponId,
    });

    if (response && Object.keys(response).length > 0) {
      selectedCouponInfo.value = response;
    }
  } catch (error) {
    console.error('获取优惠券详细信息失败', error);
    ElMessage.error('获取优惠券详细信息失败');
    selectedCouponInfo.value = null;
  } finally {
    couponInfoLoading.value = false;
  }
}

// 用户类型切换，重置表单
function handleUserTypeChange() {
  formData.usersname = '';
  formData.idNumber = '';
  formData.idCardEpFiles = [];
  formData.idCardIds = [];
  formData.businessLicenseEpFiles = [];
  formData.businessLicenseIds = [];
  formData.buyerPhotoEpFiles = [];
  formData.buyerPhotoIds = [];
  formRef.value?.clearValidate();
}

// 确认
async function handleSubmit(): Promise<boolean> {
  if (!formRef.value) return false;
  try {
    await formRef.value.validate();
    submitLoading.value = true;

    let combinedFileIds: string[] = [];
    combinedFileIds =
      formData.userstype === '个人'
        ? [...combinedFileIds, ...formData.idCardIds.map((f) => f.id)]
        : [...combinedFileIds, ...formData.businessLicenseIds.map((f) => f.id)];
    combinedFileIds = [
      ...combinedFileIds,
      ...formData.buyerPhotoIds.map((f) => f.id),
    ];

    const finalFileIdsString = combinedFileIds.filter(Boolean).join(',');

    const params = {
      couponid: formData.couponId,
      userstype: formData.userstype,
      usersshtyxydm: formData.userstype === '企业' ? formData.idNumber : '',
      usersidcardnumber: formData.userstype === '个人' ? formData.idNumber : '',
      usersname: formData.usersname,
      coupon2productids: formData.productId,
      coupon2phone: formData.phone,
      filesid: finalFileIdsString,
      coupon2merchantid: formData.merchantId,
    };

    // 调用领取优惠券API
    const response = await receiveCouponApi(params);

    if (response && response.success !== false) {
      ElMessage.success('优惠券领取申请提交成功');
      return response;
    } else {
      ElMessage.error(response?.message || '提交失败，请重试');
      return response;
    }
  } catch (error) {
    console.error('表单验证失败或提交出错：', error);
    ElMessage.error('请检查表单填写是否正确或联系管理员');
    return false;
  } finally {
    submitLoading.value = false;
  }
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-[1000px]',
  title: '领取优惠券',
  showCancelButton: true,
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onConfirm() {
    const coupon2sid = await handleSubmit();
    if (coupon2sid) {
      modalApi.close();
      emit('finish', { coupon2sid });
    }
  },
  onCancel() {
    modalApi.close();
    emit('cancel');
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const modalData = modalApi.getData() as {
        couponId?: string;
        merchantId?: string;
        productId?: string;
      };
      localCouponId.value = modalData?.couponId || '';
      localProductId.value = modalData?.productId || '';
      localMerchantId.value = modalData?.merchantId || '';

      // 重置表单数据
      formData.merchantId = modalData?.merchantId || '';
      formData.productId = '';
      formData.couponId = '';
      formData.userstype = '个人';
      formData.usersname = '';
      formData.idNumber = '';
      formData.idCardEpFiles = [];
      formData.idCardIds = [];
      formData.businessLicenseEpFiles = [];
      formData.businessLicenseIds = [];
      formData.buyerPhotoEpFiles = [];
      formData.buyerPhotoIds = [];
      formData.phone = '';

      // 重置选项数据
      productOptions.value = [];
      couponOptions.value = [];
      selectedProductInfo.value = null;
      selectedCouponInfo.value = null;

      formRef.value?.resetFields();
      submitLoading.value = false;

      // 初始化经销商选项
      fetchMerchantOptions();

      // 如果传入了merchantId，自动获取对应的产品列表
      if (modalData?.merchantId) {
        fetchProductOptions(modalData.merchantId);
      }
    }
  },
});

// 领取优惠劵对外暴露方法，外部调用
function openReceiveCouponModal(data?: {
  couponId?: string;
  merchantId?: string;
  productId?: string;
}) {
  modalApi.setData(data || {});
  modalApi.open();
}

defineExpose({
  openReceiveCouponModal,
});

onMounted(() => {});
</script>

<template>
  <Modal>
    <div class="p-4">
      <div
        class="rounded-md border border-gray-200 bg-white px-4 py-4 shadow-sm"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="140px"
        >
          <el-form-item label="经销商" prop="merchantId">
            <el-select
              v-model="formData.merchantId"
              placeholder="请选择经销商"
              :loading="merchantLoading"
              :disabled="isMerchantDisabled"
              clearable
              @change="handleMerchantChange"
            >
              <el-option
                v-for="option in merchantOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请先选择经销商"
              :loading="productLoading"
              :disabled="!formData.merchantId"
              clearable
              @change="handleProductChange"
            >
              <el-option
                v-for="option in productOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="优惠券" prop="couponId">
            <el-select
              v-model="formData.couponId"
              placeholder="请先选择产品"
              :loading="couponLoading"
              :disabled="!formData.productId"
              clearable
              @change="handleCouponChange"
            >
              <el-option
                v-for="option in couponOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <!-- 产品详细信息展示 -->
          <el-form-item v-if="selectedProductInfo" label="" label-width="0">
            <div
              class="w-full rounded-md border border-green-600 bg-green-200 p-4"
            >
              <div v-if="productInfoLoading" class="text-center">
                <span class="text-gray-500">加载产品信息中...</span>
              </div>
              <div v-else class="space-y-2">
                <div class="mb-2">
                  <span class="text-lg font-semibold text-green-800">
                    {{ selectedProductInfo.productsname }}
                  </span>
                </div>
                <div class="grid grid-cols-2 gap-4">
                  <div class="space-y-2">
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        产品型号:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedProductInfo.productsmodel }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        机具类型:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedProductInfo.productsjjlx }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        产品分类:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedProductInfo.productscategory }}
                      </span>
                    </div>
                  </div>
                  <div class="space-y-2">
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        产品价格:
                      </span>
                      <span class="text-sm font-semibold text-red-600">
                        ¥{{
                          selectedProductInfo.productsprice?.toLocaleString()
                        }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        中央补贴:
                      </span>
                      <span class="text-sm text-green-600">
                        ¥{{
                          selectedProductInfo.productszybt?.toLocaleString()
                        }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-20 text-sm font-medium text-gray-600">
                        特殊补贴:
                      </span>
                      <span class="text-sm text-green-600">
                        ¥{{
                          selectedProductInfo.productstsxzybt?.toLocaleString()
                        }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 优惠券详细信息展示 -->
          <el-form-item v-if="selectedCouponInfo" label="" label-width="0">
            <div
              class="w-full rounded-md border border-blue-600 bg-blue-200 p-4"
            >
              <div v-if="couponInfoLoading" class="text-center">
                <span class="text-gray-500">加载优惠券信息中...</span>
              </div>
              <div v-else class="space-y-2">
                <div class="mb-2">
                  <span class="text-lg font-semibold text-blue-800">
                    {{ selectedCouponInfo.couponmc }}
                  </span>
                </div>
                <div class="grid grid-cols-2 gap-4">
                  <div class="space-y-2">
                    <div class="flex">
                      <span class="w-24 text-sm font-medium text-gray-600">
                        优惠券ID:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedCouponInfo.couponid }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-24 text-sm font-medium text-gray-600">
                        创建时间:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedCouponInfo.couponcreatedate }}
                      </span>
                    </div>
                  </div>
                  <div class="space-y-2">
                    <div class="flex">
                      <span class="w-24 text-sm font-medium text-gray-600">
                        状态:
                      </span>
                      <span
                        :class="
                          selectedCouponInfo.couponsfky === 1
                            ? 'text-green-600'
                            : 'text-red-600'
                        "
                        class="text-sm font-semibold"
                      >
                        {{
                          selectedCouponInfo.couponsfky === 1
                            ? '可用'
                            : '不可用'
                        }}
                      </span>
                    </div>
                    <div class="flex">
                      <span class="w-24 text-sm font-medium text-gray-600">
                        创建人:
                      </span>
                      <span class="text-sm text-gray-800">
                        {{ selectedCouponInfo.couponcreateuser }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="用户类型" prop="userstype">
            <el-radio-group
              v-model="formData.userstype"
              @change="handleUserTypeChange"
            >
              <el-radio value="个人">个人</el-radio>
              <el-radio value="企业">企业</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="usersnameLabel" prop="usersname">
            <el-input
              v-model="formData.usersname"
              :placeholder="`请输入${usersnameLabel}`"
              clearable
            />
          </el-form-item>

          <el-form-item :label="idNumberLabel" prop="idNumber">
            <el-input
              v-model="formData.idNumber"
              :placeholder="`请输入${idNumberLabel}`"
              clearable
            />
          </el-form-item>

          <el-form-item
            :label="idPhotoLabel"
            :prop="
              formData.userstype === '个人' ? 'idCardIds' : 'businessLicenseIds'
            "
          >
            <template v-if="formData.userstype === '个人'">
              <UploadFile
                v-model:file-list="formData.idCardEpFiles"
                v-model:file-ids="formData.idCardIds"
                attmodel="coupon_identity"
                attpath="/coupon_identity/"
                :limit="1"
                list-type="picture-card"
                tips=""
                accept="image/*,.pdf"
              />
            </template>
            <template v-else>
              <UploadFile
                v-model:file-list="formData.businessLicenseEpFiles"
                v-model:file-ids="formData.businessLicenseIds"
                attmodel="coupon_identity"
                attpath="/coupon_identity/"
                :limit="1"
                list-type="picture-card"
                tips=""
                accept="image/*,.pdf"
              />
            </template>
          </el-form-item>

          <el-form-item label="购机者照片(可选)" prop="buyerPhotoIds">
            <UploadFile
              v-model:file-list="formData.buyerPhotoEpFiles"
              v-model:file-ids="formData.buyerPhotoIds"
              attmodel="coupon_buyer"
              attpath="/coupon_buyer/"
              :limit="1"
              list-type="picture-card"
              tips=""
              accept="image/*,.pdf"
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入您的手机号码"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
.rules-text p {
  margin-bottom: 0.25rem;
}
</style>
