<template>
  <div>
    <el-form ref="commentRef" :model="cmts">
      <el-form-item label="个人意见">
        <el-input
          type="textarea"
          :model-value="cmts?.userComments"
          :rows="5"
          show-word-limit
          :maxlength="1000"
          :readonly="!props.canEdit"
          @update:modelValue="onUpdateUserComments"
        ></el-input>
      </el-form-item>
      <el-form-item label="意见附件：">
        <accessory-uploader :model-value="cmts?.userAccessoryList" @update:modelValue="onUpdateUserAccessories" category="workflow" :readonly="!props.canEdit" />
      </el-form-item>

      <el-form-item label="部门意见" v-if="props.deptShow">
        <el-input
          type="textarea"
          :model-value="cmts?.deptComments"
          :rows="5"
          show-word-limit
          :maxlength="1000"
          :readonly="!props.canEdit"
          @update:modelValue="onUpdateDeptComments"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门附件：" v-if="props.deptShow">
        <accessory-uploader :model-value="cmts?.deptAccessoryList" @update:modelValue="onUpdateDeptAccessories" category="workflow" :readonly="!props.canEdit" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import type { Accessory, CommentsDto } from '@cacp/ui'
import AccessoryUploader from '@/components/accessory/AccessoryUploader.vue'

const commentRef = ref<FormInstance>()

const props = defineProps<{
  comments: CommentsDto
  canEdit: boolean
  deptShow: boolean
}>()
const emits = defineEmits<{
  (e: 'onUpdateComments', comments: CommentsDto): void
}>()

const cmts = ref<CommentsDto>()
watchEffect(() => {
  cmts.value = cloneDeep(props.comments)
  // cmts.value = props.comments
})

function onUpdateUserComments(val: string) {
  cmts.value!.userComments = val
  cmts.value!.userModified = true
  emits('onUpdateComments', cmts.value!)
}

function onUpdateDeptComments(val: string) {
  cmts.value!.deptComments = val
  cmts.value!.deptModified = true
  emits('onUpdateComments', cmts.value!)
}

function onUpdateUserAccessories(val: Array<Accessory>) {
  cmts.value!.userAccessoryList = val
  cmts.value!.userModified = true
  emits('onUpdateComments', cmts.value!)
}

function onUpdateDeptAccessories(val: Array<Accessory>) {
  cmts.value!.deptAccessoryList = val
  cmts.value!.deptModified = true
  emits('onUpdateComments', cmts.value!)
}
</script>
