<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="债权编号" prop="creditNumber">
        <el-input v-model="queryParams.creditNumber" placeholder="请输入债权编号" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="关联合同" prop="contractId">
        <el-select v-model="queryParams.contractId" placeholder="请选择关联合同" clearable style="width: 240px">
          <el-option v-for="contract in contractList" :key="contract.contractId" 
            :label="contract.contractNumber + ' - ' + contract.title" :value="contract.contractId" />
        </el-select>
      </el-form-item>
      <el-form-item label="债权人" prop="creditorName">
        <el-input v-model="queryParams.creditorName" placeholder="请输入债权人名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="债务人" prop="debtorName">
        <el-input v-model="queryParams.debtorName" placeholder="请输入债务人名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="债权状态" prop="creditStatus">
        <el-select v-model="queryParams.creditStatus" placeholder="债权状态" clearable style="width: 240px">
          <el-option label="已生成" value="generated" />
          <el-option label="有效" value="active" />
          <el-option label="已转让" value="transferred" />
          <el-option label="已结算" value="settled" />
          <el-option label="已失效" value="expired" />
          <el-option label="已验证" value="verified" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['credit:credit:add']">生成债权</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['credit:credit:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="creditList">
      <el-table-column label="债权编号" align="center" key="creditNumber" prop="creditNumber" min-width="180"
        v-if="columns[0].visible" />
      <el-table-column label="关联合同" align="center" key="contractNumber" min-width="150"
        :show-overflow-tooltip="true" v-if="columns[1].visible">
        <template #default="scope">
          <span>{{ scope.row.contractNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="债权人" align="center" key="creditorName" prop="creditorName" min-width="100"
        :show-overflow-tooltip="true" v-if="columns[2].visible" />
      <el-table-column label="债务人" align="center" key="debtorName" prop="debtorName" min-width="100"
        :show-overflow-tooltip="true" v-if="columns[3].visible" />
      <el-table-column label="债权金额" align="center" key="creditAmount" prop="creditAmount" min-width="150"
        v-if="columns[4].visible">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.creditAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发行日期" align="center" prop="issueDate" min-width="120" v-if="columns[5].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期日期" align="center" prop="maturityDate" min-width="120" v-if="columns[6].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.maturityDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="债权状态" align="center" key="creditStatus" min-width="100" v-if="columns[7].visible">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.creditStatus)">
            {{ getStatusText(scope.row.creditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="数字签名" align="center" key="digitalSignature" min-width="100" v-if="columns[8].visible">
        <template #default="scope">
          <el-tag v-if="scope.row.digitalSignature" type="success" size="small">已签名</el-tag>
          <el-tag v-else type="info" size="small">未签名</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160" v-if="columns[9].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" min-width="160" v-if="columns[10].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
              v-hasPermi="['credit:credit:query']"></el-button>
          </el-tooltip>
          <!-- 已验证状态注释掉修改按钮 -->
          <!--<el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['credit:credit:edit']" v-if="hasRole(['security_company', 'administrator']) && scope.row.creditStatus !== 'verified'"></el-button>
          </el-tooltip>-->
          <!-- 已验证状态隐藏删除按钮 -->
          <el-tooltip content="删除" placement="top" v-if="scope.row.creditStatus !== 'verified'">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['credit:credit:remove']" v-if="hasRole(['security_company', 'administrator'])"></el-button>
          </el-tooltip>
          <!-- 已验证状态隐藏验证按钮 -->
          <el-tooltip content="验证债权" placement="top" v-if="scope.row.creditStatus !== 'verified'">
            <el-button link type="primary" icon="Check" @click="handleValidate(scope.row)"
              v-hasPermi="['credit:credit:validate']"></el-button>
          </el-tooltip>
          <!--<el-dropdown @command="(command) => handleCommand(command, scope.row)" v-if="hasMoreActions(scope.row)">
            <el-button link type="primary" icon="DArrowRight">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="signature" 
                  v-if="scope.row.digitalSignature"
                  v-hasPermi="['credit:credit:signature']">
                  <el-icon>
                    <Key />
                  </el-icon>数字签名
                </el-dropdown-item>
                <el-dropdown-item command="transfer"
                  v-if="scope.row.creditStatus === 'active' && hasRole(['security_company', 'administrator'])"
                  v-hasPermi="['credit:credit:transfer']">
                  <el-icon>
                    <Switch />
                  </el-icon>转让债权
                </el-dropdown-item>
                <el-dropdown-item command="history"
                  v-hasPermi="['credit:credit:history']">
                  <el-icon>
                    <Clock />
                  </el-icon>转让历史
                </el-dropdown-item>
                <el-dropdown-item command="log"
                  v-hasPermi="['system:operlog:query']">
                  <el-icon>
                    <List />
                  </el-icon>操作日志
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="Credit">
import { listCredits, getCredit, delCredit, validateCredit, exportCredit, transferCredit } from "@/api/credit/credit";
import { listContracts } from "@/api/credit/contract";

const { proxy } = getCurrentInstance();

const creditList = ref([]);
const contractList = ref([]);
const contractMap = ref({});
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    creditNumber: null,
    contractId: null,
    creditorName: null,
    debtorName: null,
    creditStatus: null,
  },
  columns: [
    { key: 0, label: `债权编号`, visible: true, prop: 'creditNumber' },
    { key: 1, label: `关联合同`, visible: true, prop: 'contractNumber' },
    { key: 2, label: `债权人`, visible: true, prop: 'creditorName' },
    { key: 3, label: `债务人`, visible: true, prop: 'debtorName' },
    { key: 4, label: `债权金额`, visible: true, prop: 'creditAmount' },
    { key: 5, label: `发行日期`, visible: true, prop: 'issueDate' },
    { key: 6, label: `到期日期`, visible: true, prop: 'maturityDate' },
    { key: 7, label: `债权状态`, visible: true, prop: 'creditStatus' },
    { key: 8, label: `数字签名`, visible: true, prop: 'digitalSignature' },
    { key: 9, label: `创建时间`, visible: true, prop: 'createTime' },
    { key: 10, label: `更新时间`, visible: false, prop: 'updateTime' }
  ]
});

const { queryParams, columns } = toRefs(data);

/** 查询债权列表 */
function getList() {
  loading.value = true;
  listCredits(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    creditList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取部门列表 */
function getDeptList() {
  listDept({ status: 0 }).then(response => {
    deptList.value = response.data;
    // 创建部门ID到名称的映射
    const map = {};
    response.data.forEach(dept => {
      map[dept.deptId] = dept.deptName;
    });
    deptMap.value = map;
  });
}

/** 获取合同列表 */
function getContractList() {
  listContracts({ contractStatus: 'CONFIRMED' }).then(response => {
    contractList.value = response.rows;
    // 创建合同ID到合同编号的映射
    const map = {};
    response.rows.forEach(contract => {
      map[contract.contractId] = contract.contractNumber;
    });
    contractMap.value = map;
  });
}

/** 格式化债权状态 */
function getStatusText(creditStatus) {
  const statusMap = {
    'generated': '已生成',
    'active': '有效',
    'transferred': '已转让',
    'settled': '已结算',
    'expired': '已失效',
    'verified': '已验证'
  };
  return statusMap[creditStatus] || creditStatus;
}

/** 获取状态标签类型 */
function getStatusTagType(creditStatus) {
  const typeMap = {
    'generated': 'info',
    'active': 'success',
    'transferred': 'warning',
    'settled': 'primary',
    'expired': 'danger',
    'verified': 'success'
  };
  return typeMap[creditStatus] || 'info';
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({ path: '/credit/generate' });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const creditId = row.creditId;
  proxy.$router.push({ path: '/credit/generate', query: { creditId: creditId } });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const creditIds = row.creditId;
  proxy.$modal.confirm('是否确认删除债权编号为"' + row.creditNumber + '"的数据项？').then(function () {
    return delCredit(creditIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 查看详情 */
function handleDetail(row) {
  const creditId = row.creditId;
  proxy.$router.push({ path: '/credit/CreditDetail', query: { id: creditId } });
}

/** 验证债权 */
function handleValidate(row) {
  const creditId = row.creditId;
  proxy.$router.push({ path: '/credit/validate', query: { id: creditId } });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/credit/export', {
    ...queryParams.value
  }, `credit_${new Date().getTime()}.xlsx`)
}

/** 更多操作命令 */
function handleCommand(command, row) {
  switch (command) {
    case "signature":
      viewDigitalSignature(row.id);
      break;
    case "transfer":
      handleTransfer(row);
      break;
    case "blockchain":
      viewBlockchainInfo(row.id);
      break;
    case "history":
      viewTransferHistory(row.id);
      break;
    case "log":
      viewOperationLog(row.id);
      break;
  }
}

/** 检查是否有更多操作 */
function hasMoreActions(row) {
  // 检查用户是否有任何下拉菜单权限
  const hasSignaturePermission = row.digitalSignature && proxy.$auth.hasPermi('credit:credit:signature');
  const hasTransferPermission = row.creditStatus === 'active' && hasRole(['security_company', 'administrator']) && proxy.$auth.hasPermi('credit:credit:transfer');
  const hasHistoryPermission = proxy.$auth.hasPermi('credit:credit:history');
  const hasLogPermission = proxy.$auth.hasPermi('system:operlog:query');
  
  return hasSignaturePermission || hasTransferPermission || hasHistoryPermission || hasLogPermission;
}

/** 查看数字签名 */
function viewDigitalSignature(creditId) {
  proxy.$router.push({ path: '/credit/signature', query: { creditId: creditId } });
}

/** 转让债权 */
function handleTransfer(row) {
  proxy.$modal.confirm('确认要转让债权"' + row.creditNumber + '"吗？').then(function () {
    // 这里可以打开转让对话框或跳转到转让页面
    proxy.$modal.msgInfo("债权转让功能待实现");
  }).catch(() => { });
}

/** 查看区块链信息 */
function viewBlockchainInfo(creditId) {
  // 跳转到区块链信息页面或打开对话框
  proxy.$modal.msgInfo("查看区块链信息功能待实现");
}

/** 查看转让历史 */
function viewTransferHistory(creditId) {
  // 跳转到转让历史页面或打开对话框
  proxy.$modal.msgInfo("查看转让历史功能待实现");
}

/** 查看操作日志 */
function viewOperationLog(creditId) {
  // 这里可以打开操作日志对话框或跳转到日志页面
  proxy.$modal.msgInfo("查看操作日志功能待实现");
}

/** 格式化金额 */
function formatMoney(amount) {
  if (!amount) return '0.00';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount);
}

/** 检查用户角色 */
function hasRole(roles) {
  return proxy.$auth.hasRole(roles);
}

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