<!-- 发票管理 -->
<template>
  <v-card class="card-box pa-5">
    <CtTable
      :items="items"
      :headers="headers"
      :loading="false"
      :elevation="0"
      :isTools="true"
      :showPage="true"
      :total="total"
      :page-info="query"
      @pageHandleChange="handleChangePage"
      @add="handleAdd"
      @edit="handleEdit"
      @del="handleDelete"
    >
    </CtTable>
  </v-card>

  <CtDialog :visible="show" :widthType="3" titleClass="text-h6" :title="editId ? '编辑发票抬头' : '新增发票抬头'" @close="handleClose" @submit="handleSubmit">
    <CtForm ref="CtFormRef" :items="formItems"></CtForm>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'invoiceHeader'})
import { ref } from 'vue'
import { getEnterpriseBusiness } from '@/api/enterprise'
import { getInvoiceTitlePage, createInvoiceTitle, updateInvoiceTitle, deleteInvoiceTitle } from '@/api/recruit/enterprise/member/invoice'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import { useI18n } from '@/hooks/web/useI18n'
import { checkPhone, checkEmail, checkUSCI } from '@/utils/validate'

const { t } = useI18n()
const total = ref(0)
const items = ref([])
const headers = [
  { title: '抬头类型', key: 'category', sortable: false, value: item => item.category === 0 ? '个人' : '企业' },
  { title: '发票类型', key: 'type', sortable: false, value: item => item.type === 0 ? '增值税普通发票' : '增值税专用发票' },
  { title: '发票抬头', key: 'title', sortable: false },
  { title: '税号', key: 'code', sortable: false },
  { title: '联系邮箱', key: 'email', sortable: false },
  { title: '联系电话', key: 'phone', sortable: false },
  { title: '开户银行', key: 'enterpriseBankTitle', sortable: false },
  { title: '银行账号', key: 'enterpriseBankNo', sortable: false },
  { title: '操作', key: 'actions', sortable: false }
]

const query = ref({
  pageNo: 1,
  pageSize: 10
})
const CtFormRef = ref()
const show = ref(false)
const editId = ref(null)

// 抬头类型
const keys = ['enterpriseBankTitle', 'enterpriseBankNo']
const handleChangeCategory = (e) => {
  const type = formItems.value.options.find(item => item.key === 'type').value
  const code = formItems.value.options.find(item => item.key === 'code')
  code.hide = e ? false : true
  if (e) setEntBusinessInfo()
  else setEntPersonBaseInfo()
  const title = formItems.value.options.find(item => item.key === 'title')
  if (title) title.disabled = e ? true : false
  keys.forEach(k => {
    const result = formItems.value.options.find(item => item.key === k)
    result.label = (e && type) || (!e && type) ? `${result.defaultLabel} *` : result.defaultLabel
    result.rules = (e && type) || (!e && type) ? [v => !!v || `请输入${result.defaultLabel}`] : []
  })
}

const handleChangeType = (e) => {
  keys.forEach(k => {
    const result = formItems.value.options.find(item => item.key === k)
    result.label = e ? `${result.defaultLabel} *` : result.defaultLabel
    result.rules = e ? [v => !!v || `请输入${result.defaultLabel}`] : []
  })
}

const formItems = ref({
  options: [
    {
      type: 'ifRadio',
      key: 'category',
      value: 0,
      label: '抬头类型 *',
      width: 90,
      items: [
        { label: '个人', value: 0 },
        { label: '企业', value: 1 }
      ],
      change: handleChangeCategory
    },
    {
      type: 'ifRadio',
      key: 'type',
      value: 0,
      label: '发票类型 *',
      width: 90,
      items: [
        { label: '增值税普通发票', value: 0 },
        { label: '增值税专用发票', value: 1 }
      ],
      change: handleChangeType
    },
    {
      type: 'text',
      key: 'title',
      value: '',
      label: '发票抬头 *',
      rules: [v => !!v || '请输入发票抬头'],
    },
    {
      type: 'text',
      key: 'code',
      value: '',
      label: '税号 *',
      hide: true,
      outlined: true,
      rules: [
        value => {
          if (value) return true
          return '请填写税号'
        },
        value => {
          if (checkUSCI(value)) return true
          return '请填写正确的税号'
        }
      ]
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: null,
      label: '联系电话',
      outlined: true
    },
    {
      type: 'text',
      key: 'email',
      value: '',
      label: '联系邮箱 *',
      rules: [
        value => {
          if (value) return true
          return '请输入联系邮箱'
        },
        value => {
          if (checkEmail(value)) return true
          return '请输入正确的电子邮箱'
        }
      ]
    },
    {
      type: 'text',
      key: 'enterpriseBankTitle',
      value: null,
      label: '开户银行',
      defaultLabel: '开户银行',
      outlined: true
    },
    {
      type: 'number',
      key: 'enterpriseBankNo',
      value: null,
      label: '银行账号',
      defaultLabel: '银行账号',
      outlined: true
    }
  ]
})

// 获取列表
const getList =async () => {
  const res = await getInvoiceTitlePage(query.value)
  items.value = res.list
  total.value = res.total
}
getList()

const handleChangePage = (e) => {
  query.value.pageNo = e
  getList()
}

// // // 根据企业名称模糊搜索企业营业执照信息-填充发票抬头
// const getEntBusinessInfoByName = async (name) => {
//   if (!name) return
//   const data = await getEnterpriseBusinessByName({ name })
//   if (!data?.length || !Object.keys(data[0]).length) return
//   const info = {
//     ...data[0],
//     title: data[0].name,
//   }
//   formItems.value.options.forEach(e => e.value = info[e.key])
// }


// 获取企业工商信息
const business = ref({})
const getEnterpriseBusinessInfo = async () => {
  const data = await getEnterpriseBusiness()
  if (!data || !Object.keys(data).length) return
  data.category = 1
  data.title = data.name
  business.value = data
}
getEnterpriseBusinessInfo()

// 填充企业信息
const setEntBusinessInfo = () => {
  const info = business.value
  formItems.value.options.forEach(e => {
    if (e.key === 'type') return
    if ((info[e.key] || info[e.key] === 0) && e.key !== 'type') e.value = info[e.key]
    else e.value = null
  })
}

// 填充个人信息
const setEntPersonBaseInfo = () => {
  const info = JSON.parse(localStorage.getItem('entBaseInfo')) || {}
  info.title = info.name
  info.category = 0
  formItems.value.options.forEach(e => {
    if (e.key === 'type') return
    if ((info[e.key] || info[e.key] === 0) && e.key !== 'type') e.value = info[e.key]
    else e.value = null
  })
}


// 新增
const handleAdd = () => {
  // 初始化表单
  handleChangeCategory(0)
  handleChangeType(0)
  // 赋值
  setEntPersonBaseInfo()
  show.value = true
  editId.value = null
}

// 编辑
const handleEdit = (item) => {
  editId.value = item.id
  formItems.value.options.forEach(e => {
    e.value = item[e.key]
    if (e.key === 'category' || e.key === 'type') {
      e.value = item[e.key] || 0
      e.change(e.value)
    }
  })
  show.value = true
}

// 删除
const handleDelete = ({ id }) => {
  Confirm(t('common.confirmTitle'), '是否确定删除此抬头信息？').then(async () => {
    await deleteInvoiceTitle(id)
    Snackbar.success(t('common.delMsg'))
    getList()
  })
}

// 新增、编辑提交
const handleClose = () => {
  show.value = false
  editId.value = null
}

const { userId } = JSON.parse(localStorage.getItem('accountInfo'))
const handleSubmit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid || !userId) return
  const obj = {
    userId
  }
  formItems.value.options.forEach(item => {
    obj[item.key] = item.value
  })
  if (obj.type === undefined || obj.type === null || obj.type === '') return Snackbar.warning('请选择发票类型')
  if (obj.phone && !checkPhone(obj.phone)) return Snackbar.warning(t('login.correctPhoneNumber'))
  if (editId.value) obj.id = editId.value
  const api = editId.value ? updateInvoiceTitle : createInvoiceTitle
  await api(obj)
  Snackbar.success(editId.value ? t('common.editSuccessMsg') : t('common.addMsg'))
  handleClose()
  getList()
}
</script>

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