<template>
    <view class="container" style="paddingBottom:1rpx;">
      <u-navbar
			leftIconSize="40rpx"
			leftIconColor="#333333"
			title="心路历程"
		>
		</u-navbar>
      <view class="section">
        <view class="section-title">{{ title }}</view>
        <view class="form-view">
          <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="180rpx"
            :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
            <u-form-item label="标题" prop="name" required >
              <u--input v-model="form.name"  placeholder="请填写标题"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="类型" prop="typeName" required @click="handleShowTeam">
              <view class="input-with-arrow">
                <u--input v-model="form.typeName" readonly disabledColor="#ffffff" placeholder="请选择类型"
                  inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="记录时间" prop="createTime" required @click="selectDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.createTime" readonly disabledColor="#ffffff" placeholder="请选择记录时间"
                  inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="内容" prop="remark" required labelPosition="top">
              <view class="editor-container">
                <view class="editor-toolbar">
                  <view class="toolbar-item" @click="format('bold')">
                    <text class="iconfont">B</text>
                  </view>
                  <view class="toolbar-item" @click="format('italic')">
                    <text class="iconfont italic">I</text>
                  </view>
                  <view class="toolbar-item" @click="format('underline')">
                    <text class="iconfont underline">U</text>
                  </view>
                  <view class="toolbar-divider"></view>
                  <view class="toolbar-item" @click="insertImage">
                    <uni-icons type="image" size="16" color="#333333"></uni-icons>
                  </view>
                  <view class="toolbar-divider"></view>
                  <view class="toolbar-item" @click="undo">
                    <text class="iconfont">↶</text>
                  </view>
                  <view class="toolbar-item" @click="redo">
                    <text class="iconfont">↷</text>
                  </view>
                </view>
                <editor 
                  id="editor" 
                  class="editor-content"
                  :placeholder="'请填写内容'"
                  @ready="onEditorReady"
                  @input="onEditorInput"
                  @focus="editorFocus"
                  @blur="editorBlur"
                  :show-img-size="true"
                  :show-img-toolbar="true"
                  :show-img-resize="true"
                ></editor>
                <view class="editor-counter">
                  <text>{{ contentLength }}/20000</text>
                </view>
              </view>
            </u-form-item>
          </u--form>
          <view class="form-btn">
            <u-button type="primary" text="提交" @click="submit"></u-button>
          </view>
        </view>
      </view>
      <u-toast ref="uToast"></u-toast>
      <u-picker itemHeight="88" :show="showTeam" :columns="journeyTypeList" keyName="dictLabel" @cancel="handleCancel"
        @confirm="handleConfirm"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="datetime"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    </view>
  </template>
  
  <script setup>
  import {getHeartJourney, addHeartJourney, updateHeartJourney } from '@/api/invest/heartJourney'
  import { getDicts } from '@/api/system/dict/data.js'
  const { proxy } = getCurrentInstance()
  import dayjs from 'dayjs'
  import {onLoad,onReady} from "@dcloudio/uni-app";
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const datePickShow = ref(false)
const showTeam = ref(false)
const title = ref("心路历程")
const journeyTypeList = ref([])
const editorCtx = ref(null)
const contentLength = ref(0)
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const data = reactive({
  form: {},
  rules: {
          name: [{ type: 'string', required: true, message: '标题不能为空', trigger: ['change', 'blur'] }],
          createTime: [{ type: 'string', required: true, message: '记录时间不能为空', trigger: ['change', 'blur'] }],
          typeName: [{ type: 'string', required: true, message: '类型不能为空', trigger: ['change', 'blur'] }],
          remark: [{ type: 'string', required: true, message: '内容不能为空', trigger: ['change', 'blur'] }],
  }
})
const { form, rules} = toRefs(data)

onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="心路历程-修改"
       }else{
        title.value="心路历程-新增"
       }
      getDict()
  })
  onReady(() => {
    form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  })
  
  // 编辑器初始化完成
  function onEditorReady() {
    uni.createSelectorQuery().select('#editor').context((res) => {
      editorCtx.value = res.context
      // 如果是编辑模式，设置初始内容
      if (form.value.remark) {
        editorCtx.value.setContents({
          html: form.value.remark
        })
      }
    }).exec()
  }
  
  // 编辑器内容变化
  function onEditorInput(e) {
    // 获取HTML内容
    editorCtx.value.getContents({
      success: (res) => {
        form.value.remark = res.html
        // 计算内容长度（去除HTML标签）
        const text = res.text || ''
        contentLength.value = text.length
      }
    })
  }
  
  // 编辑器获得焦点
  function editorFocus() {
    // 可以添加焦点样式
  }
  
  // 编辑器失去焦点
  function editorBlur() {
    // 保存内容
    if (editorCtx.value) {
      editorCtx.value.getContents({
        success: (res) => {
          form.value.remark = res.html
        }
      })
    }
  }
  
  // 格式化文本
  function format(name, value) {
    if (!editorCtx.value) return
    
    editorCtx.value.format(name, value)
  }
  
  // 撤销
  function undo() {
    if (!editorCtx.value) return
    editorCtx.value.undo()
  }
  
  // 重做
  function redo() {
    if (!editorCtx.value) return
    editorCtx.value.redo()
  }
  
  // 插入图片
  function insertImage() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 显示加载提示
        uni.showLoading({
          title: '上传中...'
        })
        
        // 上传图片到服务器
        uni.uploadFile({
          url: proxy.$config.baseUrl + '/common/upload',
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          },
          success: (uploadRes) => {
            uni.hideLoading()
            
            try {
              const data = JSON.parse(uploadRes.data)
              if (data.code === 200) {
                // 获取图片URL
                const imageUrl = proxy.$config.baseUrl + data.fileName
                
                // 插入图片到编辑器
                if (editorCtx.value) {
                  editorCtx.value.insertImage({
                    src: imageUrl,
                    width: '100%',
                    height: 'auto',
                    success: () => {
                      uni.showToast({
                        title: '插入成功',
                        icon: 'success'
                      })
                    },
                    fail: (err) => {
                      console.error('插入图片失败', err)
                      uni.showToast({
                        title: '插入失败',
                        icon: 'none'
                      })
                    }
                  })
                }
              } else {
                uni.showToast({
                  title: data.msg || '上传失败',
                  icon: 'none'
                })
              }
            } catch (e) {
              console.error('解析上传结果失败', e)
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            uni.hideLoading()
            console.error('上传失败', err)
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (err) => {
        console.error('选择图片失败', err)
      }
    })
  }
  function  getDict() {
        // 类型
        getDicts('journey_type').then(res => {
        journeyTypeList.value =[res.data] 
      })
      if(form.value.id!=null){
        getHeartJourney(form.value.id).then(res => {
          form.value = res.data
           // 类型
        getDicts('journey_type').then(result => {
          form.value.typeName=dictStr(form.value.type, result.data)
      })
          // 如果编辑器已经初始化，设置内容
          if (editorCtx.value && form.value.remark) {
            editorCtx.value.setContents({
              html: form.value.remark
            })
          }
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleShowTeam() {
        if (journeyTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '类型为空  ', type: 'warning'
          })
        } else {
          showTeam.value = true
        }
      }
      function   handleConfirm(e) {
        form.value.typeName = e.value[0].dictLabel
        form.value.type = e.value[0].dictValue
        showTeam.value = false
      }
      function handleCancel() {
       showTeam.value = false
      }
      function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
			}
			function datePickConfirm(e) {
				form.value.createTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
				datePickShow.value = false
			}
      function submit() {
        // 提交前确保获取最新的编辑器内容
        if (editorCtx.value) {
          editorCtx.value.getContents({
            success: (res) => {
              form.value.remark = res.html
              // 执行表单验证和提交
              doSubmit()
            }
          })
        } else {
          doSubmit()
        }
      }
      
      function doSubmit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateHeartJourney(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/heartJourney/list` })
              }
            })
          })
          }else {
            addHeartJourney(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/heartJourney/list` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .section {
    margin: 24rpx;
    padding: 0;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;
  
    .section-title {
      padding: 16rpx 24rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      line-height: 1.2;
      font-size: 28rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      
      &::before {
        content: '';
        width: 6rpx;
        height: 28rpx;
        background: #ffffff;
        border-radius: 3rpx;
        margin-right: 12rpx;
      }
    }
  
    .form-view {
      padding: 24rpx;

      .input-with-arrow {
        position: relative;
        width: 100%;

        .arrow-icon {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          color: #c0c4cc;
          font-size: 20rpx;
          pointer-events: none;
          z-index: 10;
        }
      }

      .form-btn {
        padding-top: 16rpx;
      }
    }
  }
  
  .editor-container {
    width: 100%;
    border: 2rpx solid #e8edf3;
    border-radius: 12rpx;
    overflow: hidden;
    background: #ffffff;
    box-sizing: border-box;
    
    .editor-toolbar {
      display: flex;
      align-items: center;
      padding: 12rpx;
      background: #f8f9fa;
      border-bottom: 2rpx solid #e8edf3;
      flex-wrap: wrap;
      gap: 8rpx;
      
      .toolbar-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 56rpx;
        height: 56rpx;
        background: #ffffff;
        border-radius: 8rpx;
        border: 2rpx solid #e8edf3;
        transition: all 0.3s ease;
        
        &:active {
          transform: scale(0.95);
          background: #667eea;
          border-color: #667eea;
          
          .iconfont {
            color: #ffffff;
          }
        }
        
        .iconfont {
          font-size: 28rpx;
          font-weight: 600;
          color: #333333;
          
          &.italic {
            font-style: italic;
          }
          
          &.underline {
            text-decoration: underline;
          }
        }
      }
      
      .toolbar-divider {
        width: 2rpx;
        height: 40rpx;
        background: #e8edf3;
        margin: 0 4rpx;
      }
    }
    
    .editor-content {
      width: 100%;
      min-height: 500rpx;
      padding: 20rpx;
      font-size: 28rpx;
      line-height: 1.6;
      background: #ffffff;
      box-sizing: border-box;
    }
    
    .editor-counter {
      padding: 12rpx 20rpx;
      background: #f8f9fa;
      border-top: 2rpx solid #e8edf3;
      text-align: right;
      
      text {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }
  </style>
  
  <style lang="scss">
  .form-btn .u-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    border: none !important;
    border-radius: 24rpx !important;
    height: 80rpx !important;
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
  }
  
  .form-btn .u-button__text {
    font-size: 30rpx !important;
    font-weight: 500 !important;
    letter-spacing: 2rpx !important;
  }
  </style>