<template>
  <ElDialog
    v-model="dialogVisible"
    title="新增跟进记录"
    width="50%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="auto">
      <ElFormItem :label="selectLabelArr[0]" prop="first_id">
        <ElSelect v-model="formData.first_id">
          <ElOption
            v-for="item in selectList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="selectLabelArr[1]" prop="second_id">
        <ElSelect v-model="formData.second_id">
          <ElOption
              v-for="item in secondSelectList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="微信聊天记录" prop="chat_imgs">
        <el-upload
            :file-list="fileList"
            name="follow"
            :action="uploadServer"
            list-type="picture-card"
            :limit="12"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :headers="{Authorization: useUserStore().accessToken}"
            drag
        >
          <i class="el-icon-plus"></i>
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div style="color:red">支持拖拽上传，限 jpg、png、jpeg 图片，最大{{maxFileSizeMB}}M，最多12张</div>
          </template>
        </el-upload>
        <!--    图片预览    -->
        <el-image-viewer
            v-if="picDialogVisible"
            :url-list="[dialogImageUrl]"
            show-progress
            :initial-index="0"
            @close="picDialogVisible = false"
        />
      </ElFormItem>
      <ElFormItem label="跟进详情" prop="detail">
        <!-- 富文本编辑器 -->
        <ArtWangEditor class="el-top" v-model="formData.detail" height="250px"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import {computed, ref} from 'vue'
  import { useUserStore } from '@/store/modules/user'
  import { Plus } from '@element-plus/icons-vue'
  import {ElMessage, ElMessageBox, UploadProps, UploadUserFile} from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import {commonApi} from "@/api/commonApi";

  interface Props {
    visible: boolean
    type:Api.FollowTye
    userData?: any
    first_id?: number
    second_id?: number
    selectList: Api.Common.SelectRelationInfo[]
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()
  const uploadServer = computed(() => import.meta.env.VITE_API_URL + import.meta.env.VITE_UPLOAD_URL)

  const fileList = ref<UploadUserFile[]>([])

  const dialogImageUrl = ref('')
  const picDialogVisible = ref(false)

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const selectLabelArr = computed(() => {
    return {
      'school' : ['校园（园区）', '校方关系人'],
      'canteen' : ['校园（园区）', '食堂'],
      'company' : ['餐饮公司', '餐饮公司方关系人'],
    }[props.type]
  })

  // 表单实例
  const formRef = ref<FormInstance>()

  let defalutValue = {
    first_id: null,
    second_id: null,
    chat_imgs: [],
    detail: '',
    type: props.type
  }
  // 表单数据
  const formData = reactive<Form.Follow>({...defalutValue})

  // 表单验证规则
  const rules: FormRules = {
    first_id: [
      { required: true, message: '请选择' + selectLabelArr.value[0], trigger: 'blur' },
    ],
    second_id: [
      { required: true, message: '请选择' + selectLabelArr.value[1], trigger: 'blur' },
    ],
    detail: [
      { required: true, message: '请填写详情', trigger: 'blur' },
    ],
  }

  const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
    let upName = uploadFile.response ? uploadFile.response.data.name : uploadFile.name
    commonApi.delImg(upName)
    for (let i = 0; i < formData.chat_imgs.length; i++) {
      if (formData.chat_imgs[i] === upName) {
        formData.chat_imgs.splice(i, 1)
        break
      }
    }

  }
  const maxFileSizeMB = 3

  const beforeUpload: UploadProps['onChange'] = (uploadFile) => {
    if (uploadFile.size && uploadFile.size > 1024 * 1024 * maxFileSizeMB) {
      ElMessage.error('上传图片大小不能超过2M')
      return false
    }
    if (!uploadFile.type.startsWith('image/')) {
      ElMessage.error('只能上传图片文件')
      return false
    }
    return true
  }

  const handleSuccess = (response:any, uploadFile: UploadFile) => {
    if (response.code === 200) {
      formData.chat_imgs.push(response.data.name)
      ElMessage.success('上传成功!')
    } else {
      fileList.value = fileList.value.filter((file) => file.name !== uploadFile.name)
      ElMessage.error(response.msg)
    }
  }

  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    picDialogVisible.value = true
  }

  const secondSelectList = computed(() => {
    if (formData.first_id) {
      let tmp = props.selectList.find(item => item.id === formData.first_id)
      if (tmp && tmp.children) {
        if (!tmp.children.find(item => item.id === formData.second_id)) {
          formData.second_id = null
        }
        return tmp.children
      }
    }
    formData.second_id = null
    return []
  })

  // 统一监听对话框状态变化
  watch(
      () => [props.visible, props.type, props.userData],
      ([visible]) => {
        if (visible) {
          formData.first_id = props.first_id || null
          formData.second_id = props.second_id || null
        }
      },
      { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        commonApi.follow(formData).then(() => {
          ElMessage.success('提交成功')
          Object.assign(formData, defalutValue)
          formData.chat_imgs = [];
          fileList.value = []
          console.log(`%c formData == `, 'background:#41b883 ; padding:1px; color:#fff', formData);
          dialogVisible.value = false
          emit('submit')
        })
      }
    })
  }
</script>
