<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="90%"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ContentWrap>
      <!-- 精简后的搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="合同编号" prop="contractNo">
          <el-input
            v-model="queryParams.contractNo"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input
            v-model="queryParams.contractName"
            placeholder="请输入合同名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item label="甲方公司" prop="partyACompany">
          <el-input
            v-model="queryParams.partyACompany"
            placeholder="请输入甲方公司"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item label="乙方公司" prop="partyBCompany">
          <el-input
            v-model="queryParams.partyBCompany"
            placeholder="请输入乙方公司"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column
          v-if="multiple"
          type="selection"
          width="55"
        />
        <el-table-column label="合同编号" align="center" prop="contractNo" width="120" />
        <el-table-column label="合同名称" align="center" prop="contractName" width="150" />
        <el-table-column label="甲方公司" align="center" prop="partyACompany" width="150" />
        <el-table-column label="乙方公司" align="center" prop="partyBCompany" width="150" />
<!--        <el-table-column label="项目名称" align="center" prop="projectName" width="150" />-->
        <el-table-column label="合同金额" align="center" prop="currentContractAmount" width="120">
          <template #default="{row}">
            {{ row.currentContractAmount }} {{ row.currency }}
          </template>
        </el-table-column>
        <el-table-column label="生效日期" align="center" prop="effectiveDate" width="120" :formatter="dateFormatter" />
        <el-table-column label="合同状态" align="center" prop="contractStatus" width="100" />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import { MainApi, MainVO } from '@/api/contract/contractsale'
const message = useMessage() // 消息弹窗
const props = defineProps({
  modelValue: { // 控制显示隐藏
    type: Boolean,
    default: false
  },
  title: { // 弹窗标题
    type: String,
    default: '选择合同'
  },
  multiple: { // 是否多选
    type: Boolean,
    default: false
  },
  selected: { // 已选中的值
    type: Array as () => MainVO[],
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
const loading = ref(true)
const list = ref<MainVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractType: 1,
  isMainContract:1,
  contractNo: undefined,
  contractName: undefined,
  partyACompany: undefined,
  partyBCompany: undefined,
  projectName: undefined
})
const queryFormRef = ref()
const selectedRows = ref<MainVO[]>([])

// 监听visible变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    selectedRows.value = [...props.selected]
    getList()
  }
})

// 监听visible变化同步到父组件
watch(visible, (val) => {
  emit('update:modelValue', val)
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MainApi.getMainPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  Object.assign(queryParams, {
    pageNo: 1,
    pageSize: 10,
    contractType: 1,
    isMainContract:1,
    contractNo: undefined,
    contractName: undefined,
    partyACompany: undefined,
    partyBCompany: undefined,
    projectName: undefined
  })
  handleQuery()
}

/** 行选择变化 */
const handleSelectionChange = (rows: MainVO[]) => {
  if (!props.multiple && rows.length > 1) {
    selectedRows.value = [rows[rows.length - 1]]
  } else {
    selectedRows.value = rows
  }
}

/** 行点击事件 */
const handleRowClick = (row: MainVO) => {
  if (props.multiple) {
    const index = selectedRows.value.findIndex(item => item.id === row.id)
    if (index >= 0) {
      selectedRows.value.splice(index, 1)
    } else {
      selectedRows.value.push(row)
    }
  } else {
    selectedRows.value = [row]
  }
}

/** 弹窗关闭后回调 */
const handleClosed = () => {
  selectedRows.value = []
}

/** 确认选择 */
const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条数据')
    return
  }
  emit('confirm', props.multiple ? selectedRows.value : selectedRows.value[0])
  visible.value = false
}

// 暴露方法供外部调用
defineExpose({
  refresh: getList,
  setQueryParams: (params: Object) => {
    Object.assign(queryParams, params)
    getList()
  }
})
</script>
