/**
 * v-upload 图片上传
 */

import axios from 'axios';
import config from '@/config'
const maxSize = 2 * 1024 * 1024; //5M
axios.defaults.withCredentials = true

export default {
    inserted: function(el, binding) {
        el.addEventListener("change", function() {
            binding.value.loading = true
            if (el.files[0].size > maxSize) {
                binding.value.$tips({ type: 'warning', message: '上传图片不能大于2M' });
                return;
            }
            binding.value.disabled = true;
            let formData = new FormData();
            formData.append(binding.value.fileType, el.files[0]);
            formData.append('requestProject', 'gic-web');
            axios.post(config.api + binding.value.url, formData)
              .then(res => {
                console.log(res)
                binding.value.loading = false;
                el.value = "";
                if (res.data.errorCode === 0) {
                    if (binding.value.url === '/api-plug/upload-img') {
                        binding.value.model.code = res.data.result[0].imageFiledCode,
                            binding.value.model.imgUrl = res.data.result[0].qcloudImageUrl
                    } else {
                        binding.value.model.code = res.data.result.imageFiledCode,
                            binding.value.model.imgUrl = res.data.result.qcloudImageUrl
                        binding.value.model.mediaId = res.data.result.imageMediaId
                        binding.value.model.wxImg = res.data.result.wxImg || res.data.result.imageUrl || ''
                    }
                    binding.value.$tips({ type: 'success', message: '上传成功' });
                } else {
                    binding.value.$tips({ type: 'error', message:res.data.message || '上传失败' });
                }
                binding.value.disabled = false;
            }).catch(error => {
                binding.value.loading = false;
                binding.value.disabled = false;
                binding.value.$tips({ type: 'error', message: error.msg || '上传失败' });
            });
        });
    }
}
