<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="queryhFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.title" :placeholder="'文章名称'" :msg="vdata.searchData.title" />
        <jeepay-text-up v-model:value="vdata.searchData.articleId" :placeholder="'文章编号'" :msg="vdata.searchData.articleId" />
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"  
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <div>
            <a-button v-if="$access('ENT_NOTICE_ADD')" type="primary" class="mg-b-30" @click="addNewNotice">
              <plus-outlined />新建
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'articleId'">
            <b>{{ record.articleId }}</b>
          </template>
          <template v-if="column.key === 'op'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_NOTICE_VIEW')" type="link" @click="detailFunc(record.articleId)">详情</a-button>
              <a-button v-if="$access('ENT_NOTICE_EDIT')" type="link" @click="editFunc(record.articleId)">修改</a-button>
              <a-button v-if="$access('ENT_NOTICE_DEL')" type="link" style="color:red" @click="delFunc(record.articleId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 日志详情抽屉 -->
    <template>
      <a-drawer
        width="50%"
        placement="right"
        :closable="true"
        :visible="visible"
        :maskClosable="false"
        :title="vdata.isAdd?'新建公告':'公告详情'"
        :destroyOnClose="true"
        @close="onClose"
      >
        <div class="account-settings-info-view">
          <a-form ref="infoFormModel" layout="vertical" :model="vdata.noticeDate" :rules="saveRule">
            <a-row justify="space-between" type="flex">
              <a-col :span="10">  
                <a-form-item label="公告标题" name="title">
                  <a-input v-model:value="vdata.noticeDate.title" placeholder="公告标题" />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="公告副标题" name="subtitle">
                  <a-input v-model:value="vdata.noticeDate.subtitle" placeholder="公告副标题" />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="公告范围" name="articleRange">
                  <a-checkbox-group v-model:value="vdata.noticeDate.articleRange" :options="plainOptions" />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="发布人" name="publisher">
                  <a-input v-model:value="vdata.noticeDate.publisher" placeholder="发布人" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="公告内容" name="">
                  <div style="border: 1px solid #ccc">
                    <!-- 工具栏 -->
                    <Toolbar
                      :editorId="editorId"
                      :defaultConfig="toolbarConfig"
                      style="border-bottom: 1px solid #ccc"
                    />
                    <!-- 编辑器 -->
                    <Editor
                      :defaultHtml="vdata.content"
                      :editorId="editorId"
                      :defaultConfig="editorConfig"
                      style="height: 350px; overflow-y: hidden;"
                    />
                  </div>
                </a-form-item>
              </a-col>
              <a-form-item class="bottom-btn" style="margin-top: 20px">
                <a-button type="primary" :loading="vdata.btnLoading" @click="confirm">
                  <check-circle-outlined />{{ vdata.isAdd?'确认新建':'确认更新' }}
                </a-button>
              </a-form-item>
            </a-row>
          </a-form> 
        </div>
      </a-drawer>
    </template>
  </page-header-wrapper>
  <JeepayNoticeViewer ref="noticeViewer" />
</template>

<script setup lang="ts">
import { API_URL_NOTICELIST, req,$getUploadFormParams,API_URL_UPLOAD_SINGLE_FILE_URL } from '@/api/manage'
import { ref, reactive, getCurrentInstance,onBeforeUnmount } from 'vue'
import { message,Modal } from 'ant-design-vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import { IToolbarConfig } from '@wangeditor/editor'
import axios from 'axios'
import '@wangeditor/editor/dist/css/style.css'
import storage from '@/utils/jeepayStorageWrapper'
// 导入全局函数
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties
const saveRule = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  subtitle: [{ required: true, message: '请输入文章副标题', trigger: 'blur' }],
  articleRange:[{required: true,message: '请选择文章范围',  type: 'array'}],
  publisher: [{ required: true, message: '请填写发布人', trigger: 'blur' }]
}
const upload = ref()
const noticeViewer = ref() //查看详情
const plainOptions = [
  {label:'商户',value:'MCH'},
  {label:'代理商',value:'AGENT'}
]
const infoFormModel = ref()
const infoTable = ref()
const dateRangePicker = ref()
// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = 'wangeEditor-1' // 富文本编辑器
 // 编辑器配置
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: { /* 菜单配置，下文解释 */ }
}
type InsertFnType = (url: string, alt: string, href: string) => void
editorConfig.MENU_CONF['uploadImage'] = {
  base64LimitSize: 10 * 1024, // 10kb以内的图片不上传
  // // 用户自定义上传图片
  customUpload(file, insertFn) {
    $getUploadFormParams(file, 'notice').then(res =>{
      // 如果值为LOCAL_SINGLE_FILE_URL 则是本地存储
      if(res.formActionUrl =='LOCAL_SINGLE_FILE_URL') {
        res.bizType = 'notice'
        res.formActionUrl = API_URL_UPLOAD_SINGLE_FILE_URL
      }
      //uploadRes没用处
     upLoadFile(res.formActionUrl,res.formParams,file,res.bizType,insertFn).then(uploadRes =>{
      // 如果存在bizTye 则是本体存储 需要在 请求回来后显示图片
      if(res.bizType) return 
       insertFn(res.ossFileUrl, file.name, res.ossFileUrl)
     })
    }).catch(err =>{
      $infoBox.message.success('上传失败',err)
    })
  },

}

// 隐藏编辑器菜单中，一些菜单项
const toolbarConfig: Partial<IToolbarConfig> = {
  // 隐藏 全屏放大  上传视频  等
  excludeKeys: ['fullScreen', 'uploadVideo', 'insertVideo', 'deleteVideo',]
}
// eslint-disable-next-line no-unused-vars
const tableColumns = reactive([
  { key: 'articleId', title: '公告ID', fixed: 'left' },
  { key: 'title', title: '公告标题', dataIndex: 'title' },
  { key: 'subtitle', title: '公告副标题', dataIndex: 'subtitle' },
  { key: 'publisher', title: '创建者', ellipsis: true, dataIndex: 'publisher' },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期' },
  { key: 'op', title: '操作',  fixed: 'right', align: 'center' }
])

const vdata = reactive({
  searchData : {} as any,
  btnLoading:false,
  content: '',
  recordId:'',
  noticeDate:{} as any,
  isAdd:false, //是否为新建公告
  avatarUrl:''
})

let visible = ref(false)
// 重置表单验证规则
  if (infoFormModel.value) {
    infoFormModel.value.resetFields()
  }
// 请求table接口数据
function reqTableDataFunc (params) {
  return req.list(API_URL_NOTICELIST, Object.assign(params,{articleType:1}))
}
function delFunc (articleId) {
  if (!articleId) {
    return message.error('请选择要删除的公告')
  }
  Modal.confirm({
    title: '确认删除公告吗？',
    okType: 'danger',
    onOk () {        
      req.delById(API_URL_NOTICELIST, articleId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
    },
    })
}
function addNewNotice(){
  visible.value = true
  vdata.isAdd = true
  vdata.noticeDate = {}
  vdata.content=''
}
function editFunc (recordId) {
    vdata.recordId = recordId
    req.getById(API_URL_NOTICELIST, recordId).then(res => {
      vdata.content = res.content
      vdata.noticeDate = res
      vdata.noticeDate.articleRange = res.articleRange?res.articleRange.split(','):[]
      visible.value = true
      vdata.isAdd = false
    })
}

//查看详情
function detailFunc(recordId){
  noticeViewer.value.showDrawer(recordId)
}
       
function onClose () {
    visible.value = false
  }
function queryhFunc () {
  vdata.btnLoading = true
  infoTable.value.refTable(true)
}
function confirm(){
  infoFormModel.value.validate().then(() => {
    const editor:any = getEditor(editorId) 
   
      vdata.btnLoading = true // 打开按钮上的 loading
      vdata.noticeDate.content = editor.getHtml() //富文本内容
      if(vdata.isAdd){
        vdata.noticeDate.articleType = 1
        vdata.noticeDate.articleRange = vdata.noticeDate.articleRange.join(',')
          req.add(API_URL_NOTICELIST, vdata.noticeDate)
          .then(res => {
            $infoBox.message.success('添加成功')
            vdata.btnLoading = false
            visible.value = false
            queryhFunc()
        }).catch(res => {vdata.btnLoading = false})
      }else{
        vdata.noticeDate.articleRange = vdata.noticeDate.articleRange.join(',')
        req.updateById(API_URL_NOTICELIST,  vdata.recordId, vdata.noticeDate)
          .then(res => {
            $infoBox.message.success('修改成功')
            vdata.btnLoading = false
            visible.value = false
            queryhFunc()
        }).catch(res => {vdata.btnLoading = false})
      }
  })
   
}
  // 组件销毁时，及时销毁编辑器
  onBeforeUnmount(() => {
      const editor = getEditor(editorId)
      if (editor == null ) return
      // 销毁，并移除 editor
      editor.destroy()
      removeEditor(editorId)
  })
//上传图片
const upLoadFile = (url,data,file,bizType,insertFn) =>{
  let formData = new FormData()
  if (bizType) formData.append('bizType', bizType)
  formData.append('OSSAccessKeyId', data.OSSAccessKeyId)
  formData.append('key', data.key)
  formData.append('Signature', data.Signature)
  formData.append('policy', data.policy)
  formData.append('success_action_status', data.success_action_status)
  formData.append('file', file)
  return axios({
    url:url,
    method:'POST',
    data:formData,
    headers:{
      iToken:storage.getToken(),
      'content-type':'multipart/form-data'
    },
  }).then(({data})=>{
    // 如果为本地存储 显示图片
    if(bizType){
      insertFn(data.data)
    }
  })
}

function onReset(){
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: '' }
}
</script>


