<script setup lang="ts">
import FileUpload from '@/components/FlieUpload/index.vue'
import DeptTreeSelect from '@/views/components/DeptTreeSelect/index.vue'
import AForm from '@/components/AForm/index.vue'
import { StrAnyObj } from '@/typings'
import { FormConfigType } from '@/components/AForm/type'
import { getPageApi as getCorporationPageApi } from '@/api/business/corporation/corporation'
import { getPageApi as getCapitalAccountPageApi } from '@/api/business/capital/account'
import { ColumnConfigType } from '@/components/ATable/type'
import { getDetailApi } from '@/api/business/payment/requests'

const props = withDefaults(
  defineProps<{
    businessId: string
    disabled?: boolean
  }>(),
  {
    disabled: true
  }
)

watch(
  () => props.businessId,
  () => {
    nextTick(() => deptIdRef.value?.load())
    getDetailApi({ id: props.businessId }).then((resp: StrAnyObj) => {
      formData.value = resp
      updateAmount()
      updateDetailRemark()
    })
  },
  { immediate: true }
)

const formData = ref<StrAnyObj>({ paymentRequestsDetailList: [{}] })
const deptIdRef = ref<InstanceType<typeof DeptTreeSelect>>()

const formConfig: FormConfigType[] = [
  {
    type: 'select',
    prop: 'corporationId',
    label: '归属公司',
    keyName: 'id',
    labelName: 'name',
    async option() {
      const data = await getCorporationPageApi({ searchAll: true })
      return data.records
    },
    placeholder: props.disabled ? '' : undefined,
    rule: [{ required: true, message: '归属公司id不能为空', trigger: 'blur' }]
  },
  {
    type: 'slot',
    prop: 'deptId',
    label: '归属部门',
    placeholder: props.disabled ? '' : undefined,
    rule: [{ required: true, message: '部门id不能为空', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'type',
    label: '请款类型',
    dict: 'payment_requests_type',
    placeholder: props.disabled ? '' : undefined,
    rule: [{ required: true, message: '请款类型不能为空', trigger: 'blur' }]
  },
  {
    type: 'datePicker',
    prop: 'useTime',
    label: '用款时间',
    datePickerType: 'datetime',
    format: 'YYYY-MM-DD 00:00:00',
    valueFormat: 'YYYY-MM-DD 00:00:00',
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    itemType: 'textarea',
    prop: 'useRemark',
    label: '用款说明',
    rows: 3,
    span: 24,
    placeholder: '自动拼接请款明细中的款项说明',
    disabled: true
  },
  {
    type: 'slot',
    prop: 'atts',
    label: '上传附件',
    span: 24,
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'slot',
    prop: 'detailTable',
    label: '请款明细',
    span: 24,
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    prop: 'totalAmount',
    label: '付款总金额',
    disabled: true,
    placeholder: '自动统计请款明细中的请款金额'
  },
  {
    type: 'inputNumber',
    prop: 'documentQuantity',
    label: '单据数量',
    min: 0,
    precision: 0,
    placeholder: props.disabled ? '' : undefined,
    rule: [{ required: true, message: '单据数量不能为空', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'payType',
    label: '付款方式',
    dict: 'pay_type',
    placeholder: props.disabled ? '' : undefined,
    rule: [{ required: true, message: '付款方式不能为空', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'capitalAccountId',
    label: '付款账户',
    keyName: 'id',
    labelName: 'accountAlias',
    async option() {
      const data = await getCapitalAccountPageApi({ searchAll: true })
      return data.records
    },
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    prop: 'accountName',
    label: '户名',
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    prop: 'account',
    label: '银行账号',
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    prop: 'depositBank',
    label: '开户银行',
    placeholder: props.disabled ? '' : undefined
  },
  {
    type: 'input',
    prop: 'correspondentNumber',
    label: '联行号/SWIFT Code',
    placeholder: props.disabled ? '' : undefined
  }
]

const detailTableColumnConfig: ColumnConfigType[] = [
  {
    slot: 'expenseType',
    label: '费用类型',
    width: 250
  },
  {
    slot: 'remark',
    label: '款项说明'
  },
  {
    slot: 'amount',
    label: '请款金额',
    width: 180
  },
  {
    width: 100,
    if: () => !props.disabled,
    handleConfig: [
      {
        common: 'delete',
        click(row, index) {
          formData.value.paymentRequestsDetailList.splice(index, 1)
          updateDetailRemark()
          updateAmount()
        }
      }
    ]
  }
]

function addPaymentRequestsDetailList() {
  formData.value.paymentRequestsDetailList.push({})
}

function updateDetailRemark() {
  formData.value.useRemark = formData.value.paymentRequestsDetailList
    .map((item) => item.remark)
    .filter((item) => item !== '' && item !== null && item !== undefined)
    .join(' - \n')
}

function updateAmount() {
  formData.value.totalAmount = formData.value.paymentRequestsDetailList
    .map((item) => item.amount)
    .filter((item) => item !== '' && item !== null && item !== undefined)
    .reduce((pre, next) => pre + next, 0)
}
</script>

<template>
  <a-form ref="formRef" v-model="formData" :config="formConfig" :span="12" :disabled="disabled">
    <template #deptId>
      <dept-tree-select ref="deptIdRef" v-model="formData.deptId" :disabled="disabled" />
    </template>
    <template #atts>
      <file-upload v-model="formData.atts" :disabled="disabled" />
    </template>
    <template #detailTable>
      <a-table
        :data="formData.paymentRequestsDetailList"
        :columnConfig="detailTableColumnConfig"
        style="width: 100%"
        :card="false"
      >
        <template #expenseType="scope">
          <a-select v-model="scope.row.expenseType" dict="expense_type" :disabled="disabled" />
        </template>
        <template #remark="scope">
          <a-input
            v-model="scope.row.remark"
            type="textarea"
            :rows="2"
            :disabled="disabled"
            @change="updateDetailRemark"
          />
        </template>
        <template #amount="scope">
          <a-inputNumber
            v-model="scope.row.amount"
            :min="0.01"
            :precision="2"
            :disabled="disabled"
            @change="updateAmount"
          />
        </template>
      </a-table>
      <el-button
        v-if="!disabled"
        style="width: 100%; margin-bottom: 20px"
        type="primary"
        @click="addPaymentRequestsDetailList"
      >
        添加行
      </el-button>
    </template>
  </a-form>
</template>

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