<template>
  <div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="name"
          name="name"
          label="名称"
          placeholder="请输入名称"
        />
        <van-field
          v-model="logDay"
          name="logDay"
          type="number"
          label="每月日期"
          placeholder="请输入每月日期"
        />
        <van-field
          v-model="totalFee"
          name="totalFee"
          type="number"
          label="数字"
          placeholder="请输入消费金额"
        />

        <div class="types-box">
          <van-field
            v-model="typeStr"
            label="类型"
            name="typeStr"
            placeholder="请输入类型名称"
          />
          <div class="types-scroll-box" @click.stop>
            <van-tag
              type="primary"
              @click="setTypes(item)"
              mark
              v-for="item in typeList"
              :key="`tag${item.name}`"
              >{{ item.name }}</van-tag
            >
          </div>
        </div>
        <br />
        <van-field name="uploader" label="文件上传">
          <template #input>
            <van-uploader
              :model-value="files"
              multiple
              :max-count="5"
              :after-read="afterRead"
              :before-delete="filesDelete"
            />
          </template>
        </van-field>
        <van-field
          v-model="newTime"
          is-link
          readonly
          name="newTime"
          label="时间区间"
          placeholder="点击选择时间"
          @click="showCalendar = true"
        />
        <van-field
          v-model="remark"
          rows="2"
          autosize
          name="remark"
          label="留言"
          type="textarea"
          maxlength="50"
          placeholder="请输入留言"
          show-word-limit
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <van-calendar
      type="range"
      :min-date="new Date(2024, 0, 1)"
      switch-mode="year-month"
      v-model:show="showCalendar"
      @confirm="onConfirm"
      :default-date="defaultDate"
    />
    <van-number-keyboard
      v-model="totalFee"
      :show="showKeyboard"
      :maxlength="6"
      @blur="showKeyboard = false"
    />
  </div>
</template>

<script setup>
import { watch, ref, onMounted, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import dayjs from 'dayjs'
import {
  uploadFile,
  addMoreRecordInfo,
  editMoreRecordInfo,
  getMoreRecordInfo,
  getAllType,
  getRecordInfo,
  putRecordInfo
} from '@/api/api'
import { useCommonStore } from '@/store/common'
const commonStore = useCommonStore()

const router = useRouter()
const route = useRoute()

const files = ref([])
const totalFee = ref()
const showKeyboard = ref(false)
const remark = ref('')
const name = ref('')
const typeStr = ref('')
const logDay = ref(1)
const typeList = ref([])
const defaultDate = ref(null)

const afterRead = async (file) => {
  // 将文件上传至服务器
  let formData = new FormData()
  formData.append('sampleFile', file.file)
  const res = await uploadFile(formData)
  files.value.push({
    // url: window.origin + `/api/v1/files/${res.file_id}`,
    url: file.objectUrl,
    file_id: res.data.file_id,
    isImage: true
  })
}

const newTime = ref('')
const showCalendar = ref(false)

const onConfirm = (values) => {
  const [start, end] = values
  newTime.value = `${dayjs(start).format('YYYY-MM-DD')}至${dayjs(end).format(
    'YYYY-MM-DD'
  )}`
  showCalendar.value = false
}
const filesDelete = (file) => {
  files.value = files.value.filter((elm) => elm.url !== file.url)
}

onMounted(() => {
  commonStore.initBook()
  setTimeout(() => {
    getAllTypeByUser()
    if (route.params.more_id) {
      editPageInit()
    }
  }, 300)
})

async function getAllTypeByUser() {
  const res = await getAllType(commonStore.bookInfo.id)
  typeList.value = res.data
}

const onSubmit = async (values) => {
  if (route.params.more_id) {
    onEditSubmit(values)
    return
  }
  const [start_time, end_time] = `${values.newTime}`.split('至')
  await addMoreRecordInfo({
    book_id: commonStore.bookInfo.id,
    start_time,
    end_time,
    total_fee: values.totalFee,
    log_day: values.logDay,
    type: values.typeStr,
    remark: values.remark,
    name: values.name,
    files: files.value.map((elm) => elm.file_id)
  })
  router.back()
}

const onEditSubmit = async (values) => {
  const [start_time, end_time] = `${values.newTime}`.split('至')
  await editMoreRecordInfo(route.params.more_id, {
    book_id: commonStore.bookInfo.id,
    start_time,
    end_time,
    total_fee: values.totalFee,
    log_day: values.logDay,
    type: values.typeStr,
    remark: values.remark,
    name: values.name,
    files: files.value.map((elm) => elm.file_id)
  })

  router.back()
}

function setTypes(tag) {
  typeStr.value = tag.name
}

async function editPageInit() {
  const res = await getMoreRecordInfo(route.params.more_id)
  console.log(106, res)

  totalFee.value = Number(res.data.total_fee)
  typeStr.value = res.data.type
  remark.value = res.data.remark
  name.value = res.data.name
  logDay.value = res.data.log_day

  defaultDate.value = [
    dayjs(res.data.start_time).toDate(),
    dayjs(res.data.end_time).toDate()
  ]
  newTime.value = `${dayjs(res.data.start_time).format('YYYY-MM-DD')}至${dayjs(
    res.data.end_time
  ).format('YYYY-MM-DD')}`

  if (res.data?.files?.length > 0) {
    files.value = res.data?.files.map((imgStr) => ({
      url: imgStr,
      file_id: imgStr.replace(/.*api_files_/, ''),
      isImage: true
    }))
  }
}
</script>

<style lang="scss" scoped>
.types-box {
  .types-scroll-box {
    padding-left: 100px;
    text-align: left;
    padding-top: 10px;
    padding-bottom: 10px;
    max-height: 60px;
    overflow-x: scroll;
    > * {
      margin-bottom: 10px;
      margin-right: 10px;
    }
    // display: flex;
    // overflow-y: scroll;
    // flex-wrap: nowrap;
    // margin-left: 24px;
  }
}
</style>
