<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="合同名称" prop="conName">
        <el-input v-model="queryParams.conName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目编号" prop="prjId">
        <el-input v-model="queryParams.prjId" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
      </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="['pms:contract:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['pms:contract:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['pms:contract:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="合同编号" align="center" prop="conId" />
      <el-table-column label="合同名称" align="center" prop="conName" min-width="180" show-overflow-tooltip />
      <el-table-column label="合同编号" align="center" prop="conCode" width="140" />
      <el-table-column label="签约金额" align="center" prop="signAmount" width="120" />
      <el-table-column label="签约日期" align="center" prop="signDate" width="100" />
      <el-table-column label="合同状态" align="center" prop="conState" width="80" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pms:contract:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pms:contract:remove']">删除</el-button>
        </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" />

    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="合同信息" name="info">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同名称" prop="conName">
                  <el-input v-model="form.conName" placeholder="请输入合同名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="conCode">
                  <el-input v-model="form.conCode" placeholder="请输入合同编号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="项目编号" prop="prjId">
                  <el-input v-model="form.prjId" placeholder="请输入项目编号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同年份" prop="conYear">
                  <el-input v-model="form.conYear" placeholder="请输入合同年份" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同种类" prop="conKind">
                  <el-input v-model="form.conKind" placeholder="请输入合同种类" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="conType">
                  <el-input v-model="form.conType" placeholder="请输入合同类型" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="签约金额" prop="signAmount">
                  <el-input-number v-model="form.signAmount" :precision="2" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实际金额" prop="realAmount">
                  <el-input-number v-model="form.realAmount" :precision="2" style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="签约日期" prop="signDate">
                  <el-date-picker v-model="form.signDate" type="date" placeholder="选择日期" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签约人" prop="signUser">
                  <el-input v-model="form.signUser" placeholder="请输入签约人" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="payBank">
                  <el-input v-model="form.payBank" placeholder="请输入开户银行" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="payAccount">
                  <el-input v-model="form.payAccount" placeholder="请输入银行账号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="银行地址" prop="payBankAddr">
                  <el-input v-model="form.payBankAddr" placeholder="请输入银行地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="财务联系人" prop="payContact">
                  <el-input v-model="form.payContact" placeholder="请输入财务联系人" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="合同状态" prop="conState">
                  <el-input v-model="form.conState" placeholder="请输入合同状态" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="费用明细" name="fee">
          <el-button type="primary" plain icon="Plus" @click="handleAddFee">新增费用</el-button>
          <el-table :data="feeList" class="mt-2">
            <el-table-column label="费用名称" prop="feeName" />
            <el-table-column label="金额" prop="feeAmount" />
            <el-table-column label="备注" prop="remark" />
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleEditFee(scope.row)">编辑</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelFee(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="开票记录" name="bill">
          <el-button type="primary" plain icon="Plus" @click="handleAddBill">新增开票</el-button>
          <el-table :data="billList" class="mt-2">
            <el-table-column label="开票金额" prop="billAmount" />
            <el-table-column label="开票日期" prop="billDate" />
            <el-table-column label="发票号" prop="billNo" />
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleEditBill(scope.row)">编辑</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelBill(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="付款记录" name="payment">
          <el-button type="primary" plain icon="Plus" @click="handleAddPayment">新增付款</el-button>
          <el-table :data="paymentList" class="mt-2">
            <el-table-column label="付款金额" prop="payAmount" />
            <el-table-column label="付款日期" prop="payDate" />
            <el-table-column label="付款方式" prop="payMethod" />
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleEditPayment(scope.row)">编辑</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelPayment(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="变更日志" name="log">
          <el-button type="primary" plain icon="Plus" @click="handleAddLog">新增日志</el-button>
          <el-table :data="logList" class="mt-2">
            <el-table-column label="变更内容" prop="logContent" min-width="200" show-overflow-tooltip />
            <el-table-column label="变更日期" prop="logDate" width="120" />
            <el-table-column label="操作人" prop="operator" width="100" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleDelLog(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="参考文件" name="ref">
          <el-button type="primary" plain icon="Plus" @click="handleAddRef">新增参考文件</el-button>
          <el-table :data="refList" class="mt-2">
            <el-table-column label="参考名称" prop="refName" min-width="200" />
            <el-table-column label="参考地址" prop="refUrl" min-width="200" show-overflow-tooltip />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleDelRef(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog title="编辑费用" v-model="editFeeOpen" width="500px" append-to-body>
        <el-form :model="editFeeForm" label-width="100px">
          <el-form-item label="费用名称">
            <el-input v-model="editFeeForm.feeName" />
          </el-form-item>
          <el-form-item label="金额">
            <el-input-number v-model="editFeeForm.feeAmount" :precision="2" style="width:100%" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editFeeForm.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="submitEditFee">确 定</el-button>
          <el-button @click="editFeeOpen = false">取 消</el-button>
        </template>
      </el-dialog>

      <el-dialog title="编辑开票" v-model="editBillOpen" width="500px" append-to-body>
        <el-form :model="editBillForm" label-width="100px">
          <el-form-item label="开票金额">
            <el-input-number v-model="editBillForm.billAmount" :precision="2" style="width:100%" />
          </el-form-item>
          <el-form-item label="开票日期">
            <el-date-picker v-model="editBillForm.billDate" type="date" style="width:100%" />
          </el-form-item>
          <el-form-item label="发票号">
            <el-input v-model="editBillForm.billNo" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="submitEditBill">确 定</el-button>
          <el-button @click="editBillOpen = false">取 消</el-button>
        </template>
      </el-dialog>

      <el-dialog title="编辑付款" v-model="editPaymentOpen" width="500px" append-to-body>
        <el-form :model="editPaymentForm" label-width="100px">
          <el-form-item label="付款金额">
            <el-input-number v-model="editPaymentForm.payAmount" :precision="2" style="width:100%" />
          </el-form-item>
          <el-form-item label="付款日期">
            <el-date-picker v-model="editPaymentForm.payDate" type="date" style="width:100%" />
          </el-form-item>
          <el-form-item label="付款方式">
            <el-input v-model="editPaymentForm.payMethod" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="submitEditPayment">确 定</el-button>
          <el-button @click="editPaymentOpen = false">取 消</el-button>
        </template>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PmsContract">
import {
  listContract, getContract, addContract, updateContract, delContract,
  listContractFee, addContractFee, updateContractFee, delContractFee,
  listContractBill, addContractBill, updateContractBill, delContractBill,
  listContractPayment, addContractPayment, updateContractPayment, delContractPayment,
  listContractLog, addContractLog, delContractLog,
  listContractRef, addContractRef, delContractRef
} from '@/api/pms/contract'

const { proxy } = getCurrentInstance()
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const open = ref(false)
const activeTab = ref('info')
const contractList = ref([])
const feeList = ref([])
const billList = ref([])
const paymentList = ref([])
const logList = ref([])
const refList = ref([])
const editFeeOpen = ref(false)
const editBillOpen = ref(false)
const editPaymentOpen = ref(false)
const editFeeForm = ref({})
const editBillForm = ref({})
const editPaymentForm = ref({})

const data = reactive({
  form: {},
  queryParams: { pageNum: 1, pageSize: 10, conName: undefined, prjId: undefined },
  rules: { conName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }] }
})

const { queryParams, form, rules } = toRefs(data)

function getList() {
  loading.value = true
  listContract(queryParams.value).then(response => {
    contractList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function cancel() { open.value = false; reset() }

function reset() {
  form.value = { conId: undefined, conName: undefined, conCode: undefined, prjId: undefined, conYear: undefined, conKind: undefined, conType: undefined, signAmount: undefined, realAmount: undefined, signDate: undefined, signUser: undefined, payBank: undefined, payAccount: undefined, payBankAddr: undefined, payContact: undefined, payTele: undefined, conState: undefined }
  feeList.value = []; billList.value = []; paymentList.value = []; logList.value = []; refList.value = []
  activeTab.value = 'info'
  proxy.resetForm("formRef")
}

function handleQuery() { queryParams.value.pageNum = 1; getList() }
function resetQuery() { proxy.resetForm("queryRef"); handleQuery() }

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.conId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAdd() { reset(); open.value = true; title.value = '新增合同' }

function handleUpdate(row) {
  reset()
  getContract(row.conId || ids.value[0]).then(response => {
    form.value = response.data
    open.value = true; title.value = '修改合同'
    loadSubData()
  })
}

function handleDetail(row) {
  reset()
  getContract(row.conId).then(response => {
    form.value = response.data
    open.value = true; title.value = '合同详情'
    loadSubData()
  })
}

function loadSubData() {
  const conId = form.value.conId
  listContractFee({ conId }).then(r => { feeList.value = r.rows || r.data || [] })
  listContractBill({ conId }).then(r => { billList.value = r.rows || r.data || [] })
  listContractPayment({ conId }).then(r => { paymentList.value = r.rows || r.data || [] })
  listContractLog({ conId }).then(r => { logList.value = r.rows || r.data || [] })
  listContractRef({ conId }).then(r => { refList.value = r.rows || r.data || [] })
}

function handleAddFee() { addContractFee({ conId: form.value.conId }).then(() => loadSubData()) }
function handleDelFee(row) { delContractFee(row.feeId).then(() => loadSubData()) }
function handleEditFee(row) { editFeeForm.value = { ...row }; editFeeOpen.value = true }
function submitEditFee() { updateContractFee(editFeeForm.value).then(() => { editFeeOpen.value = false; loadSubData(); proxy.$modal.msgSuccess("修改成功") }) }
function handleAddBill() { addContractBill({ conId: form.value.conId }).then(() => loadSubData()) }
function handleDelBill(row) { delContractBill(row.billId).then(() => loadSubData()) }
function handleEditBill(row) { editBillForm.value = { ...row }; editBillOpen.value = true }
function submitEditBill() { updateContractBill(editBillForm.value).then(() => { editBillOpen.value = false; loadSubData(); proxy.$modal.msgSuccess("修改成功") }) }
function handleAddPayment() { addContractPayment({ conId: form.value.conId }).then(() => loadSubData()) }
function handleDelPayment(row) { delContractPayment(row.payId).then(() => loadSubData()) }
function handleEditPayment(row) { editPaymentForm.value = { ...row }; editPaymentOpen.value = true }
function submitEditPayment() { updateContractPayment(editPaymentForm.value).then(() => { editPaymentOpen.value = false; loadSubData(); proxy.$modal.msgSuccess("修改成功") }) }
function handleAddLog() { addContractLog({ conId: form.value.conId }).then(() => loadSubData()) }
function handleDelLog(row) { delContractLog(row.logId).then(() => loadSubData()) }
function handleAddRef() { addContractRef({ conId: form.value.conId }).then(() => loadSubData()) }
function handleDelRef(row) { delContractRef(row.refId).then(() => loadSubData()) }

function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      (form.value.conId ? updateContract(form.value) : addContract(form.value)).then(() => {
        proxy.$modal.msgSuccess(form.value.conId ? "修改成功" : "新增成功")
        open.value = false; getList()
      })
    }
  })
}

function handleDelete(row) {
  const conIds = row.conId || ids.value
  proxy.$modal.confirm('是否确认删除合同编号为"' + conIds + '"的数据项？').then(() => {
    return delContract(conIds)
  }).then(() => { getList(); proxy.$modal.msgSuccess("删除成功") }).catch(() => {})
}

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