<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,
  excelExportApi
} from '@/api/business/capital/transactions'
import { getPageApi as getCapitalAccountPageApi } from '@/api/business/capital/account'
import { getPageApi as getCorporationPageApi } from '@/api/business/corporation/corporation'

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>({ type: 1 })

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

const queryConfig: FormConfigType[] = [
  {
    type: 'select',
    prop: 'corporationId',
    label: '归属公司',
    keyName: 'id',
    labelName: 'name',
    async option() {
      const data = await getCorporationPageApi({ searchAll: true })
      return data.records
    }
  },
  {
    type: 'select',
    prop: 'capitalAccountId',
    label: '资金账号',
    keyName: 'id',
    labelName: 'accountAlias',
    async option() {
      const data = await getCapitalAccountPageApi({ searchAll: true })
      return data.records
    }
  },
  {
    type: 'datePicker',
    prop: 'tradingTime',
    label: '交易时间',
    datePickerType: 'daterange',
    defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]
  },
  {
    type: 'select',
    prop: 'type',
    label: '交易类型',
    option: [
      {
        key: 1,
        label: '收入'
      },
      {
        key: 0,
        label: '支出'
      }
    ]
  },
  {
    type: 'select',
    prop: 'targetType',
    label: '对方类型',
    dict: 'target_type'
  }
]

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 = '新增'
    }
  },
  {
    common: 'delete',
    disabled() {
      return selectKeys.value.length == 0
    },
    click() {
      handleRemove(selectKeys.value)
    }
  },
  {
    text: '导出',
    icon: 'Download',
    type: 'primary',
    click() {
      excelExportApi(queryData.value).then(() => {
        ElMessage.success('导出成功')
      })
    }
  }
]

const columnConfig: ColumnConfigType[] = [
  {
    prop: 'corporationName',
    label: '归属公司'
  },
  {
    prop: 'accountAlias',
    label: '资金账号'
  },
  {
    prop: 'tradingTime',
    label: '交易时间'
  },
  {
    prop: 'amount',
    label: '收入',
    formatter(row) {
      return row.type == 1 ? row.amount : ''
    },
    width: 80
  },
  {
    prop: 'amount',
    label: '支出',
    formatter(row) {
      return row.type == 1 ? '' :row.amount
    },
    width: 80
  },
  {
    prop: 'balance',
    label: '余额',
    width: 100
  },
  // {
  //   prop: 'type',
  //   label: '交易类型',
  //   formatter(row) {
  //     return row.type == 1 ? '收入' : '支出'
  //   }
  // },
  // {
  //   prop: 'amount',
  //   label: '交易金额'
  // },
  {
    prop: 'targetType',
    label: '对方类型',
    dict: 'target_type',
    width: 90
  },
  {
    prop: 'targetAccountName',
    label: '对方账户名'
  },
  {
    prop: 'targetDepositBank',
    label: '对方开户银行'
  },
  {
    prop: 'targetAccount',
    label: '对方账号'
  },
  {
    prop: 'remark',
    label: '摘要',
    showOverflowTooltip: true
  },
  {
    width: 250,
    handleConfig: [
      {
        common: 'update',
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '编辑'
          getDetailApi({ id: row.id }).then((resp: StrAnyObj) => {
            formData.value = resp
          })
        }
      },
      {
        common: 'delete',
        click(row) {
          handleRemove([row.id])
        }
      }
    ]
  }
]

const formConfig: FormConfigType[] = [
  {
    type: 'select',
    prop: 'capitalAccountId',
    label: '资金账号',
    keyName: 'id',
    labelName: 'accountAlias',
    async option() {
      const data = await getCapitalAccountPageApi({ searchAll: true })
      return data.records
    },
    rule: [{ required: true, message: '资金账号不能为空', trigger: 'blur' }]
  },
  {
    type: 'datePicker',
    prop: 'tradingTime',
    label: '交易时间',
    datePickerType: 'datetime',
    format: 'YYYY-MM-DD hh:mm:ss',
    valueFormat: 'YYYY-MM-DD hh:mm:ss',
    defaultTime: new Date(),
    rule: [{ required: true, message: '交易时间不能为空', trigger: 'blur' }]
  },
  {
    type: 'radio',
    prop: 'type',
    label: '交易类型',
    option: [
      {
        key: 1,
        label: '收入'
      },
      {
        key: 0,
        label: '支出'
      }
    ],
    rule: [{ required: true, message: '交易类型不能为空', trigger: 'blur' }]
  },
  {
    type: 'inputNumber',
    prop: 'amount',
    label: '交易金额',
    min: 0.01,
    precision: 2,
    disabled() {
      return formData.value.id != null
    },
    rule: [{ required: true, message: '交易金额不能为空', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'targetType',
    label: '对方类型',
    dict: 'target_type',
    disabled() {
      return formData.value.id != null
    },
    rule: [{ required: true, message: '对方类型不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'targetAccountName',
    label: '对方账户名',
    disabled() {
      return formData.value.id != null
    }
  },
  {
    type: 'input',
    prop: 'targetDepositBank',
    label: '对方开户银行',
    disabled() {
      return formData.value.id != null
    }
  },
  {
    type: 'input',
    prop: 'targetAccount',
    label: '对方账号',
    disabled() {
      return formData.value.id != null
    }
  },
  {
    type: 'input',
    prop: 'remark',
    itemType: 'textarea',
    rows: 5,
    label: '摘要'
  }
]

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()
    })
  })
}
</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"
    >
      <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24"> </a-form>
    </a-dialog>
  </div>
</template>
