odoo.define('jzjx_project.button', function (require) {
    "use strict";
    const FormController = require('web.FormController');
    const session = require('web.session');
    const framework = require('web.framework');

    FormController.include({
        events: _.extend({}, FormController.prototype.events, {
            'click .test_open': '_onClickDocumentsUpload',
        }),

        _onClickDocumentsUpload(ev) {
            console.log(ev);
            console.log("===================")
                        ev.preventDefault();
            const context = this.model.get(this.handle, { raw: true }).getContext();
            this._uploadFilesHandler(true)(ev);
            console.log(ev)
        },

        _uploadFilesHandler(multiple) {
            const EXTRAL_WHITELIST_EXTENSIONS = ['dwg', 'dxf', 'step', 'sldprt', 'sldasm'];
            // console.log(ev)
            // console.log("=====================================")

            return (ev) => {
                const recordId = ev.data ? ev.data.id : undefined;
                const $uploadInput = this.hiddenUploadInputFile
                    ? this.hiddenUploadInputFile.off('change')
                    : (this.hiddenUploadInputFile = $('<input>', { type: 'file', name: 'files[]', class: 'o_hidden' }).appendTo(this.$el));
                $uploadInput.attr('multiple', multiple ? true : null);
                const cleanup = $.prototype.remove.bind($uploadInput);
                $uploadInput.on('change', async changeEv => {

                    // START
                    /**
                     * 区分文件类型，以存放到不同的服务器
                     */
                    let extra_files = [];
                    let odoo_files = [];
                    for (const file of changeEv.target.files) {
                        let split_temp = file.name.split('.');
                        if (split_temp.length > 1) {
                            var file_extension = split_temp.pop();
                        } else {
                            var file_extension = '';
                        }
                        if (EXTRAL_WHITELIST_EXTENSIONS.includes(file_extension.toLowerCase())) {
                            extra_files.push(file);
                        } else {
                            odoo_files.push(file);
                        }
                    }
                    if (extra_files.length > 0){
                        // console.log("extra_files", extra_files)
                        await this._uploadFiles2Minio(extra_files);
                    }
                    // await this._uploadFiles(odoo_files, { recordId }).finally(cleanup);
                    // END

                    // await this._uploadFiles(changeEv.target.files, { recordId }).finally(cleanup);
                    changeEv.target.value = null; // 上传完成后 情况 input 值，下次上传同样的文件 就仍然可以出发 change 事件
                });
                this._promptFileInput($uploadInput);
            };
        },

        async _uploadFiles2Minio(files) {
            let self = this;
            framework.blockUI();
            await self.keepRun(3, files, self._uploadToMinIoHandler.bind(self))
            framework.unblockUI();
            await self.reload();
        },

        keepRun(limit, list, workFn) {
            return new Promise(resolve => {
                let running = 0,
                    temList = list.slice(),
                    next = function (item) {
                        workFn(item).then(result => {
                            if (result) {
                                running--;
                                if (running !== 0 || temList.length !== 0) {
                                    launcher();
                                } else {
                                    resolve("complete");
                                }
                            }
                        }).catch(err => {
                            running--;
                        });
                    },
                    launcher = function () {
                        while (running < limit && temList.length) {
                            let item = temList.shift();
                            next(item);
                            running++;
                        }
                    };
                launcher();
            });
        },

        _promptFileInput($uploadInput) {
            $uploadInput.click();
        },

        _uploadToMinIoHandler(file) {
            let self = this;
            return new Promise((resolve, reject) => {
                self._onUploadToMinIoHandler(file).then(function (result) {
                    if (result.code === 200) {
                        result.data.fname = file.name;
                        resolve(result.data);
                    } else {
                        reject(result.data);
                    }
                });
            });
        },

        _onUploadToMinIoHandler: async function (file) {
            /**
             * 文档直传MinIO
             * */
            let self = this;
            let web_base_url = session['web.base.url'];

            const formdata = new FormData();
            formdata.append('file', file);
            formdata.append('filePath', web_base_url.replace(/^https?:\/\//, '').replace("/", ""));

            return new Promise((resolve, reject) => {
                $.ajax({
                    type: "POST",
                    enctype: 'multipart/form-data',
                    url: "http://123.129.207.22:8088/resource/oss/unauthorized/upload",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    cache: false,
                    timeout: 600000,
                    success: async function (result) {
                        if (result.code === 200) {
                            const { data } = result;
                            // console.log("data", data)
                            await self._saveExtraFileLink(file.name, data.ossId, data.url);
                            await self._uploadFileUrl(data.ossId, data.url);
                            resolve(result);
                        } else {
                            console.log("result", result)
                            self.do_notify("上传失败", `${file.name} 上传失败\n${result.msg}`, false);
                            reject(result);
                        }
                    },
                    error: function (e) {
                        console.log("onload error", e)
                        let reject_data = { code: 1, msg: "error", data: e };
                        self.do_notify("上传失败", `${file.name} 上传失败\n${e}`, false);
                        reject(reject_data);
                    }
                });
            });
        },

        async _saveExtraFileLink(fname, unikey, flink) {
            /**
             * 保存文件地址到ODOO
             * */
            // let folder_id = this.searchModel.get('selectedFolderId');
            // console.log("fname, unikey, flink", fname, unikey, flink);

            var data_dict = { name: fname, url: flink, folder_id: 2, unikey: unikey, type: 'url' }
            const record = this.model.localData[this.handle]
            console.log(record)
            console.log(record.data.id)
            var res_id = record.data.id
            await this._rpc({
                model: 'roke.production.task',
                method: 'write_documents',
                args: [,data_dict, res_id],
                // kwargs: { context: session.user_context },
            });

        },

        _uploadFileUrl: function (unikey, flink) {
            /**
             * 上传文件地址，以保存ocf地址
             * */
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "http://123.129.207.22:8088/cad/uploadFileUrl",
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json',
                    data: JSON.stringify({
                        "ossId": unikey,
                        "url": flink
                    }),
                    success: function (data) {
                        console.log("success", data);
                        resolve(data);
                    },
                    error: function (data) {
                        console.log("ERROR ", data);
                        reject(data);
                    }
                });
            });
        },


    })
});









