<template>
  <div class="ml30 mr30" style="min-height:100vh;">
    <div class="">
      <van-form @submit="onSubmit" :rules="rules">
        <div class="fn-flex fn-flex-column" style="min-height:100vh;">
          <div class="fn-flex-item pt30">
            <div class="box-shadow-darkGray inner10 ulib-r20 pb30">
              <van-notice-bar
                  v-if="form.reason"
                  style="background: rgba(255, 255, 255, 0.5);"
                  wrapable
                  :scrollable="false"
              >
                <span class="color-000">审核未通过:</span><span class="text-color-theme">{{ form.reason }}</span>
              </van-notice-bar>
              <van-field class="allow-input" label="手机号" required input-align="right" v-model="form.mobile" readonly/>
              <van-field class="allow-input" label="姓名" required input-align="right" placeholder="请输入姓名" v-model="form.name"
                         :rules="[{ required: true, message: '请输入姓名' }]"/>
              <!-- 购车城市 -->
              <van-field class="allow-input" label="购车城市" required input-align="right" v-model="form.city" readonly/>
              <!--
              <van-field label="购车城市" required :border="false" input-align="right" placeholder="请选择购车城市" v-model="form.city" name="area" readonly
                is-link @click="showCityPicker" />
                -->

              <!-- 购车门店（必填） -->
              <van-field class="allow-input" name="store" required :border="false" label="购车门店" input-align="right"
                         placeholder="请选择购车门店" v-model="form.store" readonly is-link
                         @click="showStorePicker" :rules="[{ required: true, message: '请选择购车门店' }]"/>

              <!-- 品牌车型（必填） -->
              <van-field label="品牌车型" required input-align="right" v-model="form.model" readonly/>
              <!--
              <van-field name="model" required :border="false" label="品牌车型" input-align="right" placeholder="请选择品牌车型" v-model="form.model" readonly is-link
                @click="showModelPicker" :rules="[{ required: true, message: '请选择品牌车型' }]" />
                -->
              <!-- 上传购车合同（必填） -->
              <van-cell title="上传购车合同" required :border="false">
                <template #value>
                  <a href="javascript:void(0)" v-if="buy_contract_info.content"
                     @click="showPopContent(buy_contract_info,2)" class="view-example"><span
                      class="font-26 mr10">查看示例</span>
                    <van-icon size="16" name="arrow"/>
                  </a>
                </template>
              </van-cell>
              <div class="upload-box ml20 mr20">
                <van-field :rules="[{ validator: validateContractFile, message: '请上传购车合同' }]">
                  <template #input>
                    <van-uploader
                        v-model="form.contractFile"
                        :multiple="false"
                        :max-count="1"
                        accept="image/*"
                        :after-read="onContractRead"
                    >
                      <template #preview-cover="{ file }" v-if="file && file.name">
                        <div class="preview-cover van-ellipsis">{{ file.name }}</div>
                      </template>
                      <div class="fn-flex fn-flex-column fn-flex-center mt30">
                        <i class="icon-custom icon-file"></i>
                        <div class="fn-flex fn-flex-center mt10" style="gap: 10px;">
                          <van-button type="default" size="mini" round style="padding:1.2vw 2vw;">上传购车合同
                          </van-button>
                        </div>
                      </div>
                    </van-uploader>
                  </template>
                </van-field>
              </div>

              <!-- 上传发票（必填） -->
              <van-cell title="上传发票" required :border="false">
                <template #value>
                  <a href="javascript:void(0)" @click="showPopContent(allowance_invice_info,2)"
                     class="view-example"><span class="font-26 mr10">查看示例</span>
                    <van-icon size="16" name="arrow"/>
                  </a>
                </template>

              </van-cell>

              <div class="upload-box ml20 mr20">
                <van-field :rules="[{ validator: validateInvoiceFile, message: '请上传发票' }]">
                  <template #input>
                    <van-uploader
                        v-model="form.invoiceFile"
                        :multiple="false"
                        :max-count="1"
                        accept="image/*"
                        :after-read="onInvoiceRead"
                    >
                      <template #preview-cover="{ file }" v-if="file && file.name">
                        <div class="preview-cover van-ellipsis">{{ file.name }}</div>
                      </template>
                      <div class="fn-flex fn-flex-column fn-flex-center mt30">
                        <i class="icon-custom icon-file"></i>
                        <div class="fn-flex fn-flex-center mt10" style="gap: 10px;">
                          <van-button type="default" size="mini" round style="padding:1.2vw 2vw;">上传发票
                          </van-button>
                        </div>
                      </div>
                    </van-uploader>
                  </template>
                </van-field>
              </div>

              <!-- 上传商业保险单（必填） -->
              <van-cell title="上传商业保险单" :border="false">
                <template #value>
                  <a href="javascript:void(0)" @click="showPopContent(allowance_insuranc_info,2)"
                     class="view-example"><span class="font-26 mr10">查看示例</span>
                    <van-icon size="16" name="arrow"/>
                  </a>
                </template>
              </van-cell>
              <div class="text-center inner10 font-26 text-color-theme">
                平安车险客户上传保单可加速审核
              </div>
              <div class="upload-box ml20 mr20">
                <van-uploader v-model="form.insuranceFile" :multiple="false" :max-count="1" accept="image/*"
                              :after-read="onInsuranceRead">
                  <template #preview-cover="{ file }" v-if="file && file.name">
                    <div class="preview-cover van-ellipsis">{{ file.name }}</div>
                  </template>
                  <div class="fn-flex fn-flex-column fn-flex-center mt30">
                    <i class="icon-custom icon-file"></i>
                    <div class="fn-flex fn-flex-center mt10" style="gap: 10px;">
                      <van-button type="default" size="mini" round style="padding:1.2vw 2vw;">上传保险单</van-button>
                      <!-- <van-button type="primary" size="mini" round style="padding:1.2vw 2vw;" @click="onWechatInsuranceUpload">微信上传</van-button> -->
                    </div>
                  </div>
                </van-uploader>
              </div>

            </div>
          </div>
          <div class="text-center pt40 pb30">
            <!-- 协议 -->
            <div class="agreement ml100 mr100 pb20" style="line-height: 1.6;">
              提交即同意
              <a v-for="(item,index) in allowance_bottom_info" :key="index" href="javascript:void(0)"
                 @click="showPopContent(item,1)" class="agreement-link">{{ item.title }}</a>
            </div>

            <!-- 提交按钮 -->
            <van-button type="danger" round block native-type="submit" :loading="submitting">
              {{ submitting ? '提交中...' : '提交' }}
            </van-button>
          </div>
        </div>


        <!-- 使用van-popup包装van-picker -->
        <!-- <van-popup v-model="cityPickerVisible" position="bottom">
          <van-picker :columns="cityColumns" @confirm="onCityConfirm" @cancel="cityPickerVisible = false" />
        </van-popup> -->

        <van-popup v-model:show="cityPickerVisible" destroy-on-close position="bottom">
          <van-area :area-list="areaList" :model-value="pickerValue" :columns-num="2" @confirm="onConfirm"
                    @cancel="showArea = false"/>
        </van-popup>

        <van-popup v-model:show="storePickerVisible" destroy-on-close position="bottom">
          <van-picker :columns="storeColumns" @confirm="onStoreConfirm" @cancel="storePickerVisible = false"/>
        </van-popup>

        <van-popup v-model:show="modelPickerVisible" destroy-on-close position="right"
                   :style="{ width: '80%', height: '100%' }">
          <BrandList :is-sticky="false" @brandItem="handleBrandItem"/>
        </van-popup>

        <!-- 车系选择弹窗 -->
        <van-popup v-model:show="seriesPickerVisible" destroy-on-close position="bottom">
          <van-picker :columns="seriesColumns" @confirm="onSeriesConfirm" @cancel="seriesPickerVisible = false"/>
        </van-popup>
      </van-form>
    </div>
    <PopContent :content="content" :img="guide_img" :show-pop="showContentPop"
                @update:show-pop="showContentPop = $event"/>
  </div>

</template>

<script setup>
import WechatUtils, {WechatShare} from '@/utils/wechat'
import {ref, reactive, onMounted} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {showConfirmDialog, showToast} from 'vant';
import {areaList} from '@vant/area-data';
import BrandList from '../components/BrandList.vue' // 导入BrandList组件
import PopContent from '@/components/PopContent.vue' // 导入PopContent组件
import api from '../utils/api.js' // 导入API
// import WechatUtils, { WechatImage } from '../utils/wechat.js' // 导入微信工具
import {getBasicConfig} from '@/utils/basicSetting'


const route = useRoute();
const router = useRouter();
// 优惠券id
const couponId = ref(route.params.couponId || route.query.couponId || '');
// 获取补贴ID（从路由参数或查询参数中获取）
const subsidyId = ref(route.params.id || route.query.id || '');

// 表单数据
const form = reactive({
  mobile: '',
  name: '',
  city: '',
  cityId: '',
  store: '',
  storeId: '',
  model: '',
  brandId: '',
  seriesId: '',
  contractFile: [],
  invoiceFile: [],
  insuranceFile: [],
  contractUrl: '',
  invoiceUrl: '',
  insuranceUrl: '',
  reason: '',
  cityName: '',
  brandName: ''
});

// 选择器可见性
const cityPickerVisible = ref(false);
const storePickerVisible = ref(false);
const modelPickerVisible = ref(false);
const seriesPickerVisible = ref(false);

// 提交状态
const submitting = ref(false);

// 选择器选项
const cityColumns = ref([]);
const storeColumns = ref([]);
const modelColumns = ref([]);
const seriesColumns = ref([]);

// 校验规则
const rules = {
  // store: [{ required: true, message: '请选择购车门店' }],
  // model: [{ required: true, message: '请选择品牌车型' }],
  contractFile: [{validator: (val) => val && val.length > 0, message: '请上传购车合同'}],
  invoiceFile: [{validator: (val) => val && val.length > 0, message: '请上传发票'}],
  // insuranceFile: [{ validator: (val) => val && val.length > 0, message: '请上传商业保险单' }],
};
const validateContractFile = (val) => {
  if (!form.contractUrl) {
    return false;
  } else {
    return true;
  }
};
const validateInvoiceFile = (val) => {
  if (!form.invoiceUrl) {
    return false;
  } else {
    return true;
  }
};


// 组件挂载时检查补贴ID
onMounted(async () => {
  // if (!couponId.value) {
  //   showToast('缺少补贴ID参数');
  //   console.warn('补贴ID未找到，请检查路由参数');
  // }
  let appid = localStorage.getItem('app_id')
  if (appid) {
    await WechatUtils.init(appid);
    // 隐藏分享
    await WechatShare.hideAllNonBaseMenuItem();
  }
  await getGuideInfo();
  if (subsidyId.value) { //编辑
    await getSubsidyInfo(subsidyId.value);
  } else {
    await getMobile(couponId.value);
  }
  await loadStoresByCity(form.cityId);
});

// API方法定义
const getMobile = async (couponId) => {
  try {
    const response = await api.get('/auto/ucenter/couponDetail', {id: couponId});
    if (response.code === 200) {
      // form.mobile = response.data.mobile;
      Object.assign(form, response.data);
    }
  } catch (error) {
    console.error(error);
  }
};
/**
 * 获取门店列表
 * @param {number} cityId - 城市ID
 */
const getStoreList = async (cityId, couponId) => {
  try {
    const response = await api.get('/auto/biz', {cityId, couponId});
    if (response.code === 200) {
      return response.data;
    } else {
      console.error('获取门店列表失败:', response.message);
      return [];
    }
  } catch (error) {
    console.error('获取门店列表异常:', error);
    return [];
  }
};

/**
 * 获取品牌列表
 */
const getBrandList = async () => {
  try {
    const response = await api.get('/auto/car/brand');
    if (response.code === 200) {
      return response.data;
    } else {
      console.error('获取品牌列表失败:', response.message);
      return {};
    }
  } catch (error) {
    console.error('获取品牌列表异常:', error);
    return {};
  }
};

/**
 * 获取车系列表
 * @param {number} brandId - 品牌ID
 * @param {number} page - 页码
 * @param {number} size - 分页大小
 */
const getSeriesList = async (brandId, page = 1, size = 100) => {
  try {
    const response = await api.get('/auto/brand/series', {
      brand_id: brandId,
      page,
      size
    });
    if (response.code === 200) {
      return response.data;
    } else {
      console.error('获取车系列表失败:', response.message);
      return {list: [], count: 0};
    }
  } catch (error) {
    console.error('获取车系列表异常:', error);
    return {list: [], count: 0};
  }
};

/**
 * 上传图片
 * @param {File} file - 图片文件
 */
const uploadImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await api.upload(formData, {headers: {'Content-Type': 'multipart/form-data'}});
    if (response.code === 200) {
      return response.data;
    } else {
      console.error('上传图片失败:', response.message);
      return null;
    }
  } catch (error) {
    console.error('上传图片异常:', error);
    return null;
  }
};

/**
 * 使用微信JS-SDK选择并上传图片
 * @param {string} type - 图片类型 'invoice' | 'insurance'
 */
const chooseAndUploadWechatImage = async (type) => {
  try {
    // 检查是否在微信浏览器中
    if (!window.wx) {
      showToast('请在微信中打开');
      return;
    }

    // 选择图片
    const localIds = await WechatImage.chooseImage({
      count: 1, // 只选择一张图片
      sizeType: ['compressed'], // 使用压缩图
      sourceType: ['album', 'camera'] // 可以指定来源是相册还是相机
    });

    if (localIds && localIds.length > 0) {
      const localId = localIds[0];

      // 上传图片到微信服务器
      const serverId = await WechatImage.uploadImage(localId);

      if (serverId) {
        // 调用后端接口，将微信服务器的图片下载到自己的服务器
        const response = await api.post('/auto/upload/wechat', {
          serverId: serverId
        });

        if (response.code === 0) {
          // 根据类型更新对应的表单字段
          if (type === 'invoice') {
            form.invoiceUrl = response.data.url;
            form.invoiceFile = [{
              url: response.data.url,
              name: '发票图片',
              isImage: true
            }];
            showToast('发票上传成功');
          } else if (type === 'insurance') {
            form.insuranceUrl = response.data.url;
            form.insuranceFile = [{
              url: response.data.url,
              name: '保险单图片',
              isImage: true
            }];
            showToast('保险单上传成功');
          }

          console.log(`${type}上传成功:`, response.data);
        } else {
          showToast(response.message || '图片上传失败');
        }
      } else {
        showToast('图片上传到微信服务器失败');
      }
    }
  } catch (error) {
    console.error('微信图片上传失败:', error);
    showToast('图片上传失败，请重试');
  }
};

/**
 * 发票微信上传处理
 */
const onWechatInvoiceUpload = () => {
  chooseAndUploadWechatImage('invoice');
};

/**
 * 保险单微信上传处理
 */
const onWechatInsuranceUpload = () => {
  chooseAndUploadWechatImage('insurance');
};

/**
 * 提交审核资料
 * @param {Object} submitData - 提交的数据
 */
const submitSubsidyData = async (submitData) => {
  try {
    const response = await api.post('/auto/subsidy', {
      ...submitData
    });
    if (response.code === 200) {
      return response;
    } else {
      throw new Error(response.message || '提交失败');
    }
  } catch (error) {
    console.error('提交审核资料异常:', error);
    throw error;
  }
};

/**
 * 修改审核资料
 * @param {Object} submitData - 修改数据
 */
const reSubmitSubsidyData = async (submitData) => {
  try {
    const response = await api.put('/auto/subsidy', {
      ...submitData
    });
    if (response.code === 200) {
      return response;
    } else {
      throw new Error(response.message || '提交失败');
    }
  } catch (error) {
    console.error('修改审核资料异常:', error);
    throw error;
  }
};

// 城市选择确认
// const onCityConfirm = (value) => {
//   form.city = value[0];
//   cityPickerVisible.value = false;
//   loadStoresByCity(form.city);
// };

// 门店选择确认
const onStoreConfirm = (value) => {
  form.store = value.selectedOptions[0].text;
  form.storeId = value.selectedOptions[0].value;
  storePickerVisible.value = false;
};

// 品牌选择确认
const handleBrandItem = async (brandInfo) => {
  form.model = brandInfo.name || brandInfo;
  form.brandId = brandInfo.id;
  modelPickerVisible.value = false;

  // 选择品牌后，加载对应的车系列表
  if (brandInfo.id) {
    await loadSeriesByBrand(brandInfo.id);
    seriesPickerVisible.value = true;
  }
};

// 车系选择确认
const onSeriesConfirm = (value) => {
  const seriesName = value.selectedOptions[0].text;
  const seriesId = value.selectedOptions[0].value;

  // 将品牌和车系组合显示
  form.model = `${form.model} ${seriesName}`;
  form.seriesId = seriesId;
  seriesPickerVisible.value = false;
};

// 显示选择器
const showCityPicker = () => (cityPickerVisible.value = true);
const pickerValue = ref('');
const onConfirm = async ({selectedValues, selectedOptions}) => {
  console.log('选择的值：', selectedValues);
  console.log('选择的选项：', selectedOptions);
  pickerValue.value = selectedValues.length
      ? selectedValues[selectedValues.length - 1]
      : '';
  cityPickerVisible.value = false;
  form.city = selectedOptions.map((item) => item.text).join('/');
  form.cityId = selectedValues[selectedValues.length - 1]; // 获取最后一级的城市ID
  console.log(form.city); // 打印选择的城市

  // 选择城市后加载门店列表
  await loadStoresByCity(form.cityId);
};

const showStorePicker = () => {
  if (!form.cityId) {
    showToast('请先选择城市');
    return;
  }
  if (!storeColumns.value.length) {
    showToast('当前城市无可用门店');
    return;
  }
  storePickerVisible.value = true;
};

const showModelPicker = () => (modelPickerVisible.value = true);

// 加载门店列表
const loadStoresByCity = async (cityId) => {
  if (!cityId) return;

  const storeData = await getStoreList(cityId, couponId.value);
  if (storeData && storeData.list) {
    storeColumns.value = storeData.list.map(store => ({
      text: store.name,
      value: store.id
    }));
  } else {
    storeColumns.value = [];
  }
};

// 加载车系列表
const loadSeriesByBrand = async (brandId) => {
  if (!brandId) return;

  const seriesData = await getSeriesList(brandId);
  if (seriesData && seriesData.list) {
    seriesColumns.value = seriesData.list.map(series => ({
      text: series.name,
      value: series.id
    }));
  } else {
    seriesColumns.value = [];
  }
};
// 购车合同上传处理
const onContractRead = async (file) => {
  console.log('上传购车合同:', file);
  const uploadResult = await uploadImage(file.file);
  if (uploadResult) {
    form.contractUrl = uploadResult.url;
    console.log('发票购车合同成功:', uploadResult);
  } else {
    showToast('购车合同上传失败');
  }
};
// 发票上传处理
const onInvoiceRead = async (file) => {
  console.log('上传发票:', file);
  const uploadResult = await uploadImage(file.file);
  if (uploadResult) {
    form.invoiceUrl = uploadResult.url;
    console.log('发票上传成功:', uploadResult);
  } else {
    showToast('发票上传失败');
  }
};

// 保险单上传处理
const onInsuranceRead = async (file) => {
  console.log('上传保险单:', file);
  const uploadResult = await uploadImage(file.file);
  if (uploadResult) {
    form.insuranceUrl = uploadResult.url;
    console.log('保险单上传成功:', uploadResult);
  } else {
    showToast('保险单上传失败');
  }
};

// 验证表单数据
const validateForm = () => {
  const errors = [];

  // if (!subsidyId.value) {
  //   errors.push('缺少补贴ID');
  // }

  if (!form.cityId) {
    errors.push('请选择购车城市');
  }

  if (!form.storeId) {
    errors.push('请选择购车门店');
  }

  if (!form.brandId) {
    errors.push('请选择品牌');
  }

  if (!form.seriesId) {
    errors.push('请选择车系');
  }
  if (!form.contractUrl) {
    errors.push('请上传购车合同');
  }
  if (!form.invoiceUrl) {
    errors.push('请上传发票');
  }

  // if (!form.insuranceUrl) {
  //   errors.push('请上传商业保险单');
  // }

  return errors;
};

// 提交处理
const onSubmit = async (values) => {
  console.log('提交数据:', values);
  console.log('完整表单数据:', form);

  // 验证表单
  const errors = validateForm();
  if (errors.length > 0) {
    showToast(errors[0]);
    return;
  }

  // 显示确认弹窗
  try {
    let message = '确定要提交审核资料吗？\n提交后将无法修改。';
    if (subsidyId.value) {
      message = '确定要修改审核资料吗？';
    }
    await showConfirmDialog({
      title: '确认提交',
      message: message,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      confirmButtonColor: '#f84803'
    });

    // 用户确认后开始提交
    submitting.value = true;

    const submitData = {
      id: subsidyId.value,
      couponId: couponId.value,
      bizId: form.storeId,
      cityId: form.cityId,
      brandId: form.brandId,
      seriesId: form.seriesId,
      billImg: form.invoiceUrl,
      businessImg: form.insuranceUrl,
      contractImg: form.contractUrl,
      name: form.name
    };

    console.log('提交参数:', submitData);
    if (subsidyId.value) { //重新提交
      console.log('重新提交审核');
      await reSubmitSubsidyData(submitData);
    } else {
      const result = await submitSubsidyData(submitData);
    }
    showToast('提交成功！');

    // 提交成功后跳转到我的补贴页面
    setTimeout(() => {
      router.replace('/my/allowance');
    }, 1500);

  } catch (error) {
    if (error === 'cancel') {
      // 用户取消了提交
      return;
    }

    console.error('提交失败:', error);
    showToast(error.message || '提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};


const showContentPop = ref(false);

const content = ref('');
const allowance_bottom_info = ref([])
const allowance_invice_info = ref({})
const allowance_insuranc_info = ref({})
const buy_contract_info = ref({})
const guide_img = ref('')
const getGuideInfo = async () => {
  allowance_bottom_info.value = await getBasicConfig('allowance_bottom')
  allowance_invice_info.value = await getBasicConfig('allowance_invoice')
  allowance_insuranc_info.value = await getBasicConfig('allowance_insuranc')
  buy_contract_info.value = await getBasicConfig('buy_contract')
}

const showPopContent = (item, type = 1) => {
  if (!item.content) return
  showContentPop.value = true;
  content.value = ''
  guide_img.value = ''
  if (type == 1) {
    content.value = item.content;
    guide_img.value = '';
  } else if (type == 2) {
    content.value = '';
    guide_img.value = item.content;
  }
};

// 获取补贴详情
const getSubsidyInfo = async (couponId) => {
  try {
    const response = await api.get('/auto/subsidy/detail', {id: couponId});
    if (response.code === 200) {
      console.log('补贴详情:', response.data);
      Object.assign(form, response.data);
      console.log('form表单数据:', form);
    }
  } catch (error) {
    console.error(error);
  }
};
</script>

<style scoped lang="scss">
.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  /* width: 100%; */
  height: 260px;
  background-color: #f9f9f9;

  ::v-deep {
    .van-field__error-message {
      text-align: center;
    }

    .van-field {
      background-color: #f9f9f9;
      padding: 0;
    }

    .van-uploader {
      width: 100%;
      height: 100%;

      .van-uploader__wrapper {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }

      .van-uploader__preview {
        // margin-top: 3vw;
        margin: 0;
      }

      .van-uploader__preview-image {
        width: 100%;
        height: 100%;
      }

      .van-uploader__input-wrapper {
        width: 100%;
      }

      // width: 100%;
    }
  }
}

.upload-text {
  margin-top: 10px;
}

.view-example {
  color: #527acc;
  font-size: 26px;
  display: block;
}

.agreement {
  text-align: center;
  // margin: 20px 0;
  font-size: 26px;
}

.agreement-link {
  color: #527acc;
  margin: 0 5px;
  display: inline-block;
}

.van-field__label {
  width: 100px;
}

.allow-input {
  ::v-deep {
    .van-field__error-message {
      text-align: right;
    }
  }
}
</style>