<script lang="ts" setup>
import type { UploadFile, UploadFiles, UploadRawFile } from 'element-plus'

import { useRoute, useRouter } from 'vue-router'

import { SYS_INFO } from '@vben/preferences'
import { useAccessStore } from '@vben/stores'

import { Paperclip, Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

import { putMailbox, sendMailbox } from '#/api'
import { useEmail } from '#/store'

import UploadDia from './components/uploadDia.vue'

const router = useRouter()
interface formType {
  content: string
  letterIcon: string
  letterOpenIcon: string
  messageType: number
  publishTime: string
  recipients: anyObj[]
  recipientType: string
  senderId: string
  senderName: string
  title: string
  userMessageAppendix: {
    imageResource: string
    rewardInfo: {
      rewards: any[]
    }
  }
}
const Email = useEmail()

const route = useRoute()
const picUpload = ref()
const showCancel = ref(false)
const fileList = ref<any[]>([])
const onSending = ref(false) // 发动结束前不可发送
const inputData = ref({
  receive: '',
  send: '系统邮件',
})
const { accessToken } = storeToRefs(useAccessStore())
const dialogVisible = ref(false)
const dialogGiftVisible = ref(false)
const giftData = ref({
  // 奖励弹框数据
  giftSelect: {},
  giftOptions: [
    {
      rewardCode: 'diamond',
      cName: '钻石',
      note: '普通货币，可在商城内购买心仪的商品。',
      needRedeem: false,
      rewardResourceUrl:
        'https://word-1313840333.cos.ap-guangzhou.myqcloud.com/1792385917515063297.png',
      rewardType: 4,
    },
    {
      rewardCode: 'currency',
      cName: '乐币',
      note: '珍贵货币，可在商城内购买心仪的实物商品。',
      needRedeem: false,
      rewardResourceUrl:
        'https://word-1313840333.cos.ap-guangzhou.myqcloud.com/1792385916177080321.png',
      rewardType: 4,
    },
    {
      rewardCode: 'experience',
      cName: '经验值',
      note: '闯关及完成任务获得经验值。',
      needRedeem: false,
      rewardResourceUrl:
        'https://word-1313840333.cos.ap-guangzhou.myqcloud.com/1792385915531157506.png',
      rewardType: 4,
    },
    {
      rewardCode: 'activeDegree',
      cName: '活跃度',
      note: '完成任务获得活跃度。',
      needRedeem: false,
      rewardResourceUrl:
        'https://word-1313840333.cos.ap-guangzhou.myqcloud.com/1792385888888938497.png',
      rewardType: 4,
    },
    {
      rewardCode: 'twistEggCoin',
      cName: '扭蛋币',
      note: '投入扭蛋机可扭蛋1次。',
      needRedeem: false,
      rewardResourceUrl:
        'https://word-1313840333.cos.ap-guangzhou.myqcloud.com/1792385916831391746.png',
      rewardType: 2,
    },
  ],
  giftNumber: 0,
})
const _formData: formType = {
  recipients: [],
  senderId: '-1',
  title: '',
  content: '',
  recipientType: 'selected',
  letterIcon: '',
  messageType: 1,
  letterOpenIcon: '',
  publishTime: '',
  senderName: '',
  userMessageAppendix: {
    imageResource: '',
    rewardInfo: {
      rewards: [],
    },
  },
}
const formData = ref({
  ..._formData,
})

const handleRemove = (file: UploadFile) => {
  picUpload.value.handleRemove(file)
}

function handleAddReceive(str: string) {
  if (str === 'all') {
    formData.value.recipientType = 'all'
    formData.value.recipients = []
  } else {
    if (!formData.value.recipients.some((item) => item.recipientId === str)) {
      formData.value.recipients.push({
        recipientId: str,
      })
    }
  }
  inputData.value.receive = ''
}

function handleAddSender(str: string) {
  // 输入发送人
  formData.value.senderId = str === '系统邮件' ? '-1' : str
}

function handlecloseReceive(item: any) {
  if (item === 'all') {
    formData.value.recipientType = 'selected'
  } else {
    formData.value.recipients = formData.value.recipients.filter(
      (v) => v.recipientId !== item.recipientId,
    )
  }
}
function handlecloseGift(item: any) {
  const rewardInfo = formData.value.userMessageAppendix?.rewardInfo
  if (!rewardInfo?.rewards?.length) return
  // 删除某个奖励
  rewardInfo.rewards = rewardInfo.rewards.filter(
    (v) => v.rewardCode !== item.rewardCode,
  )
}

function handleSend() {
  if (onSending.value) return
  onSending.value = true
  if (!formData.value.publishTime) {
    formData.value.publishTime = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss')
  }
  const appendix = formData.value.userMessageAppendix
  if (appendix) {
    appendix.imageResource = fileList.value
      .map((item) => {
        if (item.url) return item.url
        else if (item.response.code === 200) return item.response.data.filePath
        else return ''
      })
      .join(',')
  }

  // 有空白停止发送，提示用户
  if (
    !formData.value.title ||
    !formData.value.content
    // !formData.value.userMessageAppendix?.rewardInfo.rewards.length
  ) {
    onSending.value = false
    return ElMessage.error('请勿发送空内容')
  }
  formData.value.publishTime = dayjs(formData.value.publishTime).format(
    'YYYY-MM-DD HH:mm:ss',
  )
  if (route.params.id === '0') {
    // 添加
    sendMailbox(formData.value)
      .then(() => {
        ElMessage.success('发送成功')
        dialogVisible.value = false
        router.back()
      })
      .finally(() => {
        onSending.value = false
      })
  } else {
    // 修改
    putMailbox({ id: route.params.id, ...formData.value })
      .then(() => {
        ElMessage.success('发送成功')
        dialogVisible.value = false
        router.back()
      })
      .finally(() => {
        onSending.value = false
      })
  }
}

function disabledDate(time: Date) {
  // return time.getTime() < Date.now() - 8.64e7; // 只能选择今天及今天之后的日期
  return time.getTime() < Date.now() - 8.64e6 // 只能选择今天之后的日期，今天的日期也不能选
}

function handleAddGift() {
  if (
    giftData.value.giftNumber !== 0 &&
    !formData.value.userMessageAppendix?.rewardInfo.rewards.some(
      (item) =>
        item.rewardCode === (giftData.value.giftSelect as any).rewardCode,
    )
  ) {
    formData.value.userMessageAppendix?.rewardInfo.rewards.push({
      count: giftData.value.giftNumber,
      ...giftData.value.giftSelect,
    })
  }

  clearAddGiftData()
  dialogGiftVisible.value = false
}

function clearAddGiftData() {
  giftData.value.giftNumber = 0
  giftData.value.giftSelect = {}
}

function handleCancel() {
  // 取消编辑
  router.back()
}
function beforeUpload(file: UploadRawFile) {
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小请不要超过10M')
    return false
  }
}

function error(error: Error, _: UploadFile, _2: UploadFiles) {
  if (String(error).includes('413')) {
    ElMessage.error('上传的图片过大')
  }
}

onMounted(() => {
  if (route.params.id !== '0') {
    for (const key in formData.value) {
      ;(formData.value as any)[key] = Email.userMessageBoxAddMessage[key]
    }
    inputData.value.send =
      Email.userMessageBoxAddMessage.senderId === '-1'
        ? '系统邮件'
        : Email.userMessageBoxAddMessage.senderId
    fileList.value =
      Email.userMessageBoxAddMessage.userMessageAppendix?.imageResource
        .split(',')
        .map((item: any) => ({ url: item, name: 'https://...' }))
  }
})
onUnmounted(() => {
  Email.clearData()
})
</script>

<template>
  <div class="page">
    <div class="title">
      <div class="get title-item">
        <div class="label">收件人：</div>
        <div class="content receive">
          <!-- <input class="ipt" type="text" placeholder="请输入收件人" /> -->
          <template v-if="formData.recipients?.length > 0">
            <el-tag
              v-for="(item, index) in formData.recipients"
              :key="index"
              closable
              size="large"
              @close="handlecloseReceive(item)"
            >
              {{ item.recipientId }}
            </el-tag>
          </template>
          <el-tag
            v-if="formData.recipientType === 'all'"
            closable
            size="large"
            @close="handlecloseReceive('all')"
          >
            all
          </el-tag>

          <el-input
            v-model="inputData.receive"
            class="ipt"
            placeholder="请输入收件人"
            :disabled="formData.recipientType === 'all'"
            @change="handleAddReceive($event)"
          />
        </div>
      </div>
      <div class="send title-item">
        <div class="label">发件人：</div>
        <div class="content">
          <el-input
            v-model="inputData.send"
            class="ipt"
            placeholder="请输入发件人"
            @change="handleAddSender($event)"
          />
        </div>
      </div>
      <div class="topic title-item">
        <div class="label"><span> 主</span> <span> 题：</span></div>
        <div class="content">
          <el-input
            v-model="formData.title"
            class="ipt"
            placeholder="请输入主题"
          />
        </div>
      </div>
      <div class="center title-item">
        <div class="label"><span> 正</span> <span> 文：</span></div>
        <div class="content center-content">
          <el-input
            v-model="formData.content"
            class="ipt"
            type="textarea"
            :rows="8"
            placeholder="请输入正文"
          />
        </div>
      </div>
    </div>
    <div class="link">
      <div class="pic link-item">
        <div class="label">
          <el-icon><Paperclip /></el-icon>
          添加图片
        </div>
        <div class="link-content">
          <el-upload
            ref="picUpload"
            v-model:file-list="fileList"
            action="/api/main/sysFileInfo/tenUploadAll"
            :headers="{
              Authorization: accessToken,
              'X-Tenant-Id': SYS_INFO.tenantId,
            }"
            :before-upload="beforeUpload"
            :on-error="error"
          >
            <el-icon><Plus /></el-icon>

            <template #file="{ file }">
              <div class="file-item">
                <el-tag closable size="large" @close="handleRemove(file)">
                  {{ file.name }}
                </el-tag>
              </div>
            </template>
          </el-upload>
        </div>
      </div>
      <div class="prise link-item">
        <div class="label">
          <el-icon><Paperclip /></el-icon>
          添加奖励
        </div>
        <div class="priseList-content">
          <div
            v-if="formData.userMessageAppendix?.rewardInfo.rewards.length > 0"
            class="tag-box"
          >
            <el-tag
              v-for="item in formData.userMessageAppendix?.rewardInfo.rewards"
              :key="item"
              closable
              size="large"
              @close="handlecloseGift(item)"
            >
              {{ `${item.cName || item.rewardCode} ${item.count}` }}
            </el-tag>
          </div>
          <div class="addIcon" @click="dialogGiftVisible = true">
            <el-icon><Plus /></el-icon>
          </div>
        </div>
      </div>
      <div class="mail link-item">
        <div class="label">
          <el-icon><Paperclip /></el-icon>
          <span> 信封图标 </span>

          <UploadDia v-model="formData.letterIcon" />
        </div>
        <div class="label">
          <el-icon><Paperclip /></el-icon>
          <span> 信封拆后图标 </span>

          <UploadDia v-model="formData.letterOpenIcon" />
        </div>
      </div>
    </div>
    <div class="button">
      <div class="send">
        <el-button
          v-if="Email.sendStatus !== 2"
          size="large"
          type="primary"
          @click="handleSend"
        >
          发送
        </el-button>
      </div>
      <div class="send">
        <el-button
          v-if="Email.sendStatus !== 2"
          size="large"
          type="primary"
          @click="dialogVisible = true"
        >
          定时发送
        </el-button>
      </div>
      <div class="send">
        <el-button
          size="large"
          @click="
            () => {
              if (Email.sendStatus !== 2) {
                showCancel = true
              } else {
                $router.back()
              }
            }
          "
        >
          {{ Email.sendStatus === 2 ? '返回' : '取消' }}
        </el-button>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="定时发送" center width="500">
      <el-date-picker
        v-model="formData.publishTime"
        type="datetime"
        placeholder="请选择日期时间"
        format="YYYY/MM/DD HH:mm:ss"
        :disabled-date="disabledDate"
      />
      <p style="margin: 20px 0; font-size: 18px; text-align: center">
        给
        {{ formData.recipientType === 'all' ? '所有用户' : '选中的用户' }}
        发送邮件，是否确认定时发送？
      </p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSend"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogGiftVisible" title="添加奖励" center width="500">
      <div class="dialogGiftContent">
        <el-row justify="space-around">
          <el-col :span="10">
            <span style="padding-right: 20px">奖励</span>
            <el-select
              v-model="giftData.giftSelect"
              placeholder="请选择"
              value-key="rewardCode"
              style="width: 120px"
            >
              <el-option
                v-for="item in giftData.giftOptions"
                :key="item.rewardCode"
                :label="item.cName"
                :value="item"
              />
            </el-select>
          </el-col>
          <el-col :span="10">
            <span style="padding-right: 20px">数量</span>
            <el-input
              v-model.number="giftData.giftNumber"
              style="width: 120px"
              placeholder="Please input"
            />
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAddGift"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showCancel" title="确认取消" center width="500">
      <p style="margin: 20px 0; font-size: 18px; text-align: center">
        取消后无法保存记录，是否确认取消
      </p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCancel = false">取消</el-button>
          <el-button type="primary" @click="handleCancel"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
ul,
li {
  padding: 0;
  margin: 0;
  list-style-type: none;
}
//
.page {
  height: calc(100vh - 130px);
  padding: 20px;
  background-color: #fff;
}

.title {
  .title-item {
    box-sizing: border-box;
    display: flex;
    width: 100%;
    margin-bottom: 15px;
    font-size: 20px;
    line-height: 30px;
    border-bottom: 1px solid #cfcfcf;

    .label {
      box-sizing: border-box;
      display: flex;
      flex-shrink: 0;
      justify-content: space-between;
      width: 80px;
      margin-right: 10px;
    }

    &:last-child {
      display: block;
      border-bottom: none;
    }

    .content {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      gap: 20px;

      :deep(.ipt) {
        width: 100%;
        height: 30px;
        font-family: 'Times New Roman', Times, serif;
        font-size: 20px;
        outline: none;
        border: none;

        .el-input__wrapper {
          box-shadow: none;
        }

        .el-textarea__inner,
        .el-input__inner {
          font-family: 'Times New Roman', Times, serif;
          color: #222;
          outline: none;
          border: none;
          border-radius: 0;
          box-shadow: none;

          &:hover {
            border: none;
            box-shadow: none;
          }

          &:focus {
            border: none;
            box-shadow: none;
          }

          &::placeholder {
            font-family: 'Times New Roman', Times, serif;
            font-size: 16px;
          }
        }
      }
    }

    .receive {
      :deep(.ipt) {
        width: 200px;
      }
    }

    .center-content {
      padding: 10px 20px;
      margin-top: 10px;
      border: 1px solid #cfcfcf;

      :deep(.ipt) {
        height: 100%;
      }
    }
  }

  .topic {
    .content {
      :deep(.ipt) {
        .el-input__inner {
          font-weight: bold;
        }
      }
    }
  }
}

.link {
  .link-item {
    display: flex;
    margin-bottom: 20px;
    font-size: 20px;

    .label {
      flex-shrink: 0;
      margin-right: 10px;

      .el-icon {
        color: rgb(160 160 160);
      }
    }

    .link-content {
      width: 100%;

      & > :deep(div) {
        display: flex;
        flex-flow: row-reverse wrap;
        align-items: center;
        justify-content: flex-end;
        width: 100%;

        .el-upload-list {
          display: flex;
          flex-wrap: wrap;
          width: auto;
          margin: 0;

          li {
            display: flex;
            width: max-content;
            margin: 0 10px 5px 0;
          }
        }
      }
    }

    .link-content,
    .priseList-content {
      .el-tag {
        border-radius: 5px !important;
      }
    }

    .priseList-content {
      display: flex;
      align-items: center;

      .tag-box {
        display: flex;
        gap: 10px;
        align-items: center;
        margin-right: 10px;
      }

      .addIcon {
        cursor: pointer;
      }
    }
  }

  .mail {
    .label {
      display: flex;
      align-items: center;

      span {
        margin-right: 20px;
      }

      &:first-child {
        margin-right: 200px;
      }
    }
  }
}

.button {
  display: flex;
  gap: 30px;
  padding: 12px 0;
}

.dialogGiftContent {
  //   display: flex;
}
</style>
