<template>
  <n-drawer
    class="top0"
    to="#main"
    :show="show"
    width="5.2rem"
    :mask-closable="false"
  >
    <n-drawer-content>
      <template #header>
        <div class="head">
          <p>{{ mode ? basicData.name : '新增活动' }}</p>
          <n-space>
            <n-button size="small" @click="closeDrawer(false)">取消</n-button>
            <template v-if="mode === 'view'">
              <n-button type="error" size="small" @click="mode = 'modify'">
                编辑
              </n-button>
              <n-button type="primary" size="small" @click="submit">
                <template #icon>
                  <n-icon size=".12rem">
                    <svg-icon :data="exportIcon" original />
                  </n-icon>
                </template>
                导出
              </n-button>
            </template>
            <n-button v-else type="primary" size="small" @click="submit">
              完成
            </n-button>
          </n-space>
        </div>
      </template>
      <div class="content">
        <div>
          <p class="title">基本信息</p>
          <n-form
            ref="basicRef"
            :model="basicData"
            :rules="rules"
            size="small"
            label-placement="top"
          >
            <n-grid :cols="24" :x-gap="12">
              <n-form-item-gi :span="12" label="活动名称" path="name">
                <p v-if="mode === 'view'">{{ basicData.name }}</p>
                <n-input v-else v-model:value="basicData.name" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="标签类别" path="type">
                <p v-if="mode === 'view'">
                  {{
                    typeOptions.find((e) => e.value === basicData.type)?.label
                  }}
                </p>
                <n-select
                  v-else
                  v-model:value="basicData.type"
                  :options="typeOptions"
                />
              </n-form-item-gi>
              <n-form-item-gi
                :span="24"
                label="党组织名称（下拉或输入关键字选择）"
                path="orgName"
              >
                <p v-if="mode === 'view'">
                  {{
                    orgOptions.find((e) => e.value === basicData.orgName)?.label
                  }}
                </p>
                <n-select
                  v-else
                  v-model:value="basicData.orgName"
                  :options="orgOptions"
                  filterable
                />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="活动日期" path="date">
                <n-date-picker
                  v-model:value="basicData.date"
                  :disabled="mode === 'view'"
                  style="width: 100%"
                />
              </n-form-item-gi>
              <n-form-item-gi
                :span="24"
                label="活动地址（请具体填写，如“XX区XX路XX号XX中心”）"
                path="address"
              >
                <p v-if="mode === 'view'">{{ basicData.address }}</p>
                <n-input v-else v-model:value="basicData.address" />
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </div>
        <div>
          <p class="title">人员参与情况</p>
          <n-form
            ref="memberRef"
            :model="memberData"
            :rules="rules"
            size="small"
            label-placement="top"
          >
            <n-grid :cols="24" :x-gap="12">
              <n-form-item-gi :span="12" label="实际参与人数" path="count">
                <p v-if="mode === 'view'">{{ memberData.count }}</p>
                <n-input-number
                  v-else
                  v-model:value="memberData.count"
                  size="small"
                  :show-button="false"
                  :min="0"
                >
                  <template #suffix>人</template>
                </n-input-number>
              </n-form-item-gi>
              <n-form-item-gi
                :span="12"
                label="不计入参与活动党员人数"
                path="excludeCount"
              >
                <p v-if="mode === 'view'">{{ memberData.excludeCount }}</p>
                <n-input-number
                  v-else
                  v-model:value="memberData.excludeCount"
                  size="small"
                  :show-button="false"
                  :min="0"
                >
                  <template #suffix>人</template>
                </n-input-number>
              </n-form-item-gi>
              <n-form-item-gi
                :span="24"
                label="电子表格或签到照片（大小20M以内）"
                path="fileType"
              >
                <p v-if="mode === 'view'">
                  {{
                    fileOptions.find((e) => e.value === memberData.fileType)
                      ?.label
                  }}
                </p>
                <n-select
                  v-else
                  v-model:value="memberData.fileType"
                  :options="fileOptions"
                  placeholder="请选择上传类型"
                />
              </n-form-item-gi>
              <n-form-item-gi v-if="memberData.fileType === 'file'" :span="24">
                <n-upload
                  style="width: 100%"
                  action="http://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  accept=".docx,.doc,.xlsx,.xls,.csv,.txt"
                >
                  <n-button> 上传附件 </n-button>
                </n-upload>
              </n-form-item-gi>
              <n-form-item-gi v-if="memberData.fileType === 'photo'" :span="24">
                <n-upload
                  style="width: 100%"
                  action="http://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  :default-file-list="previewFileList"
                  accept="image/jpg,image/jpeg,image/png,image/img"
                  list-type="image-card"
                  @preview="handlePreview"
                >
                  点击上传
                </n-upload>
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </div>
        <div>
          <p class="title">活动详情</p>
          <n-form
            ref="detailRef"
            :model="detailData"
            :rules="rules"
            size="small"
            label-placement="top"
          >
            <n-grid :cols="24" :x-gap="12">
              <n-form-item-gi
                :span="24"
                label="活动内容描述或照片（大小20M以内）"
                path="fileType"
              >
                <p v-if="mode === 'view'">
                  {{
                    fileOptions.find((e) => e.value === memberData.fileType)
                      ?.label
                  }}
                </p>
                <n-select
                  v-else
                  v-model:value="detailData.fileType"
                  :options="fileOptions"
                  placeholder="请选择上传类型"
                />
              </n-form-item-gi>
              <n-form-item-gi v-if="detailData.fileType === 'file'" :span="24">
                <n-upload
                  style="width: 100%"
                  action="http://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  accept=".docx,.doc,.xlsx,.xls,.csv,.txt"
                >
                  <n-button> 上传附件 </n-button>
                </n-upload>
              </n-form-item-gi>
              <n-form-item-gi v-if="detailData.fileType === 'photo'" :span="24">
                <n-upload
                  style="width: 100%"
                  action="http://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  :default-file-list="previewFileList"
                  accept="image/jpg,image/jpeg,image/png,image/img"
                  list-type="image-card"
                  @preview="handlePreview"
                >
                  点击上传
                </n-upload>
              </n-form-item-gi>
              <n-form-item-gi
                :span="24"
                label="活动照片（格式为jpg、jpeg、png、img， 大小20M以内）"
                path="photo"
              >
                <n-upload
                  style="width: 100%"
                  action="http://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  :default-file-list="previewFileList"
                  accept="image/jpg,image/jpeg,image/png,image/img"
                  list-type="image-card"
                  @preview="handlePreview"
                >
                  点击上传
                </n-upload>
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </div>
      </div>
    </n-drawer-content>
  </n-drawer>
  <n-modal
    v-model:show="showPhoto"
    preset="card"
    style="width: 30%"
    title="照片预览"
  >
    <img :src="previewImageUrl" style="width: 100%" />
  </n-modal>
</template>

<script lang="ts" setup>
import store from '@/store'
import { computed, onMounted, PropType, ref, watch } from 'vue'
import { NForm } from 'naive-ui'
import exportIcon from '@images/export.svg'
import { activity } from '@/util/tags'
import { useFetchOrg } from '@/hooks/useFetch'

const props = defineProps({
  data: {
    type: Object as PropType<{ [key: string]: any }>,
    default: null,
  },
})
const mode = ref<string | null>(null)

const orgOptions = ref([])
onMounted(async () => {
  orgOptions.value = (
    await useFetchOrg({
      a: 'id,count',
      keys: '党组织名称',
    })
  )?.map((item: any) => ({
    label: item['党组织名称'],
    value: item['党组织名称'],
  }))
})

const show = computed(() => store.state.showNewActivityDrawer)
const closeDrawer = () => store.commit('SET_NEW_ACTIVITY_DRAWER', false)

const typeOptions = computed(() => {
  return activity.map((item) => ({
    label: item.name,
    value: item.name,
  }))
})
const fileOptions = [
  { label: '电子表格（docx、doc、xlsx、xls、csv、txt）', value: 'file' },
  { label: '描述照片（jpg、jpeg、png、img）', value: 'photo' },
]

const basicRef = ref<typeof NForm | null>(null)
const memberRef = ref<typeof NForm | null>(null)
const detailRef = ref<typeof NForm | null>(null)
const basicData = ref({})
const memberData = ref({})
const detailData = ref({})

watch(
  () => props.data,
  (data) => {
    if (!data) {
      basicData.value = {}
      memberData.value = {}
      detailData.value = {}
      return
    }
    basicData.value = {
      name: data.name,
      type: data.type,
      orgName: data.orgName,
      date: data.date,
      address: data.address,
    }
    memberData.value = {
      count: data.count,
      excludeCount: data.excludeCount,
      fileType: data.fileType,
    }
    detailData.value = {
      fileType: data.fileType,
    }
    mode.value = data._mode || null
  },
  { immediate: true },
)

const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入活动名称',
  },
  type: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择标签类别',
  },
  orgName: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择党组织',
  },
  date: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择活动日期',
  },
  address: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入活动地址',
  },
  count: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入实际参与人数',
  },
  excludeCount: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入不计入参与活动党员人数',
  },
  fileType: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择上传类型',
  },
}

const submit = () => {
  console.log(basicData.value, memberData.value, detailData.value)
  let noMistake = true
  basicRef.value?.validate((errors: any) => errors && (noMistake = false))
  memberRef.value?.validate((errors: any) => errors && (noMistake = false))
  detailRef.value?.validate((errors: any) => errors && (noMistake = false))

  if (noMistake) {
    // TODO 请求提交数据
    console.log(basicData.value, memberData.value, detailData.value)
  }
}

const previewFileList = ref([
  {
    id: 'react',
    name: '我是react.png',
    status: 'finished',
    url: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
  },
  {
    id: 'vue',
    name: '我是vue.png',
    status: 'finished',
    url: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
  },
])
const previewImageUrl = ref('')
const showPhoto = ref(false)
function handlePreview(file: any) {
  const { url } = file
  previewImageUrl.value = url
  showPhoto.value = true
}
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.head
  width 100%
  $flex-align()
  justify-content space-between
.content
  height 100%
  overflow-y auto
  background #f7f7f7
  padding .08rem .1rem
  box-sizing border-box
  p
    font-size .11rem
    padding-left .02rem
  >div
    background $white-bg
    border-radius .04rem
    margin-bottom .08rem
    padding .08rem
    overflow hidden
    box-sizing border-box
    .title
      font-family $font-ping-medium
      margin-bottom .1rem
      font-size .14rem
      $flex-align()
      &:before
        content ''
        display inline-block
        width .02rem
        height .14rem
        background $red
        margin-right .06rem
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
.n-drawer.n-drawer--right-placement.top0
  top 0
  .n-drawer-header__main
    width 100%
  .n-input-number
    width 100%
    .n-input-wrapper
      padding-right 0
    .n-input__suffix
      background #f3f4f7
      border-left .01rem solid $light-gray
      padding 0 .1rem
</style>
