<template>
  <a-row :gutter="8" :wrap="false">
    <a-col flex="auto">
      <a-card>
        <a-table :columns="columns" :data-source="listData" bordered="true" :loading="loading"
          :pagination="paginationState" :scroll="{ x: 'max-content' }" @change="onTableChange">
          <template #bodyCell="{ index, column, record }">
            <template v-if="'direction' === column.key">
              <span>{{ record.direction === 'Out' ? '迁出' : '迁入' }}</span>
            </template>
            <template v-if="'directionType' === column.key">
              <span>{{ record.directionType === 'Transfer' ? '转出' : '去世' }}</span>
            </template>
            <template v-if="'passWayAt' === column.key">
              <span>{{dayjs(record.passWayAt).format('YYYY-MM-DD')}}</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-col>
  </a-row>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { ref, defineProps } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import { useI18n } from 'vue-i18n'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { useForm, useModal } from '@/hooks'
const { formRecord, formData: contactForm, formRef, formRules, resetForm } = useForm()
import dayjs from 'dayjs'
defineOptions({
  name: 'allocation',
})
const props = defineProps({
  formData: {
    type: Object,
    default: () => ({})
  }
});
const areaCascaderRef=ref()
const actionType = ref('')
const visibleOpen = ref(false)
const dicsStore = useDicsStore()
const columns = [
  {
    title: '迁出/迁入',
    dataIndex: 'direction',
    key: 'direction',
    align: 'center',
    width: 120,
  },

  // --- 联系方式 ---
  {
    title: '迁出类型',
    dataIndex: 'directionType',
    key: 'directionType',
    align: 'center',
    width: 130,
  },
  {
    title: '去世时间',
    dataIndex: 'passWayAt',
    key: 'passWayAt',
    align: 'center',
    width: 130,
  },
  {
    title: '转出原因',
    dataIndex: 'reason',
    key: 'reason',
    align: 'center',
    width: 80,
  }
];
const { t } = useI18n() // 解构出t方法
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } = usePagination()
const editDialogRef = ref()
getPageList()

async function getPageList() {
  try {
    const { pageSize, current } = paginationState
    const { success, data, total } = await apis.contacts
      .getInOutList({
        pageSize,
        current: current,
        customerId: props.formData.customerId
      })
      .catch(() => {
        throw new Error()
      })

    if (config('http.code.success') === success) {
      listData.value = data
      paginationState.total = total || 0
    }
  } catch (error) {

  }
}

/**
 * 删除
 */
function handleDelete({ id }) {
  Modal.confirm({
    title: t('pages.system.user.delTip'),
    content: t('button.confirm'),
    okText: t('button.confirm'),
    onOk: () => {
      return new Promise((resolve, reject) => {
        ; (async () => {
          try {
            const { success } = await apis.contacts.delItem(id).catch(() => {
              throw new Error()
            })
            if (config('http.code.success') === success) {
              resolve()
              message.success(t('component.message.success.delete'))
              await getPageList()
            }
          } catch (error) {
            reject()
          }
        })()
      })
    },
  })
}
const handleOk = () => {
  console.log('contactForm.value', contactForm.value)
  formRef.value.validate().then(async () => {
    const params = {
      ...contactForm.value,
      customerId: props.formData.customerId
    }
    if (actionType.value === 'create') {
      const { success } = await apis.contacts.createItem(params).catch(() => {
        // throw new Error()
      })
      if (config('http.code.success') === success) {
        message.success('添加成功')
        visibleOpen.value = false
        resetForm()
        await getPageList()
      }
    }else{
      const { success } = await apis.contacts.updateItem(params).catch(() => {
        // throw new Error()
      })
      if (config('http.code.success') === success) {
        message.success('编辑成功')
        visibleOpen.value = false
        resetForm()
        await getPageList()
      }
    }


  }).catch((err) => {
    console.log('err', err)
    // message.error(err)
  })
}
const showModal = () => {
  contactForm.value.gender = '1';
  contactForm.value.isEmergency = '2';
  actionType.value = 'create';
  visibleOpen.value = true;
};
function onAreaChange(value, labels) {
  contactForm.value.areaCodes = [...value]
  console.log(contactForm.value.areaCodes)
  contactForm.value.areaLabels = [...labels]
}
const handleEdit = (record) => {
  actionType.value = 'edit';
  contactForm.value = Object.assign({}, record)
  visibleOpen.value = true
}
/**
 * 分页
 */
function onTableChange({ current, pageSize }) {
  paginationState.current = current
  paginationState.pageSize = pageSize
  getPageList()
}

/**
 * 搜索
 */
function handleSearch() {
  resetPagination()
  getPageList()
}
/**
 * 重置
 */
function handleResetSearch() {
  searchFormData.value = {}
  resetPagination()
  getPageList()
}
/**
 * 编辑完成
 */
async function onOk() {
  await getPageList()
}

</script>

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