<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 {
  getDetailApi,
  getRemitPageApi,
  remitApi,
  remitExcelExportApi
} 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'
import MoneyPDF from '@/components/PDF/moneyPDF.vue'
import { getPdf } from '@/utils/getPdf.js'

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 detailData = ref<StrAnyObj>({ paymentRequestsDetailList: [{}] })
const formData = ref<StrAnyObj>({})

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

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

const disabled = ref(false)

const dialogPrint = ref<boolean>(false)
const rowData = ref<StrAnyObj>({})

const queryConfig: FormConfigType[] = [
  {
    type: 'select',
    prop: 'corporationId',
    label: '归属公司',
    keyName: 'id',
    labelName: 'name',
    async option() {
      const data = await getCorporationPageApi({ searchAll: true })
      return data.records
    }
  },
  {
    type: 'slot',
    prop: 'deptId',
    label: '归属部门'
  },
  {
    type: 'select',
    prop: 'type',
    label: '请款类型',
    dict: 'payment_requests_type'
  },
  {
    type: 'select',
    prop: 'payType',
    label: '付款方式',
    dict: 'pay_type'
  },
  {
    type: 'select',
    prop: 'paymentStatus',
    label: '放款状态',
    option: [
      {
        key: 0,
        label: '未打款'
      },
      {
        key: 1,
        label: '部分打款'
      },
      {
        key: 2,
        label: '已打款'
      }
    ]
  }
]

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 = '新增'
    //   }
  },
  {
    text: '导出',
    icon: 'Download',
    type: 'primary',
    click() {
      remitExcelExportApi(queryData.value).then(() => {
        ElMessage.success('导出成功')
      })
    }
  }
]

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: 'paymentStatus',
    label: '放款状态',
    formatter(row) {
      switch (row.paymentStatus) {
        case 0:
          return '未打款'
        case 1:
          return '部分打款'
        case 2:
          return '已打款'
      }
    }
  },
  {
    width: 250,
    handleConfig: [
      {
        text: '打款',
        if: (row) => row.paymentStatus != 2,
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '打款'
          disabled.value = false
          getDetailApi({ id: row.id }).then((resp: StrAnyObj) => {
            detailData.value = resp
            formData.value.capitalAccountId = resp.capitalAccountId
            formData.value.amount = resp.totalAmount - resp.remitAmount
            formData.value.remark = resp.useRemark
            formData.value.paymentRequestsId = resp.id
          })
        }
      },
      {
        common: 'detail',
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '详情'
          disabled.value = true
          getDetailApi({ id: row.id }).then((resp: StrAnyObj) => {
            detailData.value = resp
          })
        }
      },
      {
        text: '打印',
        click(row) {
          rowData.value = row
          dialogPrint.value = true
        }
      }
    ]
  }
]

const detailConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'totalAmount',
    label: '请款金额',
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    prop: 'remitAmount',
    label: '已打款金额',
    placeholder: '',
    disabled: true
  },
  {
    type: 'select',
    prop: 'payType',
    label: '付款方式',
    dict: 'pay_type',
    placeholder: '',
    disabled: true
  },
  {
    type: 'select',
    prop: 'capitalAccountId',
    label: '付款账户',
    keyName: 'id',
    labelName: 'accountAlias',
    placeholder: '',
    async option() {
      const data = await getCapitalAccountPageApi({ searchAll: true })
      return data.records
    },
    disabled: true
  },
  {
    type: 'input',
    prop: 'accountName',
    label: '户名',
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    prop: 'account',
    label: '银行账号',
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    prop: 'depositBank',
    label: '开户银行',
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    prop: 'correspondentNumber',
    label: '联行号/SWIFT Code',
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    itemType: 'textarea',
    prop: 'useRemark',
    label: '用款说明',
    rows: 3,
    span: 24,
    placeholder: '',
    disabled: true
  },
  {
    type: 'upload',
    prop: 'atts',
    label: '附件',
    span: 24
  }
]

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: 'inputNumber',
    prop: 'amount',
    label: '打款金额',
    min: 0.01,
    precision: 2,
    rule: [{ required: true, message: '打款金额不能为空', trigger: 'blur' }]
  },
  {
    type: 'datePicker',
    prop: 'remitTime',
    label: '打款时间',
    datePickerType: 'datetime',
    format: 'YYYY-MM-DD 00:00:00',
    valueFormat: 'YYYY-MM-DD 00:00:00',
    rule: [{ required: true, message: '打款时间不能为空', trigger: ['blur', 'change'] }]
  },
  {
    type: 'input',
    itemType: 'textarea',
    prop: 'remark',
    label: '摘要',
    rows: 5,
    span: 24
  },
  {
    type: 'upload',
    prop: 'atts',
    label: '附件',
    span: 24
  }
]

onMounted(() => {
  getPage()
  selectDeptIdRef.value?.load()
})

function getPage() {
  getRemitPageApi(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(() => {
    remitApi(formData.value).then(() => {
      dialogVisible.value = false
      ElMessage.success('打款成功')
      getPage()
    })
  })
}

function formClosed() {
  formRef.value?.resetFields()
}
const printObj = ref({
  id: 'pdfDom',
  popTitle: '',
  extraCss:
    'https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css',
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'
})
const clickDownload = () => {
  getPdf('请款PDF文件')
}
</script>

<template>
  <div>
    <el-card v-if="showQuery">
      <a-form ref="queryRef" v-model="queryData" :config="queryConfig" :span="6">
        <template #deptId>
          <dept-tree-select ref="selectDeptIdRef" v-model="queryData.deptId" />
        </template>
      </a-form>
    </el-card>

    <a-table
      :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-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogTitle"
      :footer="!disabled"
      @submit="formSubmit"
      @closed="formClosed"
      width="1400px"
    >
      <div v-if="disabled">
        <a-form v-model="detailData" :config="detailConfig" :span="12" disabled> </a-form>
      </div>

      <el-card v-if="!disabled" header="请款信息">
        <a-form v-model="detailData" :config="detailConfig" :span="12" disabled></a-form>
      </el-card>

      <el-card v-if="!disabled" header="打款信息" style="margin-top: 10px">
        <a-form ref="formRef" v-model="formData" :config="formConfig" :span="12"> </a-form>
      </el-card>
    </a-dialog>

    <a-dialog
      :footer="false"
      v-if="dialogPrint"
      v-model="dialogPrint"
      title="打印"
      width="840px"
      height="200px"
    >
      <MoneyPDF :rowData="rowData"></MoneyPDF>
      <template #footer>
        <div>
          <el-button @click="dialogPrint = false" size="large">取消</el-button>
          <el-button type="primary" v-print="printObj" size="large">打印</el-button>
          <el-button type="primary" @click="clickDownload()" size="large">下载PDF</el-button>
        </div>
      </template>
    </a-dialog>
  </div>
</template>
