<template>
  <view class="ss-p-x-30 ss-p-y-30">
    <!-- 黄历信息 -->
    <view class="popupContent">
			<view class="content-box">
				<view class="text-center ss-p-y-30">
					<view class="yangli">{{ almanac.yangli }}</view>
					<view class="yinli">{{ almanac.yinli }}</view>
					<view class="d-flex align-center justify-center">
						<span style="color: #7f7f7f;">幸运色</span>
						<span v-if="almanac.color === '白'" class="ss-m-l-20" style="color: #7f7f7f;">白色</span>
						<view
							v-else
							class="luckyColor ss-m-l-20"
							:style="{ 'background-color': `${colorDict[almanac.color] || '#2979ff'}` }"
						></view>
					</view>
				</view>
				<view class="center-box ss-p-y-30 ss-p-x-30">
					<view class="d-flex">
						<view class="yi d-flex align-center justify-center">宜</view>
						<view class="font-size-15" style="flex: 1; color: #c6b393;">{{ almanac.yi }}</view>
					</view>
					<view class="d-flex ss-m-t-30">
						<view class="ji d-flex align-center justify-center">忌</view>
						<view class="font-size-15" style="flex: 1; color: #7f7f7f;">{{ almanac.ji }}</view>
					</view>
				</view>
				<view class="bottom-box">
					<view class="bottom-box-item d-flex flex-column align-center justify-center">
						<view class="padding">
							<view class="label">五行</view>
							<view class="value">{{ almanac.wuxing }}</view>
						</view>
						<view class="border"></view>
						<view class="padding">
							<view class="label">吉神</view>
							<view class="value">{{ almanac.jishen }}</view>
						</view>
					</view>
					<view class="bottom-box-item d-flex align-center justify-center">
						<view class="padding">
							<view class="label">彭祖</view>
							<view class="value">{{ almanac.baiji }}</view>
						</view>
					</view>
					<view class="bottom-box-item d-flex flex-column align-center justify-center">
						<view class="padding">
							<view class="label">冲煞</view>
							<view class="value">{{ almanac.chongsha }}</view>
						</view>
						<view class="border"></view>
						<view class="padding">
							<view class="label">凶神</view>
							<view class="value">{{ almanac.xiongshen }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

    <view class="journal">
      <uni-section title="手账" type="line"></uni-section>
			<uni-card v-if="journal && journal?.notes && !isEdit" @click="handleUpdateJournal">
				<view class="ss-m-t-15">{{ journal.notes }}</view>
			</uni-card>
      <view v-if="isEdit" class="ss-m-t-30 journal-content">
        <uni-easyinput
          :type="inputType"
          v-model="notes"
          clearable
          :focus="inputType === 'textarea'"
          maxlength="500"
          autoHeight
          placeholder="请输入要记录的内容"
          @input="handleInput"
        />
        <view v-if="inputType === 'textarea'" style="text-align: end;" class="ss-m-t-10 color-999">{{ notes?.length || 0 }}/500</view>
        <view class="f-horizon-center" v-if="inputType === 'textarea'">
          <button class="commonBtnStyle cancel-button" size="default" @click="handleCancel">取 消</button>
          <button 
            size="default" 
            :class="{'save-button': notes, 'commonBtnStyle': notes, 'send-button': !notes}" 
            @click="handleSubmit"
            :disabled="disabled"
          >保 存</button>
        </view>
      </view>
		</view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getDrawLots, getCalendarRecord, saveCalendarRecord } from '@/api/drawLots.js'

const colorDict = {
	'白': '#FAFAFA',
	'黑': '#212121',
	'绿': '#43A047',
	'红': '#F44336',
	'黄': '#FDD835'
}

const inputType = ref('text')
const isEdit = ref(false)
const date = ref(null)
const notes = ref(null) // 手账内容
const journal = ref({}) // 当前日期手账记录
const disabled = ref(false)
const deleteDisabled = ref(false)
const userInfo = ref(uni.getStorageSync('wechat_user'))

// 获取黄历信息
const almanac = ref({})
const getCalendarInfo = async () => {
  try {
    const { result } = await getDrawLots({ date: date.value })
    if (!result) return uni.showToast({ title: '黄历信息获取失败', icon: 'none' })
    almanac.value = result || {}
  } catch (error) {
    console.log(error, '黄历-错误信息')
  }
}

// 获取手账记录
const calendarRecord = ref([])
const getCalendarData = async (month_key) => {
	try {
		const { result } = await getCalendarRecord({ month_key, openid: userInfo.value.openid })
		calendarRecord.value = result?.calendar_content || []

    // 当前日期手账记录
    journal.value = calendarRecord.value.find(item => item.date === date.value) || {}

    // 在手账记录中有黄历信息的则直接展示，没有则从接口获取
    if (journal.value?.almanac) almanac.value = journal.value.almanac
    else getCalendarInfo()

    // 没有手账记录的时候，默认为编辑状态展示输入框
    if (!journal.value?.notes) {
      isEdit.value = true
      inputType.value = 'text'
    }
	} catch {}
}

onLoad((options) => {
  date.value = options?.date || null

  // 获取手账记录
  getCalendarData(options?.date.slice(0, 7))
})

const handleSaveAlmanac = async () => {
	if (journal.value.almanac) return
	const index = calendarRecord.value.findIndex(item => item.date === date.value)
	if (index === -1) {
		calendarRecord.value.push({
			date: date.value,
			almanac: almanac.value,
			notes: '',
			events: []
		})
	} else calendarRecord.value[index].almanac = almanac.value

	await saveCalendarRecord({
		openid: userInfo.value.openid,
		month_key: date.value.slice(0, 7),
		calendar_content: calendarRecord.value
	})
}

onUnload(async () => {
	console.log('onUnload')
	// 没有编辑手账时，只查看黄历的需要在返回上一页时保存黄历信息
	await handleSaveAlmanac()
})

const handleUpdateJournal = () => {
  isEdit.value = true
  inputType.value = 'textarea'
  notes.value = journal.value?.notes || ''
}

const handleInput = () => {
  if (!notes.value) inputType.value = 'textarea'
}

const handleCancel = () => {
  isEdit.value = !journal.value?.notes ? true : false
  inputType.value = 'text'
  notes.value = null
}

// 删除
const handleDelete = async () => {
  const index = calendarRecord.value.findIndex((item) => item.date === date.value)
  if (index === -1) return uni.showToast({ title: '删除失败，当前数据不存在', icon: 'none', duration: 2000 })
  calendarRecord.value.splice(index, 1)
  deleteDisabled.value = true
  disabled.value = true

  try {
    await saveCalendarRecord({ openid: userInfo.value.openid, month_key: date.value.slice(0, 7), calendar_content: calendarRecord.value })
    uni.showToast({ title: '删除成功', icon: 'none', duration: 2000 })
    setTimeout(() => {
			uni.navigateBack({
				delta: 1
			})
			disabled.value = false
      deleteDisabled.value = false
		}, 1000)
  } catch {
    deleteDisabled.value = false
    disabled.value = false
  }
}

// 保存
const handleSubmit = async () => {
  if (!notes.value) return uni.showToast({ title: '请输入要记录的内容', icon: 'none', duration: 2000 })
  disabled.value = true

  let list = []
  if (!calendarRecord.value.length) {
    // 新增手账
    list = [{ date: date.value, events: [], notes: notes.value, almanac: almanac.value }]
  } else {
    const index = calendarRecord.value.findIndex((item) => item.date === date.value)
    if (index > -1) {
      calendarRecord.value[index].notes = notes.value
      // 没有黄历信息的，保存黄历信息
      if (!calendarRecord.value[index].almanac) calendarRecord.value[index].almanac = almanac.value
    } else {
      calendarRecord.value.push({ date: date.value, events: [], notes: notes.value, almanac: almanac.value })
    }
    list = calendarRecord.value
  }
  const params = {
    openid: userInfo.value.openid,
    month_key: date.value.slice(0, 7),
    calendar_content: list
  }

  console.log(params, 'params')
  try {
    await saveCalendarRecord(params)
    uni.showToast({ title: '保存成功', icon: 'none', duration: 2000 })
    disabled.value = false
    handleCancel()
    getCalendarData(date.value.slice(0, 7))
  } catch {
    disabled.value = false
  }
}
</script>

<style lang="scss" scoped>
$commonColor: #c2a08c;
$size: 25px;

:deep {
	.uni-card {
		margin: 30rpx 0 !important;
	}
}

.journal {
	margin-top: 30rpx;
	padding-bottom: 100px;
	.title {
		color: #999;
		margin: 0 30px;
	}
	.description {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}
  &-content {
    background-color: #f1f1f1;
    padding: 30rpx;
    border-radius: 8px;
  }
}

.popupContent {
	position: relative;
	background-color: #fff;
	width: 80vw;
  margin: 0 auto;
	.content-box {
		height: 100%;
		border: 1px solid $commonColor;
		border-radius: 6px; 
	}
	.yangli {
		font-weight: bold;
		color: $commonColor;
		font-size: 30px;
	}
	.yinli {
		color: #7f7f7f;
		margin: 10px 0;
	}
	.center-box {
		border-top: 1px solid $commonColor;
		border-bottom: 1px solid $commonColor;
		.yi {
			width: $size;
			height: $size;
			background-color: #c39c87;
			border-radius: 50%;
			color: #fff;
			margin-right: 10px;
			font-size: 14px;
		}
		.ji {
			width: $size;
			height: $size;
			background-color: #bfbfbf;
			border-radius: 50%;
			color: #fff;
			margin-right: 10px;
			font-size: 14px;
		}
	}
	.bottom-box {
		display: flex;
		&-item {
			width: 33.3%;
			text-align: center;
			border-right: 1px solid $commonColor;
			&:nth-child(3n) {
				border-right: none;
			}
			.label {
				font-size: 17px;
			}
			.value {
				color: #7f7f7f;
				font-size: 14px;
				margin-top: 10px;
			}
			.padding {
				padding: 10px;
			}
			.border {
				border-top: 1px solid #c2a08c;
				height: 1px;
				width: 100%;
			}
		}
	}
	.luckyColor {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
	}
}
</style>