<template>
  <div>
    <el-table v-loading="loading" :data="tableList" border stripe>
      <el-table-column v-for="col in columns" :prop="col.prop" :key="col.prop" :label="col.label" />
      <el-table-column label="发送方式" min-width="150">
        <template #default="{ row }">
          <el-checkbox-group v-model="row.sendType" size="small" @change="rowChange(row)">
            <el-checkbox label="微信"> 微信 </el-checkbox>
            <el-checkbox label="微信群"> 微信群 </el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column label="群二维码" width="100">
        <template #default="{ row }">
          <el-upload
            ref="rewardFile"
            action="#"
            :limit="1"
            accept=".jpg,.jpeg,.png"
            :disabled="loading"
            :show-file-list="false"
            :before-upload="fileBeforeUpload"
            :http-request="(data) => rewardUpload(data, row.id)"
          >
            <el-button type="primary" size="small">
              <Icon icon="ep:upload" class="mr-5px" size="small" /> 点击上传
            </el-button>
          </el-upload>
          <!-- <UploadImg v-model="row.wxQrCode" /> -->

          <!-- <img :src="row.wxCode" width="80px" height="80px" alt="" /> -->
        </template>
      </el-table-column>
      <el-table-column label="微信群名称" prop="wxGroup" min-width="150" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <!-- <div>
            <el-button
              v-if="row.sendType.includes('微信群')"
              type="primary"
              style="padding: 5px 0"
              text
              @click="row.edit = true"
            >
              修改群名称
            </el-button>
          </div> -->
          <div v-if="['每日', '每月'].includes(row.sendFrequency)">
            <el-button type="primary" style="padding: 5px 0" text @click="changeSendTime(row)">
              修改发送时间
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Dialog
      :title="`修改【${sendTimeInfo.messageName}】发送时间`"
      v-model="showSendTime"
      width="500px"
    >
      <el-text type="danger">
        <span v-if="sendTimeInfo.sendFrequency == '每日'">
          请按照时间格式输入，多个时间以“、”分割，如09:00、15:00、18:00
        </span>
        <span v-else-if="sendTimeInfo.sendFrequency == '每月'">
          请按照"日期-时间"格式输入，多个日期以“、”分割，如26-18:00、28-14:00、30-15:00、30-18:00
        </span>
      </el-text>
      <el-input
        type="textarea"
        class="mt-20px mb-20px"
        :autosize="{ minRows: 3 }"
        v-model="sendTimeInfo.sendTime"
        placeholder="请输入"
        clearable
      />
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitSendTime">确 定</el-button>
        <el-button @click="showSendTime = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script setup name="WXSetting">
import * as WechatApi from '@/api/system/wechat'

const message = useMessage() // 消息弹窗

const loading = ref(false)
const tableList = ref([])
const columns = [
  {
    label: '消息名称',
    prop: 'messageName'
  },
  {
    label: '解释说明',
    prop: 'description'
  },
  {
    label: '发送频率',
    prop: 'sendFrequency'
  },
  {
    label: '发送时间',
    prop: 'sendTime'
  }
]

onMounted(() => {
  getTableList()
})

async function getTableList() {
  try {
    loading.value = true
    const list = await WechatApi.getWechatConfigList()
    tableList.value = list.map((it) => ({ ...it, sendType: it.sendType || [] }))
  } finally {
    loading.value = false
  }
}

let timer = ref(null)
const lastId = ref('')
function rowChange(row) {
  try {
    lastId.value == row.id && clearTimeout(timer.value)
    timer.value = setTimeout(async () => {
      lastId.value = row.id
      await WechatApi.updateWechatGroup({
        id: row.id,
        sendType: row.sendType,
        wxGroup: row.wxGroup
      })
      // message.success('修改成功')
    }, 1500)
  } finally {
  }
}

const showSendTime = ref(false)
const sendTimeInfo = ref({})
function changeSendTime(row) {
  showSendTime.value = true
  sendTimeInfo.value = { ...row }
}

const formLoading = ref(false)

async function submitSendTime() {
  // 校验时间是否有效
  const arr = sendTimeInfo.value.sendTime ? sendTimeInfo.value.sendTime.split('、') : []

  if (sendTimeInfo.value.sendFrequency == '每日') {
    // 正则校验是否HH:MM
    if (arr.some((it) => !/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(it))) {
      message.error('请检查输入格式是否正确！！！')
      return
    } else {
      try {
        formLoading.value = true
        await WechatApi.updateWechatSendTime({
          id: sendTimeInfo.value.id,
          sendTime: arr.join('、')
        })
        message.success('修改成功！')
        getTableList()
        showSendTime.value = false
      } finally {
        formLoading.value = false
      }
    }
  } else if (sendTimeInfo.value.sendFrequency == '每月') {
    // 正则校验是否【1-31】-HH:MM
    const reg = /^([1-9]|[1-2]\d|3[01])-([01]?[0-9]|2[0-3]):[0-5][0-9]$/
    if (arr.length > 0 && arr.some((it) => !reg.test(it))) {
      message.error('请检查输入格式是否正确！！！')
      return
    } else {
      try {
        formLoading.value = true
        await WechatApi.updateWechatSendTime({
          id: sendTimeInfo.value.id,
          sendTime: arr.join('、')
        })
        message.success('修改成功！')
        getTableList()
        showSendTime.value = false
      } finally {
        formLoading.value = false
      }
    }
  }
}

const fileBeforeUpload = (file) => {
  let format = '.' + file.name.split('.')[1]
  if (!['.jpg', '.png', 'jpeg'].includes(format)) {
    message.error(`请上传指定格式".jpg,.jpeg,.png"文件`)
    return false
  }
  let isRightSize = file.size / 1024 / 1024 < 20
  if (!isRightSize) {
    message.error('文件大小超过 20MB')
  }
  return isRightSize
}

const fd = ref(new FormData())

async function rewardUpload(data, id) {
  fd.value.append('file', data.file)
  fd.value.append('id', id)
  // 上传接口，成功后得到微信群名
  try {
    // 上传文件
    setTimeout(() => {
      getTableList()
    }, 2000)
  } finally {
  }
}
</script>

<style lang="scss" scoped></style>
