<template>
    <view class="rf-category" style="position: relative;">
        <u-toast ref="uToast" />
        <!--搜索导航栏-->
        <view class="icoStyle">
            <u-navbar :back-text="i18n('return')" :title="i18n('resourceApplicationResearch')" :background="barBackground"
                      back-icon-color="white" title-color="white" :back-text-style="backStyle"></u-navbar>
        </view>
        <view class="content">
            <u-form :model="form" ref="uForm" label-position="top" style="padding: 0 30upx;margin-top: 20upx;">
                <!--参观人数-->
                <u-form-item required :label="i18n('resourceAttendance')" prop="numberOfVisitors">
                    <u-input v-model="form.numberOfVisitors" :placeholder="i18n('resourcePleaseEnterTheNumberOfVisitors')"/>
                </u-form-item>
                <!--参观时间-->
                <u-form-item required :label="i18n('resourceVisitTime')" prop="date">
                    <calendar v-model="show" ref="calendar" @change="change" mode="range"
                                :start-text="i18n(startText)" :end-text="i18n(endText)" :toolTip="i18n(toolTip)" max-date="2030-12-31"
                                :range-color="rangeColor" :range-bg-color="rangeBgColor" :active-bg-color="activeBgColor" :btn-type="btnType"
                                :textzhi="$i18n.locale=='zh'?'至':' To '"
                    >
                    </calendar>
<!--                    <u-input id="inputDate" v-model="form.date" @focus="inputDate" :placeholder="$i18n.locale=='zh'?'请输入参观时间':'Please enter the time of visit'" />-->
                    <u-input type="select" id="inputDate" v-model="form.date" @click="inputDate" :placeholder="$i18n.locale=='zh'?'请输入参观时间':'Please enter the time of visit'" />
                </u-form-item>
                <!--联系人-->
                <u-form-item required :label="i18n('resourceTheContact')" prop="contactsName">
                    <u-input v-model="form.contactsName" :placeholder="i18n('resourcePleaseEnterYourName')"/>
                </u-form-item>
                <!--申请单位-->
                <u-form-item required :label="i18n('resourceToApplyForTheUnit')" prop="affiliatedUnitName">
                    <u-input v-model="form.affiliatedUnitName" :placeholder="i18n('resourcePleaseEnterTheUnitName')"/>
                </u-form-item>
                <!--联系电话-->
                <u-form-item required :label="i18n('resourceContactPhoneNumber')" prop="contactsNumber">
                    <u-input v-model="form.contactsNumber" :placeholder="i18n('resourcePleaseEnterYourContactInformation')" type="number"/>
                </u-form-item>
                <!--邮箱-->
                <u-form-item required :label="i18n('resourceEmail')" prop="contactsEmail">
                    <u-input v-model="form.contactsEmail" :placeholder="i18n('resourcePleaseEnterEmailAddress')"/>
                </u-form-item>
                <!--其他说明-->
                <u-form-item :label="i18n('resourceOtherInstructions')">
                    <u-input v-model="form.otherInstructions" :placeholder="i18n('resourcePleaseEnterAdditionalInstructions')"/>
                </u-form-item>
                <!--附件-->
                <!--<u-form-item :label="i18n('resourceTheAttachment')" label-width="150">
&lt;!&ndash;                    <u-upload :action="action" :file-list="fileList" max-count="1"></u-upload>&ndash;&gt;
                    <view v-show="!form.file" style="height: 66upx;width: 66upx;background-color: #aaaaaa;border-radius: 20upx;"  @click="addFile">
                        <u-icon name="plus" color="white" size="66"></u-icon>
                    </view>
                    <view v-show="form.file" style="width: 100%;height: 70upx;border-bottom: 1px solid rgb(192, 196, 204);">

                    </view>
                </u-form-item>-->
            </u-form>
            <view style="padding: 40upx 60upx;">
                <u-button :action="action" :file-list="fileList" type="primary" shape="circle" @click="submitApply">{{i18n('resourceSubmit')}}</u-button>
            </view>
        </view>
    </view>
</template>

<script>
    import rfSearchBar from '@/components/rf-search-bar';
    import calendar from './calendar';
    export default {
        data() {
            return {
                // bar
                barBackground: {
                    backgroundImage: 'linear-gradient(270deg, #4BC0E2 0%, #538BE7 100%)',
                },
                backStyle: {
                    color: '#fff'
                },
                // 字典
                classify1:'',
                classify2:'',
                // form
                form:{
                    numberOfVisitors:'',
                    date:'',
                    dateOfVisitors:'',
                    startDateOfVisitors:'',
                    endDateOfVisitors:'',
                    contactsName:'',
                    affiliatedUnitName:'',
                    contactsNumber:'',
                    contactsEmail:'',
                    otherInstructions:'',
                    file:'',
                    researchResourcesEntityId:''
                },
                baseResearchApplication: {
                    numberOfVisitors:'',
                    startDateOfVisitors:'',
                    endDateOfVisitors:'',
                    contactsName:'',
                    affiliatedUnitName:'',
                    contactsNumber:'',
                    contactsEmail:'',
                    otherInstructions:'',
                    file:'',
                    researchResourcesEntityId:''
                },
                formRules: {
                    numberOfVisitors: [
                        {
                            required: true,
                            message: this.i18n('resourcePleaseEnterTheNumberOfVisitors'),
                            trigger: ['change','blur'],
                        }
                    ],
                    date: [
                        {
                            required: true,
                            message: this.$i18n.locale=='zh'?'请输入参观时间':'Please enter the time of visit',
                            trigger: ['change','blur'],
                        }
                    ],
                    contactsName: [
                        {
                            required: true,
                            message: this.i18n('resourcePleaseEnterYourName'),
                            trigger: ['change','blur'],
                        }
                    ],
                    affiliatedUnitName: [
                        {
                            required: true,
                            message: this.i18n('resourcePleaseEnterTheUnitName'),
                            trigger: ['change','blur'],
                        }
                    ],
                    contactsNumber: [
                        {
                            required: true,
                            message: this.i18n('resourcePleaseEnterYourContactInformation'),
                            trigger: ['change','blur'],
                        }
                    ],
                    contactsEmail: [
                        {
                            required: true,
                            message: this.i18n('resourcePleaseEnterEmailAddress'),
                            trigger: ['change','blur'],
                        }
                    ],
                },
                action: 'http://www.example.com/upload',
                fileList: [],
                // 日期选择
                show: false,
                startText: 'resourceStart',
                endText: 'resourceEnd',
                toolTip:'resourceSelectTime',
                rangeColor: '#2979ff',
                rangeBgColor: 'rgba(41,121,255,0.13)',
                activeBgColor: '#2979ff',
                btnType: 'primary',
                // route
                entityId:'',
                name:'',
                flag:'',
            }
        },
        components: { rfSearchBar , calendar },
        onReady() {
            this.$refs.uForm.setRules(this.formRules);
        },
        onLoad:function(options){
            this.entityId = options.entityId;
            this.name = options.name;
            this.flag = options.flag;
        },
        async onShow() {
            await this.getDict();
        },
        computed:{
            token(){
                return 'Bearer '+uni.getStorageSync('Auth-Token');
            }
        },
        methods: {
            async getDict(){
                const res = await this.$myRequest({
                    url: '/sys/sysDicts',
                    data: {
                        type:this.$i18n.locale=="zh"?'RESEARCH_RESULT_TYPE_DICT,RESEARCH_RESOURCE_TYPE_DICT':'RESEARCH_RESULT_TYPE_DICT_EN,RESEARCH_RESOURCE_TYPE_DICT_EN',
                    }
                });
                if (res.data) {
                    let both={
                        label:this.$t('common.All'),
                        value:null
                    };
                    this.classify1=res.data[0];
                    this.classify2=res.data[1];
                    this.classify1.unshift(both);
                    this.classify2.unshift(both);
                }
            },
            // 输入时间
            inputDate(){
                this.show = true;
            },
            change(e) {
                this.form.startDateOfVisitors = e.startDate;
                this.form.endDateOfVisitors = e.endDate;
                this.form.date = e.startDate + " - " + e.endDate;
                let inputDate = document.getElementById('inputDate');
                inputDate = inputDate.childNodes[0].childNodes[0].childNodes[1];
            },
            upload(){
                uni.chooseFile({
                    count: 1,
                    extension:['.pdf'],
                    success: function (res) {
                        console.log('res');
                        console.log(res);
                    }
                });
            },
            //提交申请
            date(date){
                let time = new Date(date)
                return time.getTime()
            },
            async submitApply(){
                const that = this;
                this.$refs.uForm.validate(valid => {
                    if (valid) {
                        that.baseResearchApplication.numberOfVisitors = that.form.numberOfVisitors;
                        that.baseResearchApplication.startDateOfVisitors = that.date(that.form.startDateOfVisitors);
                        that.baseResearchApplication.endDateOfVisitors = that.date(that.form.endDateOfVisitors);
                        that.baseResearchApplication.contactsName = that.form.contactsName;
                        that.baseResearchApplication.affiliatedUnitName = that.form.affiliatedUnitName;
                        that.baseResearchApplication.contactsNumber = that.form.contactsNumber;
                        that.baseResearchApplication.contactsEmail = that.form.contactsEmail;
                        that.baseResearchApplication.otherInstructions = that.form.otherInstructions;
                        that.baseResearchApplication.file = that.form.file;

                        that.baseResearchApplication.reserveOne = that.name;
                        that.baseResearchApplication.status = "1";
                        that.baseResearchApplication.researchResourcesEntityId = that.entityId;
                        that.$myRequest({
                            url: '/resourceshare/baseResearchApplications',
                            method:'post',
                            headers: {
                                token:this.token
                            },
                            data: {
                                baseResearchApplication:JSON.stringify(that.baseResearchApplication)
                            },
                        }).then((res)=>{
                            if(res){
                                if(res.msg == '请勿重复提交'){
                                    if (this.$i18n.locale == 'zh') {
                                        this.$refs.uToast.show({
                                            title: '请勿重复提交',
                                            type: 'error',
                                            back:true
                                        })
                                    } else {
                                        this.$refs.uToast.show({
                                            title: 'Do not repeat submission',
                                            type: 'error',
                                            back:true
                                        })
                                    }
                                }else{
                                    uni.redirectTo({
                                        url: `/pages/resourceSharing/resourceApplySuccess?entityId=${this.entityId}`,
                                    });
                                    /*if (this.$i18n.locale == 'zh') {
                                        this.$refs.uToast.show({
                                            title: '申请成功',
                                            type: 'success',
                                            back:true
                                        })
                                    } else {
                                        this.$refs.uToast.show({
                                            title: 'Application approved',
                                            type: 'success',
                                            back:true
                                        })
                                    }*/
                                }
                            }
                        }).catch((error)=>{
                            if (this.$i18n.locale == 'zh') {
                                this.$refs.uToast.show({
                                    title: '申请失败',
                                    type: 'error',
                                    back:true
                                })
                            } else {
                                this.$refs.uToast.show({
                                    title: 'Application failed',
                                    type: 'error',
                                    back:true
                                })
                            }
                        });
                    } else {
                        if (this.$i18n.locale == 'zh') {
                            this.$refs.uToast.show({
                                title: '必填项未填',
                                type: 'warning',
                            })
                        } else {
                            this.$refs.uToast.show({
                                title: 'The required fields are not filled in',
                                type: 'warning',
                            })
                        }
                    }
                });
            },
            async submit(){
                this.$myRequest({
                    url: '/resourceshare/baseResearchApplications',
                    method:'post',
                    headers: {
                        token:this.token
                    },
                    data: {
                        ...that.baseResearchApplication
                    },
                    success: (res) => {
                        // console.log(res.data);		// 控制台显示数据信息
                        if(res){
                            console.log(res)
                        }
                    },
                });
                if(res){
                    console.log(res)
                }
            },
            back() {
                uni.navigateBack();
            },
            //中英文切换
            i18n (data) {
                return this.$t('common.'+data);
            },
            //** 上传文件类 开始
            // 打开系统文件管理器，获取文件返回绝对路径（暂只支持安卓）
            addFile(){
                let that = this;
                // #ifdef APP-PLUS
                if (plus.os.name.toLowerCase() != "android") {
                    uni.showModal({
                        title: '提示',
                        content: '仅支持Android平台',
                        success: function(res) {}
                    });
                    return false
                }

                let main = plus.android.runtimeMainActivity();
                let Intent = plus.android.importClass("android.content.Intent");
                let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
                //fileIntent.setType(“image/*”);//选择图片
                //fileIntent.setType(“audio/*”); //选择音频
                //fileIntent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
                //fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
                fileIntent.setType("*/*"); //无类型限制
                fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
                main.startActivityForResult(fileIntent, 1);
                // 获取回调
                main.onActivityResult = function(requestCode, resultCode, data) {
                    let Activity = plus.android.importClass("android.app.Activity");
                    let ContentUris = plus.android.importClass("android.content.ContentUris");
                    let Cursor = plus.android.importClass("android.database.Cursor");
                    let Uri = plus.android.importClass("android.net.Uri");
                    let Build = plus.android.importClass("android.os.Build");
                    let Environment = plus.android.importClass("android.os.Environment");
                    let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
                    let MediaStore = plus.android.importClass("android.provider.MediaStore");
                    // 给系统导入 contentResolver
                    let contentResolver = main.getContentResolver()
                    plus.android.importClass(contentResolver);
                    // 返回路径
                    let path = '';
                    if (resultCode == Activity.RESULT_OK) {
                        let uri = data.getData()
                        if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
                            path = uri.getPath();
                            return;
                        }
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
                            path = getPath(this, uri);
                        } else { //4.4以下下系统调用方法
                            path = getRealPathFromURI(uri)
                        }
                        // 回调
                        that.resultPath(path)
                    }
                    // 4.4 以上 从Uri 获取文件绝对路径
                    function getPath(context, uri) {
                        let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
                        let scheme = uri.getScheme().toLowerCase()
                        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                            // ExternalStorageProvider
                            if (isExternalStorageDocument(uri)) {
                                let docId = DocumentsContract.getDocumentId(uri);
                                let split = docId.split(":");
                                let type = split[0];
                                // 如果是手机内部存储
                                if ("primary" == type.toLowerCase()) {
                                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                                } else {
                                    return '/storage/' + type + "/" + split[1];
                                }
                            }
                            // DownloadsProvider
                            else if (isDownloadsDocument(uri)) {
                                let id = DocumentsContract.getDocumentId(uri);
                                let split = id.split(":");
                                return split[1]
                                // let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
                                // return getDataColumn(context, contentUri, null, null);
                            }
                            // MediaProvider
                            else if (isMediaDocument(uri)) {
                                let docId = DocumentsContract.getDocumentId(uri);
                                let split = docId.split(":");
                                let type = split[0];
                                let contentUri = null;
                                if ("image" == type.toLowerCase()) {
                                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                                } else if ("video" == type.toLowerCase()) {
                                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                                } else if ("audio" == type.toLowerCase()) {
                                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                                }
                                let selection = "_id=?";
                                let selectionArgs = [split[1]];
                                return getDataColumn(context, contentUri, selection, selectionArgs);
                            }
                        }
                        // MediaStore (and general)
                        else if ("content" == scheme) {
                            return getDataColumn(context, uri, null, null);
                        }
                        // File
                        else if ("file" == scheme) {
                            return uri.getPath();
                        }
                    }

                    // 4.4 以下 获取 绝对路径
                    function getRealPathFromURI(uri) {
                        let res = null
                        let proj = [MediaStore.Images.Media.DATA]
                        let cursor = contentResolver.query(uri, proj, null, null, null);
                        if (null != cursor && cursor.moveToFirst()) {;
                            let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            res = cursor.getString(column_index);
                            cursor.close();
                        }
                        return res;
                    }

                    // 通过uri 查找出绝对路径
                    function getDataColumn(context, uri, selection, selectionArgs) {
                        let cursor = null;
                        let column = "_data";
                        let projection = [column];
                        // let contentResolver = context.getContentResolver()
                        // plus.android.importClass(contentResolver);
                        cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            let column_index = cursor.getColumnIndexOrThrow(column);
                            return cursor.getString(column_index);
                        }
                    }

                    function isExternalStorageDocument(uri) {
                        return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
                    }

                    function isDownloadsDocument(uri) {
                        return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
                    }

                    function isMediaDocument(uri) {
                        return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
                    }
                }
                // #endif
            },
            // 上传调用
            resultPath(e){
                // e 为解析出来的文件本地路径
                let that =this;
                let fIndex =e.lastIndexOf(".");
                let fileType =e.substr(fIndex+1);   //文件后缀

                //判断是否为图片
                function isAssetTypeAnImage(ext) {
                    return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
                }

                //判断是否为文档
                function isAssetFile(ext) {
                    return ['txt','pdf','doc','xls','xlsx','ppt','docx'].indexOf(ext.toLowerCase()) !== -1;
                }

                //图片上传调用
                /*if(isAssetTypeAnImage(fileType)){
                    that.form.numberOfVisitors = e
                    uni.uploadFile({
                        // url: this.$Base_Url + '/api/work_img', //仅为示例，非真实的接口地址
                        // url: this.$Base_Url + '/api/work_img', //仅为示例，非真实的接口地址
                        filePath:"file:/"+ e,
                        name: 'img',
                        formData: {},
                        header:{  //仅为示例，非真实的请求header
                            // 'nktjj_session': uni.getStorageSync("c") || '',
                            //"cookie": 'nktjj_session=' + uni.getStorageSync("c") || '',
                            // 'X-Requested-With': 'XMLHttpRequest',
                            // 'Content-Type': 'application/json; charset=UTF-8'
                        },
                        success: (uploadFileRes) => {
                            that.form.contactsName = uploadFileRes

                            //这里会有一个坑
                            //如果是上传完就要预览图片，若后端没有返回线上路径，需要你通过通过访问本地图片路径
                            //请在取得的本地路径前 加上一个“file://”

                            let abc ="file://"+e;  //本地路径
                            let imgUrl= JSON.parse(uploadFileRes.data).data.imgUrl;	//后端返回的值
                        }
                    });
                }*/

                //文档上传调用
                if(isAssetFile(fileType)){
                    that.form.numberOfVisitors = e
                    uni.uploadFile({
                        // url: this.$Base_Url + '/api/work_file', //仅为示例，非真实的接口地址
                        url: this.$Base_Url + '/api/work_file', //仅为示例，非真实的接口地址
                        filePath:"file:/"+ e,
                        name: 'file',
                        formData: {},
                        header:{ //仅为示例，非真实的请求header
                    // 'nktjj_session': uni.getStorageSync("c") || '',
                    //"cookie": 'nktjj_session=' + uni.getStorageSync("c") || '',
                    // 'X-Requested-With': 'XMLHttpRequest',
                    // 'Content-Type': 'application/json; charset=UTF-8'
                },
                    success: (uploadFileRes) => {
                        that.form.contactsName = uploadFileRes
                        let fileId= JSON.parse(uploadFileRes.data).data.file_id;
                    }
                });
                }
            },
            //** 上传文件类 结束
        }
    }
</script>

<style lang="scss" scoped>
    .rf-category {
        background-color: #F3F4F5;
        /*  #ifdef  APP-PLUS  */
        /*margin-top: calc(20upx + var(--status-bar-height));*/
        /*  #endif  */
        .icoStyle {
            display: flex;
            align-items:center;
        }
        .content{
            background-color: white;
        }
    }
</style>
