<template>
  <Dialog title="回款记录" v-model="show" width="800px">
    <el-table :data="feebackList" border stripe>
      <el-table-column type="index" width="50" />
      <el-table-column prop="money" label="回款金额" />
      <el-table-column prop="applyTime" label="申请日期" />
      <el-table-column prop="isPayoff" label="是否结清" />
      <el-table-column prop="stateName" label="审核状态" />
    </el-table>
    <el-divider direction="horizontal" />

    <el-button v-show="showAdd" class="mb-10px" type="primary" @click="handleAdd">
      新增回款
    </el-button>
    <el-form v-if="!showAdd" :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-form-item label="回款金额" prop="money">
        <el-input-number v-model="form.money" :min="0" :controls="false" placeholder="请输入金额" />
      </el-form-item>
      <el-form-item label="是否结清" prop="isPayoff">
        <el-radio-group v-model="form.isPayoff">
          <el-radio :label="true"> 结清 </el-radio>
          <el-radio :label="false"> 未结清 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注">
        <Editor v-model:modelValue="form.remark" />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="formLoading" type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="showAdd = true">取消</el-button>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup name="DialogFeeback">
import { getPaymentPage, createPayment } from '@/api/clue/payment'

const message = useMessage() // 消息弹窗

const show = ref(false)
const feebackList = ref([])
const orderId = ref('')

function open(signId) {
  show.value = true
  orderId.value = signId
  try {
    getList()
  } catch (error) {
    console.log(error)
  }
}

const showAdd = ref(true)
const form = ref({})
const rules = {
  money: { required: true, message: '回款金额不可为空', trigger: 'blur' }
}

function getList() {
  getPaymentPage({ signId: orderId.value, pageNo: 1, pageSize: 100 }).then((data) => {
    feebackList.value = data.list
  })
}

function handleAdd() {
  showAdd.value = false
  form.value = {
    signId: orderId.value,
    money: undefined,
    isPayoff: true,
    remark: undefined
  }
}

const formRef = ref()
const formLoading = ref(false)
async function onSubmit() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await createPayment(form.value)
    message.success('申请成功！')
    getList()
    showAdd.value = true
  } finally {
    formLoading.value = false
  }
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped></style>
