<!--
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-05-07 11:31:53
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-23 01:49:16
 * @FilePath: \vue-element-plus-admin-mini\src\views\Template\TemplateMangement.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import {
  ElInput,
  ElUpload,
  ElMessage,
  UploadUserFile,
  ElButton,
  ElTag,
  ElMessageBox
} from 'element-plus'
import { Editor } from '@/components/Editor'
import { ContentWrap } from '@/components/ContentWrap'
import { getSystem, saveSystem, getBulletin, saveBulletin, deleteBulletin } from '@/api/System'
import { useI18n } from '@/hooks/web/useI18n'
import { getTreeTableListApi } from '@/api/table'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { ref, reactive, onMounted, unref } from 'vue'
import { Form, FormSchema, RadioOption } from '@/components/Form'
import { Dialog } from '@/components/Dialog'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import { any } from 'vue-types'
import { useTable } from '@/hooks/web/useTable'
const userStore = useUserStore()
const token = userStore.getToken

import type { UploadProps } from 'element-plus'

const Authorization = ref(`Bearer ${userStore.getToken}`)
const headers = ref({ Authorization: Authorization.value })

setInterval(() => {
  Authorization.value = `Bearer ${userStore.getToken}`
  console.log('Authorization', Authorization.value)
  headers.value = { Authorization: Authorization.value }
}, 6000) //
const PATH_URL = window.VITE_API_BASE_PATH + '/config/manage/uploadImg'
const IMG_URL = window.VITE_API_BASE_PATH
const { required, lengthRange } = useValidator()
const fileList = ref<UploadUserFile[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // },
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])
const dialogImageUrl = ref('')
const isedit = ref('新增')
let tihuanarr = reactive([] as any)

//表格
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getBulletin()
    console.log('ssdasadddddddddd', res)
    return {
      list: res.data,
      total: res.data.length
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

const { t } = useI18n()
const columns = reactive<TableColumn[]>([
  {
    field: 'infoType',
    label: '通知类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      return <div>{cellValue === 1 ? '更新日志' : '系统公告'}</div>
    }
  },
  {
    field: 'createTime',
    label: '发布时间'
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => editaffiche(data)}>
              {t('tableDemo.edit')}
            </ElButton>
            <ElButton type="danger" onClick={() => handerdeleteaffiche(data)}>
              {t('tableDemo.delete')}
            </ElButton>
          </>
        )
      }
    }
  }
])
//活动公告删除
const handerdeleteaffiche = async (data: TableSlotDefault) => {
  ElMessageBox.confirm('确定删除该数据?')
    .then(async () => {
      const res = await deleteBulletin({ infoId: data.row.infoId })
      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}
//活动公告编辑
const editaffiche = async (data: TableSlotDefault) => {
  isedit.value = '编辑'
  dialogVisible2.value = true
  const formData = await getFormData()
  console.log('ooooooooooooo', formData)
  formData.content = data.row.content
  formData.infoType = String(data.row.infoType)
  formData.infoId = data.row.infoId
  console.log('wwwwwwwwwww', data)
}

const updata = reactive({
  data: [
    {
      configKey: 'banner',
      configValue: '',
      contentType: 'application/json'
    },
    {
      configKey: 'direction',
      configValue: '',
      contentType: 'String'
    }
  ]
})
const dialogVisible = ref(false)

//移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log('adasdasd', uploadFile)
  console.log('adasdasde', tihuanarr)
  console.log(uploadFile, uploadFiles)
  tihuanarr.map((item, index) => {
    if (uploadFile.name == item.name) {
      tihuanarr.splice(index, 1)
    }
  })

  updata.data[0].configValue = JSON.stringify(tihuanarr)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

defineOptions({
  name: 'SystemSetting'
})

onMounted(async () => {
  const res = await getSystem()
  console.log('kankanasqqqqqqqqqqqqqqqqqq', res)

  updata.data = res.data
  res.data.map((item) => {
    if (item.configKey == 'banner') {
      tihuanarr = JSON.parse(item.configValue)
      fileList.value = JSON.parse(item.configValue)
    }
    if (item.configKey == 'direction') {
      defaultHtml.value = item.configValue
    }
  })
})

const text = ref('')
const defaultHtml = ref('')

const change = (html: string) => {
  console.log(html)
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  let a1 = {
    name: uploadFile.name,
    url: IMG_URL + response.data
  }

  tihuanarr.push(a1)
  updata.data.map((item) => {
    if (item.configKey == 'banner') {
      item.configValue = JSON.stringify(tihuanarr)
    }
  })
}

const tijiao = async () => {
  updata.data.map((item) => {
    if (item.configKey == 'banner' && item.configValue == '[]') {
      ElMessage.warning('Banner不能为空')
      return
    }

    if (item.configKey == 'direction') {
      item.configValue = defaultHtml.value
    }

    if (item.configKey == 'direction' && item.configValue == '<p><br></p>') {
      ElMessage.warning('使用教程不能为空')
      return
    }
  })

  let res = await saveSystem(updata.data)
  if (res.code == 200) {
    ElMessage({
      message: '提交成功',
      type: 'success'
    })
  }
}

let dialogVisible2 = ref(false)

const schema = reactive<FormSchema[]>([
  {
    field: 'infoType',
    label: '通知类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '更新日志',
          value: '1'
        },
        {
          label: '系统公告',
          value: '2'
        }
      ]
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'content',
    component: 'Editor',
    value: '',
    label: '内容',
    colProps: {
      span: 24
    }
  },
  {
    field: 'confirm',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%] flex justify-center h-full">
                <BaseButton
                  style="font-size: 1rem; height: 2.2rem; "
                  type="primary"
                  class="w-[70px]"
                  onClick={signIn}
                >
                  提交
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])

const xingzeng = async () => {
  console.log('sdajsda')
  isedit.value = '新增'
  dialogVisible2.value = true
}
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
// 提交活动公告
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()

  await formRef?.validate(async (isValid) => {
    if (isValid) {
      let res = await saveBulletin(formData)
      console.log('kajjjjjjjjjjjj', res)

      if (res.code == 200) {
        dialogVisible2.value = false
        refresh()
      }
    }
  })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('请上传png、jpg格式图片')
    return false
  }
  return true
}
</script>

<template>
  <ContentWrap>
    <div style="margin-bottom: 10px"
      ><img style="padding-bottom: 8px" src="@/assets/imgs/dian.png" alt="" srcset="" /> Banner</div
    >
    <el-upload
      v-model:file-list="fileList"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :action="PATH_URL"
      :headers="headers"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <el-icon> <span style="font-size: 50px">+</span> </el-icon>
      <template #tip>
        <div class="el-upload__tip" style="font-size: 14px"
          >格式：PNG/JPG，大小：1520*310px，不超过20M</div
        >
      </template>
    </el-upload>
  </ContentWrap>
  <ContentWrap>
    <div style="margin-bottom: 10px"
      ><img style="padding-bottom: 8px" src="@/assets/imgs/dian.png" alt="" srcset="" />
      使用教程</div
    >
    <Editor height="250px" v-model="defaultHtml" ref="editorRef" @change="change" />
  </ContentWrap>
  <ContentWrap>
    <div style="margin-bottom: 10px">通知</div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      headerAlign="center"
      align="center"
      :loading="loading"
      sortable
      @register="tableRegister"
    />
    <div style="width: 100%; display: flex; justify-content: center; margin: 20px 0 0px 0">
      <BaseButton @click="xingzeng" type="primary"> 新增 </BaseButton>
    </div>
  </ContentWrap>
  <div>
    <BaseButton
      @click="tijiao"
      style="font-size: 1rem; height: 2.2rem; margin-top: 10px"
      type="primary"
      class="w-[70px]"
    >
      提交
    </BaseButton>
  </div>
  <Dialog v-model="dialogVisible2" maxHeight="45vh" width="48vw" :title="isedit">
    <Form label-position="left  " :schema="schema" @register="formRegister" />
  </Dialog>
</template>

<style>
.w-e-modal .babel-container {
  margin-bottom: 2px;
}
</style>
