<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input v-model="queryParams.contractNumber" placeholder="请输入合同编号" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入合同标题" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="甲方单位" prop="clientCompany">
        <el-input v-model="queryParams.clientCompany" placeholder="请输入甲方单位名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="安保公司" prop="securityCompany">
        <el-input v-model="queryParams.securityCompany" placeholder="请输入安保公司名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="queryParams.contractStatus" placeholder="合同状态" clearable style="width: 240px">
          <el-option label="待确认" value="PENDING" />
          <el-option label="已确认" value="CONFIRMED" />
          <el-option label="执行中" value="ACTIVE" />
          <el-option label="已完成" value="COMPLETED" />
          <el-option label="已取消" value="CANCELLED" />
        </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:contract:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['credit:contract:edit']">修改</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['credit:contract:remove']" v-if="hasRole(['security_company', 'administrator'])">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['credit:contract: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="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="50" align="center" />
      <el-table-column label="合同编号" align="center" key="contractNumber" prop="contractNumber" min-width="140"
        v-if="columns[0].visible" />
      <el-table-column label="合同标题" align="center" key="title" prop="title" min-width="150"
        :show-overflow-tooltip="true" v-if="columns[1].visible" />
      <el-table-column label="甲方单位" align="center" key="clientCompany" min-width="120"
        :show-overflow-tooltip="true" v-if="columns[2].visible">
        <template #default="scope">
          <span>{{ scope.row.clientCompany }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安保公司" align="center" key="securityCompany" min-width="120"
        :show-overflow-tooltip="true" v-if="columns[3].visible">
        <template #default="scope">
          <span>{{ scope.row.securityCompany }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同金额" align="center" key="contractAmount" prop="contractAmount" min-width="150"
        v-if="columns[4].visible">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.contractAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务内容" align="center" key="serviceContent" prop="serviceContent" min-width="150"
        :show-overflow-tooltip="true" v-if="columns[5].visible" />
      <el-table-column label="开始日期" align="center" prop="startDate" min-width="120" v-if="columns[6].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" min-width="120" v-if="columns[7].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款到期日" align="center" prop="paymentDueDate" min-width="120" v-if="columns[8].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同期限" align="center" key="contractTerm" prop="contractTerm" min-width="100" v-if="columns[9].visible">
        <template #default="scope">
          <span>{{ scope.row.contractTerm ? scope.row.contractTerm + '个月' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同类型" align="center" key="contractType" min-width="100" v-if="columns[10].visible">
        <template #default="scope">
          <el-tag :type="scope.row.contractType === 'ONLINE' ? 'success' : 'info'">
            {{ scope.row.contractType === 'ONLINE' ? '线上创建' : '线下上传' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="合同来源" align="center" key="contractSource" min-width="120" v-if="columns[11].visible">
        <template #default="scope">
          <el-tag :type="scope.row.contractSource === 'PLATFORM_CREATED' ? 'primary' : 'warning'">
            {{ scope.row.contractSource === 'PLATFORM_CREATED' ? '平台创建' : '外部导入' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" key="contractStatus" min-width="100" v-if="columns[12].visible">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.contractStatus)">
            {{ getStatusText(scope.row.contractStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="数据哈希" align="center" key="dataHash" prop="dataHash" min-width="120"
        :show-overflow-tooltip="true" v-if="columns[13].visible" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160" v-if="columns[14].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[15].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" key="remark" prop="remark" min-width="150"
        :show-overflow-tooltip="true" v-if="columns[16].visible" />
      <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:contract:query']"></el-button>
          </el-tooltip>
          <!--<el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['credit:contract:edit']" v-if="hasRole(['security_company', 'administrator'])"></el-button>
          </el-tooltip> -->
          <el-tooltip content="删除" placement="top" v-if="scope.row.contractStatus === 'PENDING'">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['credit:contract:remove']" v-if="hasRole(['security_company', 'administrator'])"></el-button>
          </el-tooltip>
          <el-tooltip content="确认合同" placement="top" v-if="scope.row.contractStatus === 'PENDING'">
            <el-button link type="primary" icon="Check" @click="handleConfirm(scope.row)"
              v-hasPermi="['credit:contract:confirm']"></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="download" 
                  v-if="scope.row.fileUrl"
                  v-hasPermi="['credit:contract:download']">
                  <el-icon>
                    <Download />
                  </el-icon>下载文件
                </el-dropdown-item>
                <el-dropdown-item command="blockchain"
                  v-hasPermi="['credit:contract:blockchain']">
                  <el-icon>
                    <Link />
                  </el-icon>区块链信息
                </el-dropdown-item>
                <el-dropdown-item command="history"
                  v-hasPermi="['credit:contract: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="Contract">
import { listContracts, getContract, delContract, confirmContract, exportContract } from "@/api/credit/contract";

const { proxy } = getCurrentInstance();
const { contract_status } = proxy.useDict("contract_status");

const contractList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNumber: null,
    title: null,
    clientCompany: null,
    securityCompany: null,
    contractStatus: null,
  },
  columns: [
    { key: 0, label: `合同编号`, visible: true, prop: 'contractNumber' },
    { key: 1, label: `合同标题`, visible: true, prop: 'title' },
    { key: 2, label: `甲方单位`, visible: true, prop: 'clientCompany' },
    { key: 3, label: `安保公司`, visible: true, prop: 'securityCompany' },
    { key: 4, label: `合同金额`, visible: true, prop: 'contractAmount' },
    { key: 5, label: `服务内容`, visible: true, prop: 'serviceContent' },
    { key: 6, label: `开始日期`, visible: true, prop: 'startDate' },
    { key: 7, label: `结束日期`, visible: true, prop: 'endDate' },
    { key: 8, label: `付款到期日`, visible: true, prop: 'paymentDueDate' },
    { key: 9, label: `合同期限`, visible: true, prop: 'contractTerm' },
    { key: 10, label: `合同类型`, visible: true, prop: 'contractType' },
    { key: 11, label: `合同来源`, visible: true, prop: 'contractSource' },
    { key: 12, label: `合同状态`, visible: true, prop: 'contractStatus' },
    { key: 13, label: `数据哈希`, visible: false, prop: 'dataHash' },
    { key: 14, label: `创建时间`, visible: true, prop: 'createTime' },
    { key: 15, label: `更新时间`, visible: false, prop: 'updateTime' },
    { key: 16, label: `备注`, visible: false, prop: 'remark' }
  ]
});

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

/** 查询合同列表 */
function getList() {
  loading.value = true;
  listContracts(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    contractList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 格式化合同状态 */
function getStatusText(status) {
  const statusMap = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认', 
    'ACTIVE': '执行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  const typeMap = {
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'ACTIVE': 'primary',
    'COMPLETED': 'info',
    'CANCELLED': 'danger'
  };
  return typeMap[status] || 'info';
}


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

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

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.contractId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

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

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.contractId || ids.value;
  proxy.$router.push({ path: '/digitalCredit/create', query: { id: id } });
}



/** 删除按钮操作 */
function handleDelete(row) {
  const contractIds = row.contractId || ids.value;
  
  // 检查是否有已确认的合同
  if (row && row.contractStatus !== 'PENDING') {
    proxy.$modal.msgError("只能删除待确认状态的合同");
    return;
  }
  
  // 批量删除时检查所有选中的合同状态
  if (!row && ids.value.length > 0) {
    const confirmedContracts = contractList.value.filter(contract => 
      ids.value.includes(contract.contractId) && contract.contractStatus !== 'PENDING'
    );
    
    if (confirmedContracts.length > 0) {
      proxy.$modal.msgError("选中的合同中包含非待确认状态的合同，无法删除");
      return;
    }
  }
  
  proxy.$modal.confirm('是否确认删除合同编号为"' + contractIds + '"的数据项？').then(function () {
    return delContract(contractIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 查看详情 */
function handleDetail(row) {
  const id = row.contractId || ids.value;
  proxy.$router.push({ path: '/digitalCredit/detail/', query: { id: id } });
}

/** 确认合同 */
function handleConfirm(row) {
  const id = row.contractId || ids.value;
  proxy.$router.push({ path: '/digitalCredit/confirm/',query: { id: id }  });
}

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

/** 更多操作命令 */
function handleCommand(command, row) {
  switch (command) {
    case "download":
      downloadFile(row.fileUrl, row.title);
      break;
    case "blockchain":
      viewBlockchainInfo(row.contractId);
      break;
    case "history":
      viewChangeHistory(row.contractId);
      break;
    case "log":
      viewOperationLog(row.contractId);
      break;
  }
}

/** 检查是否有更多操作 */
function hasMoreActions(row) {
  // 检查用户是否有任何下拉菜单权限
  const hasDownloadPermission = row.fileUrl && proxy.$auth.hasPermi('credit:contract:download');
  const hasBlockchainPermission = proxy.$auth.hasPermi('credit:contract:blockchain');
  const hasHistoryPermission = proxy.$auth.hasPermi('credit:contract:history');
  const hasLogPermission = proxy.$auth.hasPermi('system:operlog:query');
  
  return hasDownloadPermission || hasBlockchainPermission || hasHistoryPermission || hasLogPermission;
}

/** 下载文件 */
function downloadFile(url, filename) {
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.click();
}

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

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

/** 查看变更历史 */
function viewChangeHistory(contractId) {
  // 跳转到变更历史页面或打开对话框
  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(() => {
  getList();
});
</script>