import { getSubmitTicket } from '../../api/work'
import request from '../../utils/request'
export default {
    data() {
        return {
            ruleForm: {
                // email: '',
                desc: '',
                files: '',

            },
            rules: {
                // email: [
                //     { required: true, message: '请输入邮箱', trigger: 'blur' },
                //     { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }

                // ],
                desc: [
                    { required: true, message: this.$t(`work.problemDescription`), trigger: 'blur' }
                ],


            },
            labelPosition: "top",
            //上传后的文件列表
            fileList: [],
            // 允许的文件类型
            fileType: ["jpg", "jpeg", "png", "mp3", "aif", "aiff", "wav", "wma", "mp4", "avi", "rmvb",],
            // 运行上传文件大小，单位 M
            fileSize: 20,
            // 附件数量限制
            fileLimit: 3,
            //请求头
            headers: { "Content-Type": "multipart/form-data" },
            FormDatas: null,
            fileName: [],
            filesId: [],
            submitWorkOrderLoading:false,
        };
    },
    watch: {
   
        "$i18n.locale": function(){
          this.translate();
          
        }
      },
    mounted(){
       
    },
    methods: {
        translate() {
            this.rules = {
              // type: "email", 
              desc: [
                { required: true, message: this.$t(`work.problemDescription`), trigger: 'blur' }
            ],
            }
          },
        async fetchSubmitWork(params) {
            this.submitWorkOrderLoading =true
            const res = await getSubmitTicket(params)
            if (res.code == 200) {
                this.$message({
                    message: res.msg,
                    type: 'success',
                    showClose: true,
                })

                for (const key in this.ruleForm) {
                    this.ruleForm[key] =""
                }

                this.fileList=[]
            }
            this.submitWorkOrderLoading =false
            

        },
        submitForm() {
           
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    console.log("进来？");
                    
                    this.submitWorkOrderLoading =true
                    //上传文件         
                    if (this.fileList[0]) {
                        //上传文件的需要formdata类型;所以要转
                        this.FormDatas = new FormData()
                        this.fileList.forEach(fileItem => {

                            this.FormDatas.append('file', fileItem);

                        })

                        // 上传选择附件     
                        this.$axios({
                            method: 'post',
                            url: `${request.defaults.baseURL}pool/ticket/uploadFile`,
                            headers: this.headers,
                            timeout: 30000,
                            data: this.FormDatas,
                        }).then(res => {
                            console.log(res,"文件返回");
                            if (res.status == 200 && res.data.code != 200) {
                                this.$message.error(res.data.msg);

                                return
                            }
                            
                            this.ruleForm.files = res.data.data.id
                            if (this.ruleForm.files) {//成功拿到返回ID
                               this.fetchSubmitWork(this.ruleForm)
                            }

                        



                        })
                    } else {

                        this.fetchSubmitWork(this.ruleForm)

                    }
                } 
            });

            this.submitWorkOrderLoading =false
        },
  
        //超出文件个数的回调
        handleExceed() {
            this.$message({
                type: 'warning',
                message: this.$t(`work.notSupported4`)
            }); return
        },
        //上传文件的事件
        uploadFile(item) {
            this.fileItem = item

            this.fileList.push(item.file);
            this.fileName.push(item.file.name)

        },
        //上传成功后的回调
        handleSuccess() {

        },
        //下载附件
        handelDownload(id) {
            if (id) {
                this.downloadUrl = ` ${request.defaults.baseURL}ticket/downloadFile?ids=${id}`

                let a = document.createElement(`a`)
                a.href = this.downloadUrl
                a.click()
            }

        },
        //上传了的文件给移除的事件，
        handleRemove(file, fileList) {

            let nameIndex = this.fileName.indexOf(file.name); // 获取第一个重复元素的索引
            if (nameIndex !== -1) {
                this.fileName.splice(nameIndex, 1); // 删除第一个重复元素
            }




            let index = this.fileList.indexOf(file); // 获取第一个重复元素的索引

            if (index !== -1) {
                this.fileList.splice(index, 1); // 删除第一个重复元素
            }



        },


        //上传文件之前
        beforeUpload(file) {
            // 校验文件类型和大小
            const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
            const isTypeValid = this.fileType.includes(fileType);
            const isSizeValid = file.size / 1024 / 1024 <= this.fileSize;
            if (!isTypeValid) {//不支持的文件类型
                this.$message.error(`${this.$t(`work.notSupported`)}：${fileType}`);
                return false;
            }
            if (!isSizeValid) {//文件大小不能超过
                this.$message.error(`${this.$t(`work.notSupported2`)}${this.fileSize} MB.`);
                return false;
            }

        },

        handelChange(file, fileList) { //控制显示上传显示列表   
            // 校验文件类型和大小
            const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
            const isTypeValid = this.fileType.includes(fileType);
            const isSizeValid = file.size / 1024 / 1024 <= this.fileSize;
            if (!isTypeValid) {//不支持的文件类型
                this.$message.error(`${this.$t(`work.notSupported`)} ${fileType}`);
                this.fileList = this.fileList.filter(item => item.name != file.name);
                return false;
            }
            if (!isSizeValid) {//文件大小不能超过
                this.fileList = this.fileList.filter(item => item.name != file.name);
                this.$message.error(`${this.$t(`work.notSupported2`)} ${this.fileSize} MB.`);
                return false;
            }
            let flag = this.fileList.some(item => item.name == file.name)

            if (flag) {
                this.$message.warning(this.$t(`work.notSupported3`));
                this.$refs.upload.handleRemove(file)

                return false
            }
            this.fileName.push(file.name)
            this.fileList.push(file.raw)

        },













    }

}