<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="detail-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <span class="header-title">创建合同</span>
    </div>

    <!-- 表单卡片 -->
    <el-card shadow="never" class="form-card">
      <div class="section-title">基本设置</div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierId">
              <el-select
                v-if="!isSupplierPreset"
                v-model="form.supplierId"
                placeholder="请选择供应商"
                style="width: 100%"
                filterable
                @change="onSupplierChange"
              >
                <el-option v-for="item in supplierList" :key="item.id" :label="`${item.supplierNo} - ${item.enterpriseName}`" :value="item.id" />
              </el-select>
              <el-input v-else :model-value="form.supplierName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商编号" prop="supplierNo">
              <el-input v-model="form.supplierNo" placeholder="请输入供应商编号" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in contractTypeDict" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提醒时间" prop="demandReminderTime">
              <el-input-number v-model="form.demandReminderTime" :min="1" :max="365" style="width: 150px" />
              <span style="margin-left: 10px">天</span>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="contractStartTime">
              <el-date-picker
                v-model="form.contractStartTime"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                :disabled-date="disabledStartDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="contractEndTime">
              <el-date-picker v-model="form.contractEndTime" type="date" placeholder="请选择" style="width: 100%" :disabled-date="disabledEndDate" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开票类型" prop="invoiceType">
              <el-select v-model="form.invoiceType" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in invoiceTypeList" :key="item.id" :label="item.invoiceTypeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlementMethod">
              <el-select v-model="form.settlementMethod" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in settlementMethodList" :key="item.id" :label="item.settlementName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input v-model="form.contractAmount" placeholder="">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-select v-model="form.taxRate" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in taxRateList" :key="item.id" :label="item.taxrateName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="合同附件" prop="contractAttachment">
              <FileUpload v-model="form.contractAttachment" :file-type="['pdf']" :file-size="50" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="合同说明" prop="contractDescription">
              <el-input v-model="form.contractDescription" type="textarea" :rows="4" placeholder="请选择" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { getDictData, getTaxRateList, getSettlementMethodList, getInvoiceTypeList } from '@/api/customer/info';
import { addContract } from '@/api/supplier/contract';
import { listInfo, getInfo } from '@/api/supplier/info';
import { ElMessage } from 'element-plus';
import FileUpload from '@/components/FileUpload/index.vue';

const route = useRoute();
const router = useRouter();

const formRef = ref();
const contractTypeDict = ref<any[]>([]);
const taxRateList = ref<any[]>([]);
const settlementMethodList = ref<any[]>([]);
const invoiceTypeList = ref<any[]>([]);
const supplierList = ref<any[]>([]);
const isSupplierPreset = ref(false);

const form = ref({
  supplierId: '',
  supplierNo: '',
  supplierName: '',
  contractNo: '',
  contractName: '',
  contractType: '',
  demandReminderTime: 4,
  contractStartTime: '',
  contractEndTime: '',
  contractAmount: '',
  taxRate: '',
  invoiceType: '',
  settlementMethod: '',
  contractAttachment: '',
  contractDescription: ''
});

const rules = {
  contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  contractStartTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  contractEndTime: [{ required: true, message: '请选择截止时间', trigger: 'change' }]
};

const wanToYuanString = (value: unknown): string => {
  const raw = String(value ?? '').trim();
  if (!raw) return '';

  const normalized = raw.replace(/,/g, '');
  const match = normalized.match(/^(-?)(\d+)(?:\.(\d+))?$/);
  if (!match) return '';

  const sign = match[1] ? '-' : '';
  const intPart = match[2] || '0';
  const fracRaw = match[3] || '';
  const fracPart = (fracRaw + '0000').slice(0, 4);

  const base = BigInt(intPart) * 10000n + BigInt(fracPart);
  return sign ? '-' + base.toString() : base.toString();
};

/** 禁用开始时间早于今天 */
const disabledStartDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/** 禁用截止时间早于开始时间 */
const disabledEndDate = (time: Date) => {
  if (!form.value.contractStartTime) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return time.getTime() < today.getTime();
  }
  const start = new Date(form.value.contractStartTime);
  start.setHours(0, 0, 0, 0);
  return time.getTime() < start.getTime();
};

/** 返回上一页 */
const goBack = () => {
  router.back();
};

/** 获取合同类型字典 */
const getContractTypeDict = async () => {
  try {
    const res = await getDictData('contract_type');
    contractTypeDict.value = res.data || [];
  } catch (e) {
    console.error('获取合同类型字典失败:', e);
  }
};

/** 获取税率列表 */
const getTaxRateData = async () => {
  try {
    const res = await getTaxRateList();
    taxRateList.value = res.rows || res.data || [];
  } catch (e) {
    console.error('获取税率列表失败:', e);
  }
};

/** 获取结算方式列表 */
const getSettlementMethodData = async () => {
  try {
    const res = await getSettlementMethodList();
    settlementMethodList.value = res.rows || res.data || [];
  } catch (e) {
    console.error('获取结算方式列表失败:', e);
  }
};

/** 获取发票类型列表 */
const getInvoiceTypeData = async () => {
  try {
    const res = await getInvoiceTypeList();
    invoiceTypeList.value = res.rows || res.data || [];
  } catch (e) {
    console.error('获取发票类型列表失败:', e);
  }
};

/** 提交表单 */
const handleSubmit = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const payload = {
          ...form.value,
          contractAmount: wanToYuanString(form.value.contractAmount)
        };
        await addContract(payload);
        ElMessage.success('创建成功');

        // 判断来源并返回刷新
        const urlParams = new URLSearchParams(window.location.search);
        const supplierId = urlParams.get('supplierId');
        if (supplierId) {
          // 从"管理"进入 → 返回合同详情页并刷新
          router.replace({ path: '/supplier/contract/detail', query: { supplierId, _t: Date.now() } });
        } else {
          // 从index页面直接进入 → 返回index页刷新统计数据
          router.replace({ path: '/supplier/contract' });
        }
      } catch (e) {
        console.error('创建合同失败:', e);
        ElMessage.error('创建失败');
      }
    }
  });
};

/** 供应商选择变更时，自动回显供应商编号 */
const onSupplierChange = (supplierId: string | number) => {
  const supplier = supplierList.value.find((item) => item.id === supplierId);
  if (supplier) {
    form.value.supplierNo = supplier.supplierNo || '';
    form.value.supplierName = supplier.enterpriseName || '';
  }
};

/** 加载供应商列表（用于下拉选择） */
const loadSupplierList = async () => {
  try {
    const res = await listInfo({ pageNum: 1, pageSize: 9999 });
    supplierList.value = res.rows || [];
  } catch (e) {
    console.error('加载供应商列表失败:', e);
  }
};

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const supplierId = urlParams.get('supplierId');

  if (supplierId) {
    // 从"管理"按钮进入，回显供应商名称和编号且不可修改
    isSupplierPreset.value = true;
    form.value.supplierId = supplierId;
    try {
      const res = await getInfo(supplierId);
      if (res.data) {
        form.value.supplierNo = res.data.supplierNo || '';
        form.value.supplierName = res.data.enterpriseName || '';
      }
    } catch (e) {
      console.error('获取供应商信息失败:', e);
    }
  } else {
    // 直接进入创建合同，需要选择供应商
    isSupplierPreset.value = false;
    await loadSupplierList();
  }

  getContractTypeDict();
  getTaxRateData();
  getSettlementMethodData();
  getInvoiceTypeData();
});
</script>

<style scoped>
.app-container {
  background: #f0f2f5;
  min-height: 100vh;
  padding: 0;
}

.detail-header {
  background: #fff;
  padding: 16px 24px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 16px;
}

.back-icon {
  font-size: 18px;
  cursor: pointer;
  margin-right: 12px;
  color: #666;
}

.back-icon:hover {
  color: #409eff;
}

.header-title {
  font-weight: 500;
  color: #333;
}

.form-card {
  margin: 16px;
  padding: 24px;
}

.section-title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}
</style>
