/*
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-07-31 18:21:04
 * @LastEditTime: 2023-08-10 18:25:28
 */
import { _ } from 'iking-utils'
import useNewsStore from '@main/store/modules/news'
import useTabbarStore from '@main/store/modules/tabbar'
import { ENewsChannel } from '../../enum'
// import { useNews } from '../useNews'
import { msgApi } from '@main/api/modules/msg'
// const {
//   getMsgChannelByNo
// } = useNews()

const REGEX = /【(.*?)】/g
const REGEX2 = /\${(.*?)\}(.*)$/

export const useChannel = (isEdit = false, systemForm: Ref<any>) => {
  const IS_EDITED = isEdit && (systemForm.value.id !== null)
  const newsStore = useNewsStore()
  const router = useRouter()
  const loading = ref(false)
  const { msgSuccess, msgError } = useMessage()

  const replaceStr = (str: string) => {
    // eslint-disable-next-line no-template-curly-in-string
    return str?.replace(REGEX, '$${$1}').replace(REGEX2, '$1$2')
  }
  const formatData = (status: typeof ENewsChannel.启用 | typeof ENewsChannel.禁用) => {
    return {
      ...systemForm.value,
      content: replaceStr(systemForm.value.content),
      status,
      configured: true,
      redirectDefinitions: [{
        redirectTo: systemForm.value.redirectDefinitions
      }]
    }
  }
  // 保存不启用
  const handSaveUnnable = async () => {
    const data = _.cloneDeep(systemForm.value)
    if (data?.$row)
      delete data.$row
    loading.value = true
    const { success, msg } = !IS_EDITED
      ? await msgApi.insertMsgTemplate(formatData(ENewsChannel.禁用))
      : await msgApi.updateMsgChannelTemplate({ ...data, content: replaceStr(data.content), status: ENewsChannel.禁用 })
    loading.value = false

    if (success) {
      msgSuccess(msg)
      if (!IS_EDITED) {
        systemForm.value.configured = true
        systemForm.value.status = ENewsChannel.禁用
      }
    }
    else {
      msgError(msg)
    }
  }
  // 启用
  const handEnable = async (cb?: Function) => {
    const data = _.cloneDeep(systemForm.value)
    if (data?.$row)
      delete data.$row
    loading.value = true
    const { success, msg } = !IS_EDITED
      ? await msgApi.insertMsgTemplate(formatData(ENewsChannel.启用))
      : await msgApi.updateMsgChannelTemplate({ ...data, content: replaceStr(data.content), status: ENewsChannel.启用 })
    loading.value = false
    cb?.(success)
    if (success) {
      msgSuccess(msg)
      if (!IS_EDITED) {
        systemForm.value.configured = true
        systemForm.value.status = ENewsChannel.启用
      }
      else {
        handCancel()
      }
    }
    else {
      msgError(msg)
    }
  }

  const tabbarStore = useTabbarStore()
  // 取消
  const handCancel = () => {
    router.back()
    newsStore.setMsgContentForm(false)
    tabbarStore.remove(location.hash.slice(1))
  }

  return {
    loading,
    handSaveUnnable,
    handEnable,
    handCancel,
    msgSuccess,
    msgError,
    linkHolder: '请输入跳转链接，支持系统内链接(approve://approve-center/approve-list)和系统外链接(http://www.abc.com)',
    linkRule: [{
      required: false,
      validator: (rule: any, value: any, callback: any) => {
        const REG = /^[^\s]+:\/\/\S+$/
        if (value === '')
          callback()

        else if (!REG.test(value))
          callback(new Error('跳转链接格式错误'))

        else
          callback()
      }
    }]
  }
}
