<template>
  <ContentWrap>
    <!-- 使用 Search 组件 -->
    <Search
      :schema="schema"
      :model="queryParams"
      :expand="true"
      :expandDefault="false"
      expand-field="projectCode"
      @search="handleQuery"
      @reset="resetQuery"
    >
      <!-- 自定义按钮插槽 -->
      <template #actionMore>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['contract:procur:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['contract:procur:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['contract:procur:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </template>
    </Search>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in contractStatusOptions"
        :key="item.value"
        :label="item.label"
        :name="item.value"
      />
<!--      <el-tab-pane label="审批中" name="1" />-->
<!--      <el-tab-pane label="执行中" name="2" />-->
<!--      <el-tab-pane label="已结项" name="3" />-->
<!--      <el-tab-pane label="已作废" name="4" />-->
    </el-tabs>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="合同编号" align="center" prop="contractNo" width="120" fixed="left" />
      <el-table-column label="合同名称" align="center" prop="contractName" width="180" fixed="left" >
      <template #default="{ row }">
        <el-link type="primary" @click="openLookup(row.id)">{{row.contractName}}</el-link>
      </template>
      </el-table-column>
      <el-table-column label="合同类别" align="center" prop="contractCategory" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONTRACT_CONTRACT_CATEGORY" :value="scope.row.contractCategory" />
        </template>
      </el-table-column>
      <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="projectCode" width="120" />-->
      <el-table-column
        label="本次合同金额"
        align="center"
        prop="currentContractAmount"
        width="120"
        :formatter="erpPriceTableColumnFormatter"
      />
      <el-table-column label="累计合同金额" align="center" prop="totalContractAmount" width="120" :formatter="erpPriceTableColumnFormatter"/>
      <el-table-column label="已收金额" align="center" prop="paidAmount" width="120" :formatter="erpPriceTableColumnFormatter"/>
      <el-table-column label="币种" align="center" prop="currency" width="80">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONTRACT_CURRENCY" :value="scope.row.currency" />
        </template>
      </el-table-column>
      <el-table-column label="主合同标记" align="center" prop="isMainContract" width="100">
        <template #default="{ row }">
          <span>{{ row.isMainContract == '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主合同编号" align="center" prop="mainContractNo" width="120" />
      <el-table-column label="合同版本" align="center" prop="contractVersion" width="100" />
      <el-table-column
        label="生效日期"
        align="center"
        prop="effectiveDate"
        width="120"
        :formatter="dateFormatter2"
      />
      <el-table-column
        label="失效日期"
        align="center"
        prop="expiryDate"
        width="120"
        :formatter="dateFormatter2"
      />
      <el-table-column
        label="乙方签字日期"
        align="center"
        prop="partyBSignDate"
        width="120"
        :formatter="dateFormatter2"
      />
      <el-table-column
        label="终止日期"
        align="center"
        prop="terminationDate"
        width="120"
        :formatter="dateFormatter2"
      />
      <el-table-column label="终止原因" align="center" prop="terminationReason" width="150" />
      <el-table-column label="经办部门" align="center" prop="handlingDepartment" width="120" />
      <el-table-column label="经办人" align="center" prop="handler" width="100" />
      <el-table-column
        label="以合同收款标记"
        align="center"
        prop="isContractPaymentMarked"
        width="140"
      >
        <template #default="{ row }">
          <span>{{ row.isContractPaymentMarked == '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源单号" align="center" prop="sourceDocumentNo" width="120" />
      <el-table-column label="备注" align="center" prop="remarks" width="200" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column label="合同状态" align="center" prop="contractStatus" width="100" fixed="right">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONTRACT_CONTRACT_STATUS" :value="scope.row.contractStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['contract:sale:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['contract:sale:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractSaleForm ref="formRef" @success="getList" />
  <ContractSaleLookup ref="lookupRef"/>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { MainApi, MainVO } from '@/api/contract/contractsale'
import ContractSaleForm from './ContractSaleForm.vue'
import { Search } from '@/components/Search'
import { FormSchema } from '@/types/form'
import ContractSaleLookup from './ContractSaleLookup.vue'
import { erpPriceTableColumnFormatter } from '@/utils'
import { TabsPaneContext } from 'element-plus'

//字典数据
const contractStatusOptions = getStrDictOptions(DICT_TYPE.CONTRACT_CONTRACT_STATUS)
const contractCategoryOptions = getIntDictOptions(DICT_TYPE.CONTRACT_CONTRACT_CATEGORY)
const currencyOptions = getStrDictOptions(DICT_TYPE.CONTRACT_CURRENCY)

// 搜索表单的 schema 配置
const schema: FormSchema[] = [
  {
    field: 'contractNo',
    label: '合同编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入合同编号',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'contractName',
    label: '合同名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入合同名称',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'partyACompany',
    label: '甲方公司',
    component: 'Input',
    componentProps: {
      placeholder: '请输入甲方公司',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'partyBCompany',
    label: '乙方公司',
    component: 'Input',
    componentProps: {
      placeholder: '请输入乙方公司',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'currency',
    label: '币种',
    component: 'Select',
    componentProps: {
      placeholder: '请选择币种',
      clearable: true,
      options: currencyOptions,
      class: '!w-240px'
    }
  },
  {
    field: 'projectCode',
    label: '项目编码',
    component: 'Input',
    componentProps: {
      placeholder: '请输入项目编码',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'handlingDepartment',
    label: '经办部门',
    component: 'Input',
    componentProps: {
      placeholder: '请输入经办部门',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'projectName',
    label: '项目名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入项目名称',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'handler',
    label: '经办人',
    component: 'Input',
    componentProps: {
      placeholder: '请输入经办人',
      clearable: true,
      class: '!w-240px'
    }
  },
  {
    field: 'contractStatus',
    label: '合同状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择合同状态',
      clearable: true,
      options: contractStatusOptions,
      class: '!w-240px'
    }
  },
  {
    field: 'contractCategory',
    label: '合同类别',
    component: 'Select',
    componentProps: {
      placeholder: '请选择合同类别',
      clearable: true,
      options: contractCategoryOptions,
      class: '!w-240px'
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')],
      class: '!w-220px'
    }
  }
]

/** 合同信息主表 列表 */
defineOptions({ name: 'ContractSale' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const currentRow = ref() // 当前选中的行
const list = ref<MainVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  contractType: 1,
  contractNo: '',
  contractName: '',
  partyACompany: '',
  partyBCompany: '',
  currency: '',
  projectCode: '',
  handlingDepartment: '',
  paymentTerms: '',
  projectName: '',
  handler: '',
  contractStatus: '',
  contractCategory: '',
  createTime: []
})
const exportLoading = ref(false) // 导出的加载中
const activeName = ref('1') // 列表 tab
/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.contractStatus = tab.paneName
  getList()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MainApi.getMainPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = (model) => {
  // 必须手动更新 queryParams！
  queryParams.value = { ...queryParams.value, ...model } // 合并数据
  getList()
}

/** 重置按钮操作 */
const resetQuery = (model) => {
  // 必须手动更新 queryParams！
  queryParams.value = { ...queryParams.value, ...model } // 合并数据
  queryParams.value.contractType = 2
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/**查看*/
const lookupRef = ref()
const openLookup=(id:number)=>{
  lookupRef.value.open( id)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MainApi.deleteMain(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除合同信息主表 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await MainApi.deleteMainList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: MainVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MainApi.exportMain(queryParams.value)
    download.excel(data, '合同信息主表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
