<!-- 发票管理 -->
<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="handle"
      @edit="handle"
      @del="handleDelete"
    >
    </CtTable>
  </v-card>

  <CtDialog :visible="show" :widthType="3" titleClass="text-h6" :title="editId ? '编辑发票抬头' : '新增发票抬头'" @close="handleClose" @submit="handleSubmit">
    <CtForm ref="CtFormRef" :items="formItems">
      <template #certificationTip>
        <div style="color:var(--color-999); font-size: 13px;margin-left: 108px;" class="mb-5">
          <v-icon color="primary" size="20" class="mr-1">mdi-check-circle-outline</v-icon>
          <span>企业实名认证账号，可开具普票和企业专票</span>
          <span>
            <span>查看</span>
          </span>
        </div>
      </template>
      <template #invoiceHeaderTip v-if="invoiceHeaderTip">
        <div style="color:var(--color-999); font-size: 13px;" class="d-flex mr-10">
          <v-icon color="primary" class="mr-1 mt-1">mdi-shield-check</v-icon>
          <div>相关法律规定，专票抬头与实名认证主体必须一致, 若需开具其他主体专票，请变更企业实名认证</div>
        </div>
      </template>
    </CtForm>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'invoiceHeader'})
import { nextTick, 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 { checkUSCI, checkBankNo, checkBankName, checkAddress } 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: 'enterpriseBankTitle', sortable: false },
  { title: '基本银行账号', key: 'enterpriseBankNo', sortable: false },
  { title: '企业注册地址', key: 'enterpriseAddress', sortable: false },
  { title: '企业注册电话', key: 'enterprisePhone', 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 editInfo = ref(null)

const personKeys = ['category', 'type', 'title']
const enterpriseKeys = ['category', 'type', 'certificationTip', 'invoiceHeaderTip', 'title', 'code', 'enterpriseBankTitle', 'enterpriseBankNo', 'enterpriseAddress', 'enterprisePhone']
// 抬头类型
const handleChangeCategory = (categoryType = 0) => { // 0: 个人, 1: 企业
  formItems.value.options = []
  const keyArr = categoryType ? enterpriseKeys : personKeys
  const arr = keyArr.map(key => {
    const optionsItem = { ...optionsBase[key] }
    if (categoryType === 0) { // 个人
      invoiceHeaderTip.value = false
      if (optionsItem.key === 'type') optionsItem.items = [optionsItem.items[0]]
      if (optionsItem.key === 'title') {
        optionsItem.value = '个人'
        optionsItem.disabled = true
      }
    } else { // 企业
      if (optionsItem.key === 'category') optionsItem.value = 1
      if (editInfo.value) {
        if (editInfo.value[key]) optionsItem.value = editInfo.value[key]
      } else {
        if (business.value[key]) optionsItem.value = business.value[key]
      }
    }
    return optionsItem
  })
  nextTick(() => {
    formItems.value.options = arr
  })
}

const invoiceHeaderTip = ref(false)
const handleChangeType = (isVerified) => {
  invoiceHeaderTip.value = isVerified
  formItems.value.options.forEach(e => {
    if (business.value[e.key]) e.value = business.value[e.key] // business.value
    if (e.key === 'title') e.disabled = isVerified
    if (e.rulesBaseLabel) {
      e.label = isVerified ? `${e.rulesBaseLabel} *` : e.rulesBaseLabel
      e.rules = isVerified ? [v => !!v || `请输入${e.rulesBaseLabel}`, ...e.rules] : []
    }
  })
}

const optionsBase = {
  category: {
    type: 'ifRadio',
    key: 'category',
    value: 0,
    label: '抬头类型 *',
    width: 90,
    items: [
      { label: '个人', value: 0 },
      { label: '企业', value: 1 }
    ],
    change: handleChangeCategory
  },
  type: {
    type: 'ifRadio',
    key: 'type',
    value: 0,
    label: '发票类型 *',
    width: 90,
    hideDetails: true,
    items: [
      { label: '增值税普通发票', value: 0 },
      { label: '增值税专用发票', value: 1 }
    ],
    change: handleChangeType
  },
  title: {
    type: 'text',
    key: 'title',
    value: '',
    label: '发票抬头 *',
    rules: [v => !!v || '请输入发票抬头'],
  },
  code: {
    type: 'text',
    key: 'code',
    value: '',
    label: '纳税人识别号 *',
    outlined: true,
    rules: [
      value => {
        if (value && checkUSCI(value)) return true
        return '纳税人识别号'
      }
    ]
  },
  enterpriseBankTitle:  {
    type: 'text',
    key: 'enterpriseBankTitle',
    value: null,
    label: '基本开户银行',
    placeholder: '请填写开户许可证上的开户银行',
    rulesBaseLabel: '基本开户银行',
    outlined: true,
    rules: [
      value => {
        if (!value || (value && checkBankName(value))) return true
        return '请输入正确的开户银行'
      }
    ]
  },
  enterpriseBankNo: {
    type: 'number',
    key: 'enterpriseBankNo',
    value: null,
    label: '基本银行账号',
    placeholder: '请填写开户许可证上的银行账号',
    rulesBaseLabel: '基本银行账号',
    outlined: true,
    rules: [
      value => {
        if (!value || (value && checkBankNo(value))) return true
        return '请输入正确的银行账号'
      }
    ]
  },
  enterpriseAddress:  {
    type: 'text',
    key: 'enterpriseAddress',
    value: null,
    label: '企业注册地址',
    placeholder: '请填写开户许可证上的企业注册地址',
    rulesBaseLabel: '企业注册地址',
    outlined: true,
    rules: [
      value => {
        if (!value || (value && checkAddress(value))) return true
        return '请输入正确的注册地址'
      }
    ]
  },
  enterprisePhone: {
    type: 'phoneNumber',
    key: 'enterprisePhone',
    value: null,
    label: '企业注册电话',
    placeholder: '请填写开户许可证上的企业注册电话',
    rulesBaseLabel: '企业注册电话',
    outlined: true,
  },
  certificationTip: {
    slotName: 'certificationTip',
  },
  invoiceHeaderTip: {
    slotName: 'invoiceHeaderTip',
  },
}
const formItems = ref({ options: [] })

// 获取列表
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 business = ref({})
const getEnterpriseBusinessInfo = async () => {
  const data = await getEnterpriseBusiness()
  if (!data || !Object.keys(data).length) return
  // console.log(1, 'business', data)
  business.value = {
    title: data.name,
    code: data.code,
    enterpriseAddress: data.address,
  }
}
getEnterpriseBusinessInfo()

// 新增 编辑
const handle = (item) => {
  editId.value = item?.id || null
  editInfo.value = item || null
  handleChangeCategory(item?.category || 0)
  handleChangeType(item?.type || 0)
  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 (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>
