<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="hover" class="search-card">
      <el-form :model="queryParams" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="合同编号">
              <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同名称">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同类型">
              <el-select v-model="queryParams.contractType" placeholder="请选择" clearable 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-col :span="6">
            <el-form-item label="合同状态">
              <el-select v-model="queryParams.contractStatus" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in contractStatusDict" :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="6">
            <el-form-item label="开始时间">
              <el-date-picker v-model="queryParams.contractStartTime" type="date" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker v-model="queryParams.contractEndTime" type="date" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="0px">
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button icon="Refresh" @click="handleReset">重置</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd">创建合同</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 合同信息列表 -->
    <el-card shadow="never" class="table-card">
      <div class="section-title">合同信息列表</div>

      <el-table v-loading="loading" :data="contractList" border style="width: 100%">
        <el-table-column prop="contractNo" label="合同编号" align="center" />
        <el-table-column prop="contractName" label="合同名称" align="center" />
        <el-table-column prop="contractType" label="合同类型" align="center">
          <template #default="scope">
            <span>{{ getDictLabel(contractTypeDict, scope.row.contractType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractAmount" label="金额（万）" align="center">
          <template #default="scope">
            <span>{{ formatWanAmount(scope.row.contractAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractStartTime" label="起始时间" align="center">
          <template #default="scope">
            <span>{{ scope.row.contractStartTime ? formatDate(scope.row.contractStartTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractEndTime" label="截止时间" align="center">
          <template #default="scope">
            <span>{{ scope.row.contractEndTime ? formatDate(scope.row.contractEndTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" align="center">
          <template #default="scope">
            <span>{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractAttachment" label="附件管理" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.contractAttachment" link type="primary" @click="handleViewAttachment(scope.row)">查看附件</el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractStatus" label="状态" align="center">
          <template #default="scope">
            <span>{{ getContractStatusText(scope.row.contractStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <!-- 待审核状态：可以修改、查看和审核 -->
            <template v-if="scope.row.contractStatus === 0 || scope.row.contractStatus === '0'">
              <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button link type="success" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="warning" @click="handleAudit(scope.row)">审核</el-button>
              <el-button link @click="handleCancel(scope.row)">作废</el-button>
            </template>

            <!-- 已生效状态：只能查看 -->
            <template v-if="scope.row.contractStatus === 1 || scope.row.contractStatus === '1'">
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button link @click="handleCancel(scope.row)">作废</el-button>
            </template>

            <!-- 已过期状态：无操作按钮 -->
            <template v-if="scope.row.contractStatus === 3 || scope.row.contractStatus === '3'">
              <span style="color: #999">-</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 合同管理对话框 -->
    <el-dialog v-model="contractDialogVisible" :title="contractDialogTitle" width="900px" :close-on-click-modal="false">
      <el-form ref="contractFormRef" :model="contractForm" :rules="contractFormRules" label-width="140px" :disabled="contractDialogReadonly">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="合同名称：" prop="contractName">
              <el-input v-model="contractForm.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同类型：" prop="contractType">
              <el-select v-model="contractForm.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-col :span="12">
            <el-form-item label="提醒时间：" prop="demandReminderTime">
              <el-input-number v-model="contractForm.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="contractForm.contractStartTime" type="date" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间：" prop="contractEndTime">
              <el-date-picker v-model="contractForm.contractEndTime" type="date" placeholder="请选择" style="width: 100%" />
            </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="contractForm.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="contractAmount">
              <el-input v-model="contractForm.contractAmount" placeholder="请输入">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="税率：" prop="taxRate">
              <el-select v-model="contractForm.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-col :span="12">
            <el-form-item label="结算方式：" prop="settlementMethod">
              <el-select v-model="contractForm.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="24">
            <el-form-item label="合同附件：" prop="contractAttachment">
              <FileUpload
                v-model="contractForm.contractAttachment"
                :limit="1"
                :file-size="50"
                :file-type="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf']"
                :disabled="contractDialogReadonly"
              />
            </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="contractForm.contractDescription" type="textarea" :rows="4" placeholder="请输入合同说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <template v-if="contractDialogAudit">
            <el-button @click="contractDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleApprove" :loading="approveLoading">审核通过</el-button>
          </template>
          <template v-else-if="contractDialogReadonly">
            <el-button @click="contractDialogVisible = false">关闭</el-button>
          </template>
          <template v-else>
            <el-button @click="contractDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleContractSubmit" :loading="contractSubmitLoading">确定</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { getContractListById, getDictData, getTaxRateList, getSettlementMethodList, getInvoiceTypeList } from '@/api/customer/info';
import { updateContract } from '@/api/supplier/contract';
import { ElMessage, ElMessageBox } from 'element-plus';
import FileUpload from '@/components/FileUpload/index.vue';
import { listByIds } from '@/api/system/oss';

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

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 yuanToWanString = (value: unknown): string => {
  const raw = String(value ?? '').trim();
  if (!raw) return '';

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

  const sign = match[1] ? '-' : '';
  const amount = BigInt(match[2] || '0');
  const intPart = amount / 10000n;
  const fracPart = amount % 10000n;

  const fracPadded = fracPart.toString().padStart(4, '0');
  const fracTrimmed = fracPadded.replace(/0+$/, '');
  const result = fracTrimmed ? `${intPart.toString()}.${fracTrimmed}` : intPart.toString();
  return sign ? '-' + result : result;
};

const formatWanAmount = (value: unknown) => {
  const v = yuanToWanString(value);
  return v ? v : '-';
};

const loading = ref(false);
const contractList = ref<any[]>([]);

// 对话框相关
const contractDialogVisible = ref(false);
const contractDialogTitle = ref('');
const contractDialogReadonly = ref(false);
const contractDialogAudit = ref(false);
const contractSubmitLoading = ref(false);
const approveLoading = ref(false);
const contractFormRef = ref();

// 合同表单
const contractForm = ref({
  id: '',
  contractName: '',
  contractType: '',
  demandReminderTime: 4,
  contractStartTime: '',
  contractEndTime: '',
  invoiceType: '',
  contractAmount: '',
  taxRate: '',
  settlementMethod: '',
  contractAttachment: '',
  contractDescription: ''
});

// 表单验证规则
const contractFormRules = {
  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 contractStatusDict = ref<any[]>([]);
const contractTypeDict = ref<any[]>([]);
const taxRateList = ref<any[]>([]);
const settlementMethodList = ref<any[]>([]);
const invoiceTypeList = ref<any[]>([]);

const queryParams = ref({
  contractNo: '',
  contractName: '',
  contractType: '',
  contractStartTime: '',
  contractEndTime: '',
  contractStatus: ''
});

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

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

/** 获取合同状态字典 */
const getContractStatusDict = async () => {
  try {
    const res = await getDictData('supplier_status');
    contractStatusDict.value = res.data || [];
  } catch (e) {
    console.error('获取合同状态字典失败:', e);
  }
};

/** 获取合同类型字典 */
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 getDictLabel = (dictList: any[], dictValue: string | number) => {
  if (!dictValue && dictValue !== 0) return '-';
  const dict = dictList.find((item) => String(item.dictValue) === String(dictValue));
  return dict ? dict.dictLabel : dictValue;
};

/** 获取合同列表 */
const getContractList = async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const supplierId = urlParams.get('supplierId');

  if (!supplierId) {
    return;
  }

  loading.value = true;
  try {
    const res = await getContractListById(supplierId, {
      ...queryParams.value
    });

    if (Array.isArray(res.data)) {
      contractList.value = res.data;
      pagination.value.total = res.data.length;
    } else {
      contractList.value = res.rows || [];
      pagination.value.total = res.total || 0;
    }
  } catch (e) {
    console.error('获取合同列表失败:', e);
  } finally {
    loading.value = false;
  }
};

/** 搜索 */
const handleSearch = () => {
  pagination.value.pageNum = 1;
  getContractList();
};

/** 重置 */
const handleReset = () => {
  queryParams.value = {
    contractNo: '',
    contractName: '',
    contractType: '',
    contractStartTime: '',
    contractEndTime: '',
    contractStatus: ''
  };
  handleSearch();
};

/** 创建合同 */
const handleAdd = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const supplierId = urlParams.get('supplierId');

  router.push({
    path: '/supplier/contract/add',
    query: supplierId ? { supplierId } : {}
  });
};

/** 查看合同 */
const handleView = (row: any) => {
  contractForm.value = {
    ...row,
    contractAmount: yuanToWanString(row?.contractAmount)
  };
  contractDialogTitle.value = '查看合同';
  contractDialogReadonly.value = true;
  contractDialogAudit.value = false;
  contractDialogVisible.value = true;
};

/** 编辑合同 */
const handleEdit = (row: any) => {
  contractForm.value = {
    ...row,
    contractAmount: yuanToWanString(row?.contractAmount)
  };
  contractDialogTitle.value = '修改合同';
  contractDialogReadonly.value = false;
  contractDialogAudit.value = false;
  contractDialogVisible.value = true;
};

/** 审核合同 */
const handleAudit = (row: any) => {
  contractForm.value = {
    ...row,
    contractAmount: yuanToWanString(row?.contractAmount)
  };
  contractDialogTitle.value = '审核合同';
  contractDialogReadonly.value = true;
  contractDialogAudit.value = true;
  contractDialogVisible.value = true;
};

/** 提交合同表单 */
const handleContractSubmit = async () => {
  contractFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      contractSubmitLoading.value = true;
      try {
        const payload = {
          ...contractForm.value,
          contractAmount: wanToYuanString(contractForm.value.contractAmount)
        };
        await updateContract(payload);
        ElMessage.success('修改成功');
        contractDialogVisible.value = false;
        // 刷新列表
        getContractList();
      } catch (e) {
        console.error('修改合同失败:', e);
        ElMessage.error('修改失败');
      } finally {
        contractSubmitLoading.value = false;
      }
    }
  });
};

/** 审核通过 */
const handleApprove = async () => {
  try {
    await ElMessageBox.confirm('确认审核通过该合同吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  approveLoading.value = true;
  try {
    await updateContract({
      id: contractForm.value?.id,
      contractStatus: 1
    });
    ElMessage.success('审核通过成功');
    contractDialogVisible.value = false;
    getContractList();
  } catch (e) {
    console.error('审核通过失败:', e);
    ElMessage.error('审核通过失败');
  } finally {
    approveLoading.value = false;
  }
};

/** 作废合同 */
const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认作废该合同吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  approveLoading.value = true;
  try {
    await updateContract({
      id: row.id,
      contractStatus: 5
    });
    ElMessage.success('操作成功');
    contractDialogVisible.value = false;
    getContractList();
  } catch (e) {
    ElMessage.error('操作失败');
  } finally {
    approveLoading.value = false;
  }
};

/** 查看附件 */
const handleViewAttachment = async (row: any) => {
  if (!row.contractAttachment) {
    ElMessage.warning('暂无附件可下载');
    return;
  }

  try {
    // 通过文件ID获取文件信息
    const res = await listByIds(row.contractAttachment);
    if (res.data && res.data.length > 0) {
      const file = res.data[0];

      // 使用fetch获取文件并强制下载
      const response = await fetch(file.url);
      const blob = await response.blob();

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = file.originalName || (row.contractName ? `${row.contractName}_合同附件` : '合同附件');
      link.style.display = 'none';

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 清理URL对象
      window.URL.revokeObjectURL(url);

      ElMessage({ message: '开始下载', type: 'info' });
    } else {
      ElMessage.warning('未找到附件文件');
    }
  } catch (e) {
    console.error('下载附件失败:', e);
    ElMessage.error('下载失败');
  }
};

/** 格式化日期 */
const formatDate = (date: string | Date) => {
  if (!date) return '-';
  const d = new Date(date);
  return d.toISOString().split('T')[0];
};

/** 获取合同状态文本 */
const getContractStatusText = (status: number | string) => {
  return getDictLabel(contractStatusDict.value, status);
};

/** 分页大小改变 */
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  getContractList();
};

/** 当前页改变 */
const handleCurrentChange = (page: number) => {
  pagination.value.pageNum = page;
  getContractList();
};

onMounted(async () => {
  await nextTick();
  getContractStatusDict();
  getContractTypeDict();
  getTaxRateData();
  getSettlementMethodData();
  getInvoiceTypeData();
  getContractList();
});

onActivated(() => {
  getContractList();
});
</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;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  padding: 24px;
}

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

.contract-detail {
  padding: 20px 0;
}

.contract-detail h4 {
  margin: 20px 0 10px 0;
  color: #333;
  font-weight: 500;
}

.contract-detail p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}
</style>
