<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="MediaManageForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="名称" v-bind="validateInfos.name" id="MediaManageForm-name" name="name">
                <a-input v-model:value="formData.name" placeholder="请输入名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注" v-bind="validateInfos.descr" id="MediaManageForm-descr" name="descr">
                <a-textarea v-model:value="formData.descr" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="系统功能" v-bind="validateInfos.sysFunc" id="MediaManageForm-sysFunc" name="sysFunc">
                <j-dict-select-tag type='list' v-model:value="formData.sysFunc" @change="sysFuncChanged"
                  dictCode="sys_function" placeholder="请选择系统功能" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="文件类型" v-bind="validateInfos.fileType" id="MediaManageForm-fileType" name="fileType">
                <j-dict-select-tag type='list' v-model:value="formData.fileType" dictCode="file_type"
                  placeholder="请选择文件类型" allowClear @change="handleFileTypeChange" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="资源类型" v-bind="validateInfos.izNetUrl" id="MediaManageForm-izNetUrl" name="izNetUrl">
                <j-dict-select-tag type='radio' v-model:value="formData.izNetUrl" dictCode="iz_net_url" allowClear
                  :disabled="formData.sysFunc == 'directive'" @change="handleFileTypeChange" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item :label="handleFileUploadLableName(formData.izNetUrl)" v-bind="validateInfos.filePath"
                id="MediaManageForm-filePath">
                <div v-if="formData.fileType && formData.izNetUrl == 'net'"
                  style="color: #999; margin-bottom: 8px; padding-left: 8px;">
                  当前协议域名为{{ urlPrefix }}
                </div>
                <a-textarea v-if="formData.fileType && (formData.izNetUrl == 'net' || formData.izNetUrl == 'full_url')"
                  v-model:value="formData.filePath" :rows="2" placeholder="请输入资源地址" style="margin-bottom: 10px;" />
                <!-- 未选择文件类型时的提示 -->
                <div v-if="!formData.fileType" class="upload-tip">
                  <span style="color: red; line-height: 32px;">请先选择文件类型</span>
                </div>

                <!-- 图片上传组件 -->
                <template v-if="formData.fileType === 'image'">
                  <j-image-upload v-if="formData.izNetUrl == 'local'" v-model:value="formData.filePath" :number="1"
                    multiple="1" :fileSize="10" accept=".png,.jpg,.jpeg" @change="handleFileChange">
                  </j-image-upload>
                  <!-- 图片预览 -->
                  <div v-if="formData.filePath && formData.izNetUrl != 'local'" class="media-preview">
                    <img :src="transUrl(formData)" style="max-width: 100%; max-height: 300px;">
                  </div>
                </template>

                <!-- 视频上传组件 -->
                <template v-if="formData.fileType === 'video'">
                  <j-upload v-if="formData.izNetUrl == 'local'" v-model:value="formData.filePath" :fileSize="100"
                    :multiple="false" :maxCount="1" accept=".mp4" @change="handleFileChange">
                  </j-upload>
                  <!-- 视频预览 -->
                  <div v-if="formData.filePath && previewShow" class="media-preview">
                    <video controls style="max-width: 100%; max-height: 300px;">
                      <source :src="transUrl(formData)" type="video/mp4">
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                </template>

                <!-- 音频上传组件 -->
                <template v-if="formData.fileType === 'audio'">
                  <j-upload v-if="formData.izNetUrl == 'local'" v-model:value="formData.filePath" :fileSize="50"
                    :multiple="false" :maxCount="1" accept=".mp3" @change="handleFileChange">
                  </j-upload>
                  <!-- 音频预览 -->
                  <div v-if="formData.filePath && previewShow" class="media-preview">
                    <audio controls style="width: 100%;">
                      <source :src="transUrl(formData)" type="audio/mpeg">
                      您的浏览器不支持音频播放
                    </audio>
                  </div>
                </template>

                <!-- 文档上传组件 -->
                <j-upload v-if="formData.fileType === 'document'" v-model:value="formData.filePath" :fileSize="20"
                  :multiple="false" :maxCount="1" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt"
                  @change="handleFileChange">
                </j-upload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, watch } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../MediaManage.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
  urlPrefix: { type: String, default: '' },
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  name: '',
  descr: '',
  sysFunc: '',
  fileType: '',
  filePath: '',
  izNetUrl: 'local',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  fileType: [{ required: true, message: '请输入文件类型!' },],
  filePath: [{ required: true, message: '请上传文件/填写资源路径' },],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 文件类型变化处理
const handleFileTypeChange = () => {
  // 切换文件类型时清空已上传的文件
  formData.filePath = '';
};

// 文件上传变化处理
const handleFileChange = (value) => {
  formData.filePath = value;
};

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  //如果是相对网络路径  需要根据机构中配置的协议+域名结尾是否有斜杠处理filePath
  if (model.izNetUrl == 'net') {
    if (props.urlPrefix.endsWith('/')) {
      if (model.filePath.startsWith('/')) {
        model.filePath = model.filePath.replace('/', '')
      }
    } else {
      if (!model.filePath.startsWith('/')) {
        model.filePath = '/' + model.filePath
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

function handleFileUploadLableName(v_) {
  if (v_ == 'local') {
    return '文件上传'
  } else if (v_ == 'net') {
    return '网络资源路径(不包含协议域名)'
  } else if (v_ == 'full_url') {
    return '完整网络资源地址'
  } else {
    return '文件上传'
  }

}
const previewShow = ref(false)
watch(
  () => formData.filePath,
  (newVal, oldVal) => {
    previewShow.value = false
    setTimeout(() => {
      previewShow.value = true
    }, 500)
  },
  {
    immediate: false,
    deep: true
  }
);

function transUrl(record) {
  if (record.izNetUrl == 'local') {
    return getFileAccessHttpUrl(record.filePath)
  } else if (record.izNetUrl == 'net') {
    return props.urlPrefix + record.filePath
  } else {
    return record.filePath
  }
}

/**
 * 系统功能变更
 */
function sysFuncChanged() {
  if (formData.sysFunc == 'directive') {
    formData.izNetUrl = 'net'
  }
}

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}

.upload-tip {
  display: flex;
  align-items: center;
  height: 32px;
}

.media-preview {
  margin-top: 16px;
  padding: 8px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>