<script setup lang="ts">
import AForm from '@/components/AForm/index.vue'
import { FormConfigType } from '@/components/AForm/type'
import { ToolbarConfigType } from '@/components/AToolbar/type'
import { ColumnConfigType } from '@/components/ATable/type'
import { StrAnyObj, StrAnyObjArr } from '@/typings'
import { useHandleData } from '@/utils/useHandleData'
import {
  getPageApi,
  getDetailApi,
  addApi,
  editApi,
  deleteApi
} from '@/api/business/payment/requests'
import {getPageApi as getCorporationPageApi} from "@/api/business/corporation/corporation";
import DeptTreeSelect from "@/views/components/DeptTreeSelect/index.vue";
import {getPageApi as getCapitalAccountPageApi} from "@/api/business/capital/account";

const queryRef = ref<InstanceType<typeof AForm>>()
const formRef = ref<InstanceType<typeof AForm>>()

const showQuery = ref<boolean>(true)
const selectKeys = ref<string[]>([])
const pageTotal = ref<number>(0)

const queryData = ref<StrAnyObj>({ pageNum: 1, pageSize: 10 })
const tableData = ref<StrAnyObjArr>([])
const formData = ref<StrAnyObj>({ paymentRequestsDetailList: [{}] })

const dialogTitle = ref<string>('')
const dialogVisible = ref<boolean>(false)

const deptIdRef = ref<InstanceType<typeof DeptTreeSelect>>()

const queryConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'corporationId',
    label: '归属公司id'
  },
  {
    type: 'input',
    prop: 'deptId',
    label: '部门id'
  },
  {
    type: 'input',
    prop: 'type',
    label: '请款类型'
  },
  {
    type: 'input',
    prop: 'useTime',
    label: '用款时间'
  },
  {
    type: 'input',
    prop: 'useRemark',
    label: '用款说明'
  },
  {
    type: 'input',
    prop: 'atts',
    label: '附件列表'
  },
  {
    type: 'input',
    prop: 'totalAmount',
    label: '付款总金额'
  },
  {
    type: 'input',
    prop: 'documentQuantity',
    label: '单据数量'
  },
  {
    type: 'input',
    prop: 'payType',
    label: '付款方式'
  },
  {
    type: 'input',
    prop: 'capitalAccountId',
    label: '资金账户id'
  },
  {
    type: 'input',
    prop: 'accountName',
    label: '户名'
  },
  {
    type: 'input',
    prop: 'account',
    label: '银行账号'
  },
  {
    type: 'input',
    prop: 'depositBank',
    label: '开户银行'
  },
  {
    type: 'input',
    prop: 'correspondentNumber',
    label: '联行号/ SWIFT Code'
  }
]

const toolbarConfig: ToolbarConfigType[] = [
  {
    common: 'search',
    click() {
      queryData.value.pageNum = 1
      getPage()
    }
  },
  {
    common: 'reset',
    click() {
      queryRef.value?.resetFields()
      getPage()
    }
  },
  {
    common: 'add',
    click() {
      dialogVisible.value = true
      dialogTitle.value = '新增'
      nextTick(() => deptIdRef.value?.load())
    }
  },
  {
    common: 'delete',
    disabled() {
      return selectKeys.value.length == 0
    },
    click() {
      handleRemove(selectKeys.value)
    }
  }
]

const columnConfig: ColumnConfigType[] = [
  {
    prop: 'corporationName',
    label: '归属公司'
  },
  {
    prop: 'deptName',
    label: '归属部门'
  },
  {
    prop: 'type',
    label: '请款类型',
    dict: 'payment_requests_type'
  },
  {
    prop: 'userName',
    label: '请款人'
  },
  {
    prop: 'createTime',
    label: '请款时间'
  },
  {
    prop: 'useTime',
    label: '用款时间'
  },
  {
    prop: 'useRemark',
    label: '用款说明',
    showOverflowTooltip: true
  },
  {
    prop: 'totalAmount',
    label: '请款金额'
  },
  {
    prop: 'payType',
    label: '付款方式',
    dict: 'pay_type'
  },
  {
    prop: 'capitalAccountName',
    label: '付款账户'
  },
  {
    prop: 'approvalStatus',
    label: '审批状态'
  },
  {
    prop: 'paymentStatus',
    label: '放款状态'
  },
  {
    width: 250,
    handleConfig: [
      {
        common: 'update',
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '编辑'
          getDetailApi({ id: row.id }).then((resp: StrAnyObj) => {
            formData.value = resp
          })
          nextTick(() => deptIdRef.value?.load())
        }
      },
      {
        common: 'delete',
        click(row) {
          handleRemove([row.id])
        }
      }
    ]
  }
]

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

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

onMounted(() => {
  getPage()
})

function getPage() {
  getPageApi(queryData.value).then((resp) => {
    tableData.value = resp.records
    pageTotal.value = resp.total
  })
}

function tableSelectionChange(item: StrAnyObjArr) {
  selectKeys.value = item.map((item) => item.id)
}

function formSubmit() {
  formRef.value?.validate(() => {
    if (formData.value.id) {
      editApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('修改成功')
        getPage()
      })
    } else {
      addApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('新增成功')
        getPage()
      })
    }
  })
}

function formClosed() {
  formRef.value?.resetFields()
}

function handleRemove(idList: string[]) {
  useHandleData('是否确认删除？', () => {
    deleteApi({ idList }).then(() => {
      ElMessage.success('删除成功')
      getPage()
    })
  })
}

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>
  <div>
    <el-card v-if="showQuery">
      <a-form ref="queryRef" v-model="queryData" :config="queryConfig" :span="6"> </a-form>
    </el-card>

    <a-table
      selection
      :data="tableData"
      :page-total="pageTotal"
      :toolbar-config="toolbarConfig"
      :column-config="columnConfig"
      v-model:showQuery="showQuery"
      v-model:page-num="queryData.pageNum"
      v-model:page-size="queryData.pageSize"
      @page-num-change="getPage"
      @page-size-change="getPage"
      @selection-change="tableSelectionChange"
    >
    </a-table>

    <a-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @submit="formSubmit"
      @closed="formClosed"
      width="1400px"
      height="200px"
    >
      <a-form ref="formRef" v-model="formData" :config="formConfig" :span="12">
        <template #dept>
          <dept-tree-select ref="deptIdRef" v-model="formData.deptId" />
        </template>
        <template #atts>
        </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"/>
            </template>
            <template #remark="scope">
              <a-input v-model="scope.row.remark" type="textarea" rows="2" @change="updateDetailRemark"/>
            </template>
            <template #amount="scope">
              <a-inputNumber v-model="scope.row.amount" :min="0.01" :precision="2" @change="updateAmount" />
            </template>
          </a-table>
          <el-button style="width: 100%; margin-bottom: 20px" type="primary" @click="addPaymentRequestsDetailList">
            添加行
          </el-button>
        </template>
      </a-form>
    </a-dialog>
  </div>
</template>
