<template>
    <div class="container-box">
        <div class="filter-box">
            <el-radio-group v-model="auditStatusDict" id="radioGroup">
                <el-radio-button label="">{{$i18n.locale=='en'? 'All': '全部'}}</el-radio-button>
                <el-radio-button label="2">{{$i18n.locale=='en'? 'Under Approval':'审批中'}}</el-radio-button>
                <el-radio-button label="4">{{$i18n.locale=='en'? 'Registration Successful': '审批通过'}}</el-radio-button>
                <el-radio-button label="3">{{$i18n.locale=='en'? 'Registration Failed': '审批不通过'}}</el-radio-button>
            </el-radio-group>
            <div>
                <el-input :placeholder="$i18n.locale=='zh'?'请输入关键词搜索':'Please enter a keyword search'"
                          v-model="searchInput"  maxlength="200" show-word-limit class="input-with-select" @change="search">
                    <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                </el-input>
            </div>
        </div>
        <el-table
                v-loading="loading"
                element-loading-text=""
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                :data="tableData"
                tooltip-effect="dark"
                :border="true"
                size="small"
                :lazy="true"
                height="570"
                :empty-text="$i18n.locale=='en'? 'Sorry no data!':'暂无数据'">
            <!--活动名称-->
            <el-table-column :label="$i18n.locale=='en'? 'Events':'活动名称'" width="400" header-align="center">
                <template slot-scope="scope">{{ scope.row.guestRoomInfoId }}</template>
            </el-table-column>
            <!--活动时间-->
            <el-table-column :label="$i18n.locale=='en'? 'Date':'活动时间'" width="90" header-align="center">
                <template slot-scope="scope">{{ scope.row.isAcceptMeeting }}</template>
            </el-table-column>
            <!--姓名-->
            <el-table-column prop="name" label="姓名" width="120" v-if="$i18n.locale=='zh'" header-align="center"></el-table-column>
            <el-table-column prop="nameEn" label="Name" width="120" v-else header-align="center"></el-table-column>
            <!--审批状态-->
            <el-table-column :label="$i18n.locale=='en'? 'Status':'状态'" width="84"
                             header-align="center">
                <template slot-scope="scope">{{ approvalStatus[scope.row.auditStatusDict]}}</template>
            </el-table-column>
            <!--审批意见-->
            <el-table-column :label="$i18n.locale=='en'? 'Opinions':'审批意见'" width="170"
                             header-align="center">
                <template slot-scope="scope">
                    <span v-show="scope.row.auditStatusDict=='1' || scope.row.auditStatusDict=='2'"
                          style="display: block; text-align: center">/</span>
                    <div v-show="scope.row.auditStatusDict!='1' && scope.row.auditStatusDict!='2'">
                        <el-tooltip v-for="(com,c) in scope.row.comments" :key="c" class="item" effect="dark"
                                    :content="com" placement="top">
                            <i class="icon el-icon-tickets"></i>
                        </el-tooltip>
                        <!-- <span v-for="(com,c) in scope.row.comments" :key="c" style="display: block">{{ com }}</span> -->
                    </div>
                </template>
            </el-table-column>
            <!--操作-->
            <el-table-column :label="$i18n.locale=='en'? 'Operation': '操作'" width="90" header-align="center">
                <template slot-scope="scope">
<!--                    <el-tooltip v-if="scope.row.auditStatusDict=='3'||scope.row.auditStatusDict=='2'" class="item" effect="dark" :content="$i18n.locale=='en'? 'ReApply': '重新报名'" placement="top">-->
                    <el-tooltip v-if="scope.row.auditStatusDict=='2'||scope.row.auditStatusDict=='5'" class="item" effect="dark" :content="$i18n.locale=='en'? 'ReApply': '重新报名'" placement="top">
                        <i class="icon el-icon-refresh-right" @click="openApply(scope.row)"></i>
                    </el-tooltip>
                    
                    <!--<el-tooltip v-if="scope.row.auditStatusDict=='3'||scope.row.auditStatusDict=='2'" class="item" effect="dark" :content="$i18n.locale=='en'? 'Check': '查看'" placement="top">
                        <i class="icon el-icon-refresh-right" @click="openApply(scope.row)"></i>
                    </el-tooltip>-->
                </template>
            </el-table-column>
        </el-table>
        <div style="width: 100%;text-align: center;">
            <el-pagination
                    style="margin-top: 20px"
                    layout="prev, pager, next"
                    @current-change="currentChange"
                    :total="totalNum">
            </el-pagination>
        </div>
        <el-dialog
                :title="$t('common.ActivityRegistration')"
                :visible.sync="dialog"
                width="50%">
            <el-form :rules="rules" ref="formLabelAlign" :model="formLabelAlign" class="demo-ruleForm"
                     v-show="$i18n.locale=='zh'"
                     label-width="200px" style="width: 700px;margin: auto;margin-top: -20px;">

                <el-form-item :label="$t('common.ActivityName')"
                              style="font-weight: 600; color:rgb(153, 153, 153) !important;">
                    <span style="line-height: 50px;">{{dialogData.guestRoomInfoId}}</span>
                </el-form-item>

                <el-form-item label="姓名" class="el-label">
                    <el-input class="el-input" v-model="formLabelAlign.name" disabled
                              :placeholder="$t('common.NameTips')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('common.NameoftheEntity')" class="el-label" prop="unitName">
                    <el-select popper-class="mySelect" style="width: 400px" v-model="formLabelAlign.unitName" filterable
                               :placeholder="$t('common.NameEntityTips')"
                               @blur="selectBlur">
                        <el-option
                                v-for="item in projectList"
                                :key="item.baseEntityId"
                                :label="item.unitName"
                                :value="item.baseEntityId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('common.Position')" class="el-label" prop="post">
                    <el-input class="el-input" v-model="formLabelAlign.post"
                              :placeholder="$t('common.PositionTips')"></el-input>
                </el-form-item>

                <el-form-item style="position: relative;" :label="$t('common.ContactPhoneNumber')" prop="contactNumber"
                              class="dcp_input">
                    <GlobalRoaming ref='GlobalRoaming' :size="{width:'398px'}"
                                   v-model="formLabelAlign.contactNumber"
                                   :mobile="formLabelAlign.contactNumber"
                                   :code="select"
                                   @getAreaCode="getPassAreaCode"></GlobalRoaming>
                </el-form-item>

                <el-form-item :label="$t('common.Email')" class="el-label" prop="mailbox">
                    <el-input class="el-input" v-model="formLabelAlign.mailbox"
                              :placeholder="$t('common.EmailTips')"></el-input>
                </el-form-item>
            </el-form>
            <el-form :rules="rules" ref="formLabelAlign" :model="formLabelAlign" class="demo-ruleForm"
                     v-show="$i18n.locale=='en'"
                     label-width="200px" style="width: 700px;margin: auto;margin-top: -20px;">
                <el-form-item :label="$t('common.ActivityName')"
                              style="font-weight: 600; color:rgb(153, 153, 153) !important;">
                    <span style="line-height: 50px;">{{dialogData.guestRoomInfoId}}</span>
                </el-form-item>
                <el-form-item label="Country" class="el-label" prop="unitCountry" v-if="$i18n.locale!=='zh'">
                    <el-select class="el-select" filterable v-model="formLabelAlign.unitCountry"
                               :placeholder="$t('common.CountryTips')"
                               style="width: 400px;">
                        <el-option :label="item.label" :value="item.value"
                                   v-for="(item,index) in countrydate"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="Region" class="el-label" prop="Region" v-if="$i18n.locale=='en'">
                    <!--<el-input class="el-input" v-model="formLabelAlign.Region"
                              :placeholder="$t('common.RegionTips')"></el-input>-->
                    <el-select class="el-select"  filterable v-model="formLabelAlign.Region" :placeholder="$t('common.RegionTips')"
                               style="width: 400px;">
                        <el-option :label="item.label" :value="item.label"
                                   v-for="(item,index) in Regiondate"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="Title" class="el-label" prop="Title" v-if="$i18n.locale=='en'">
                    <!-- <el-input class="el-input" v-model="formLabelAlign.Title"></el-input> -->
                    <el-select class="el-select" filterable v-model="formLabelAlign.Title"
                               :placeholder="$t('common.TitleTips')"
                               style="width: 400px;">
                        <el-option :label="item.label" :value="item.value"
                                   v-for="(item,index) in titleList"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="First(given) Name(s)" class="el-label" prop="FirstName" v-if="$i18n.locale=='en'">
                    <el-input class="el-input" v-model="formLabelAlign.FirstName"
                              :placeholder="$t('common.FirstNameTips')"></el-input>
                </el-form-item>
                <el-form-item label="Last Name" class="el-label" prop="LastName" v-if="$i18n.locale=='en'">
                    <el-input class="el-input" v-model="formLabelAlign.LastName"
                              :placeholder="$t('common.LastNameTips')"></el-input>
                </el-form-item>


                <el-form-item :label="$t('common.NameoftheEntity')" class="el-label" prop="unitName">
                    <el-select popper-class="mySelect" style="width: 400px" v-model="formLabelAlign.unitName" filterable
                               :placeholder="$t('common.NameEntityTips')"
                               @blur="selectBlur">
                        <el-option
                                v-for="item in projectList"
                                :key="item.baseEntityId"
                                :label="item.unitName"
                                :value="item.baseEntityId">
                        </el-option>
                    </el-select>


                </el-form-item>
                <el-form-item :label="$t('common.Position')" class="el-label" prop="post">
                    <el-input class="el-input" v-model="formLabelAlign.post"
                              :placeholder="$t('common.PositionTips')"></el-input>
                </el-form-item>

                <el-form-item style="position: relative;" :label="$t('common.ContactPhoneNumber')" prop="contactNumber"
                              class="dcp_input">
                    <GlobalRoaming ref='GlobalRoaming' :size="{width:'398px'}"
                                   v-model="formLabelAlign.contactNumber"
                                   :mobile="formLabelAlign.contactNumber"
                                   :code="select"
                                   @getAreaCode="getPassAreaCode"></GlobalRoaming>
                </el-form-item>

                <el-form-item :label="$t('common.Email')" class="el-label" prop="mailbox">
                    <el-input class="el-input" v-model="formLabelAlign.mailbox"
                              :placeholder="$t('common.EmailTips')"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialog = false">{{$t('common.Cancel')}}</el-button>
                <el-button type="primary" @click="save()">{{$t('common.Confirm')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import Base from "@/views/base/Base";
    import {getDicts} from "@/api/dict";
    import {formatDate} from "@/utils/formatUtils";
    import {getActivityApplyByIdForWeb, getMeetingApproveHistory} from '@/api/meeting/meetingApply'
    import {get} from '@/api/meeting/meetingApply'
    import {getList} from '@/api/country'
    import {saveActivityOrUpdate, getApproverId} from "@/api/meeting/meetingApply";
    import GlobalRoaming from "@/components/GlobalRoaming";
    import {countryNationalSpace} from '@/api/cooperation/baseCooperationUnit'


    export default {
        name: "userCenterActivityRegistration",
        extends: Base,
        components: { GlobalRoaming },
        data() {
            return {
                Regiondate:[],
                language:'',
                userId: JSON.parse(localStorage.getItem('user')).userId,
                // 字典
                statusArray: [],
                statusEnArray: [],
                // 检索
                auditStatusDict:'',
                searchInput:'',
                // 分页
                cureentPage: 1,
                totalNum: 0,
                // 表格
                tableData:[],
                loading:true,
                // 重新报名
                processKey: "MEETING_APPROVE",
                approverId: '',
                dialog:false,
                dialogData:{}, // 存储当前活动报名审批信息
                meetingApply:{}, // 存储当前活动报名信息
                formLabelAlign: { // 表单
                    id:null,
                    name: '',
                    unitName: '',
                    ifName: null,
                    post: '',
                    contactNumber: '',
                    mailbox: '',
                    FirstName: '',
                    LastName: '',
                    unitCountry: '',
                    Title: '',
                    Region: '',
                    auditStatusDict: '',
                    language: '',
                    selectCode: '',
                    invitationCode: '',//邀请码
                    meetingId: '',//会议id
                    // reApply: 'true'//重新报名标识
                },
                titleList: [
                    {
                        value: 'Mr.',
                        lable: 'Mr.'
                    }, {
                        value: 'Ms.',
                        lable: 'Ms.'
                    }, {
                        value: 'Dr.',
                        lable: 'Dr.'
                    }, {
                        value: 'Prof.',
                        lable: 'Prof.'
                    }
                ],
                select:'', //区号
                projectList: [], // 单位 list
                countrydate:[]
            }
        },
        mounted() {
            const that = this;
            this.getBaseList();// 获取企业报名信息
            this.$nextTick(function () {
                getDicts('APPROVAL_STATUS').then(res => {
                    that.statusArray = res.data[0];
                    that.statusEnArray = [{"label": "UnderApproval", "value": "2"},
                        {"label": "Registration Failed", "value": "3"},
                        {"label": "Registration Successful", "value": "4"}];
                })
                that.getApplyHistory();
            })
        },
        watch:{
            "$i18n.locale"() {
                this.auditStatusDict = '';
                this.searchInput = '';
                this.cureentPage = 1;
                this.totalNum = 0;
                this.getBaseList();// 获取企业报名信息
                this.getApplyHistory()
            },
            'auditStatusDict'(val,oldVal){
                this.getApplyHistory()
            },
            'dialog'(val,oldval){
                if(val == false){
                    this.dialogData = {}
                    this.meetingApply = {}
                    this.formLabelAlign = {
                        id:null,
                        name: '',
                        unitName: '',
                        ifName: null,
                        post: '',
                        contactNumber: '',
                        mailbox: '',
                        FirstName: '',
                        LastName: '',
                        unitCountry: '',
                        Title: '',
                        Region: '',
                        auditStatusDict: '',
                        language: '',
                        selectCode: '',
                        invitationCode: '',//邀请码
                        meetingId: '',//会议id
                        
                    }
                }
            }
        },
        computed: {
            approvalStatus: function () {
                if (this.$i18n.locale == "en") {
                    return this.statusEnArray.array2Obj('value', 'label');
                } else {
                    return this.statusArray.array2Obj('value', 'label');
                }
            },
            rules() {
                return {
                    Country: [
                        {required: true, message: 'Please enter Country', trigger: 'change'}
                    ],
                    unitName: [
                        {
                            required: true,
                            message: this.$i18n.locale == 'zh' ? '请输入单位名称' : 'Please enter the unit name',
                            trigger: 'change'
                        },
                    ],
                    unitNameEn: [
                        {required: true, message: 'Please enter the unit name', trigger: 'blur'},
                    ],
                    Region: [
                        {required: true, message: 'Please select an area', trigger: 'blur'},
                    ],
                    Title: [
                        {required: true, message: 'Please choose a title', trigger: 'blur'},
                    ],
                    unitCountry: [
                        {required: true, message: 'Please enter the name of the country', trigger: 'change'}
                    ],
                    FirstName: [
                        {required: true, message: 'Please enter First(given) Name(s)', trigger: 'blur'},
                    ],
                    LastName: [
                        {required: true, message: 'Please enter Last Name', trigger: 'blur'},
                    ],
                    post: [
                        {
                            required: true,
                            message: this.$i18n.locale == 'zh' ? '请输入职务' : 'Please enter job title',
                            trigger: 'blur'
                        }
                    ],
                    postEn: [
                        {required: true, message: 'Please enter job title', trigger: 'blur'}
                    ],
                    contactNumber: [
                        {
                            required: true,
                            message: this.$i18n.locale == 'zh' ? '请输入联系电话' : 'Please enter cellphone number',
                            trigger: 'blur'
                        },
                        {
                            pattern: /^0{0,1}(13[0-9]|15[7-9]|153|151|156|18[1-9])[0-9]{8}$/,
                            message: this.$i18n.locale == 'zh' ? '联系电话格式不正确，请重新输入' : 'Contact number format is incorrect, please re-enter',
                            trigger: 'blur'
                        }
                    ],
                    mailbox: [
                        {
                            required: true,
                            message: this.$i18n.locale == 'zh' ? '请输入邮箱' : 'Please enter email address',
                            trigger: 'blur'
                        },
                        {
                            pattern: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
                            message: this.$i18n.locale == 'zh' ? '邮箱格式不正确，请重新输入' : 'Email format is incorrect, please re-enter',
                            trigger: 'blur'
                        }
                    ],

                }
            }
        },
        methods: {
            // 获取数据
            getApplyHistory() {
                const that = this;
                let params = {
                    pageNo: this.cureentPage,
                    pageSize: 10,
                    auditStatusDict: this.auditStatusDict,
                    createBy: this.userId,
                    language: this.$i18n.locale.toUpperCase(),
                };
                getActivityApplyByIdForWeb(params).then(res => {
                    let that = this;
                    if (res.data) {
                        if (res.data.page) {
                            this.totalNum = Number(res.data.page.totalCount);
                        }
                        if (res.data.page.list) {
                            that.tableData = res.data.page.list;
                            /*that.tableData.forEach((i)=>{
                                i.createDate = i.createDate ? formatDate(i.createDate, "YYYY-MM-DD") : "";
                            })*/
                            that.tableData.forEach(item => {
                                that.$set(item, 'comments', [])
                                // item.comments = []
                                item.isAcceptMeeting = item.isAcceptMeeting - 0
                                item.isAcceptMeeting = item.isAcceptMeeting ? formatDate(item.isAcceptMeeting, "YYYY-MM-DD") : "";
                                getMeetingApproveHistory(item.id).then(res => {
                                    if (res.data) {
                                        if (res.data.tasks) {
                                            res.data.tasks.forEach(com => {
                                                if (com.comment) {
                                                    item.comments.push(com.comment)
                                                }
                                            })
                                        }
                                    }
                                }).then(function () {
                                    console.log('that.tableData', that.tableData)
                                }).catch(() => {
                                    this.loading = false
                                })
                            })
                        } else {
                            that.tableData = []
                        }
                    } else {
                        that.tableData = []
                    }
                    this.loading = false
                })
            },
            // 输入关键字检索
            search(){
                this.getApplyHistory()
            },
            // 分页
            currentChange(p) {
                this.cureentPage = p;
                this.getApplyHistory();
            },
            // 重新报名
            async openApply(ele){
                const that = this;
                that.dialog = true;
                that.dialogData = ele;

                let id = ele.id;
                await this.getApply(id)
            },
            async getApply(id){
                get(id).then(result => {
                    let data = result.data;
                    if(data) {
                        this.meetingApply =  data.meetingApply || this.meetingApply;
                        this.formLabelAlign.id = this.meetingApply.id;
                        this.formLabelAlign.name = this.meetingApply.name;

                        this.formLabelAlign.ifName = 'false';
                        if(this.$i18n.locale=='zh') {
                                this.formLabelAlign.unitName = this.meetingApply.unitName;
                        }else {
                                this.formLabelAlign.unitName = this.meetingApply.unitNameEn;
                        }
                        console.log(this.projectList);
                        this.projectList.forEach(i=>{
                            if(this.$i18n.locale=='zh') {
                                if (this.meetingApply.unitName == i.unitName) {
                                    this.formLabelAlign.unitName = i.baseEntityId;
                                    this.formLabelAlign.ifName = 'true'
                                }
                            }else {
                                if (this.meetingApply.unitNameEn == i.unitName) {
                                    this.formLabelAlign.unitName = i.baseEntityId;
                                    this.formLabelAlign.ifName = 'true'
                                }
                            }
                        });
                        // this.formLabelAlign.reApply = 'true';
                        this.formLabelAlign.post = this.meetingApply.positionName;
                        this.formLabelAlign.contactNumber = this.meetingApply.tel;
                        this.formLabelAlign.mailbox = this.meetingApply.email;
                        this.formLabelAlign.unitCountry = this.meetingApply.unitCountryDict;
                        this.formLabelAlign.Region = this.meetingApply.unitCountryDictEn;
                        this.formLabelAlign.Title = this.meetingApply.dietaryTaboos;
                        this.formLabelAlign.FirstName = this.meetingApply.givenName;
                        this.formLabelAlign.LastName = this.meetingApply.surname;
                        this.formLabelAlign.meetingId = this.meetingApply.meetingId;
                        this.select = this.formLabelAlign.selectCode = this.meetingApply.mobileAreaCodeDictEn;
                    }
                }).catch(error => {

                });
            },
            save: function () {
                //流程改造6
                this.formLabelAlign.auditStatusDict = '2';
                this.$refs['formLabelAlign'].validate((valid) => {
                    if (valid) {
                        this.upData();
                    } else {
                        return false;
                    }
                });
            },
            async upData() {
                const that = this;
                that.formLabelAlign.invitationCode = that.meetingApply.invitationCode;
                this.submitHandler((token) => {
                    getApproverId(this.meetingApply.invitationCode).then((result)=>{
                        result = result.data;
                        var str = "";
                        for(var i = 0; i<result.length; i++){
                            str += result[i].userId + ",";
                        }
                        if (str.length > 0) {
                            str = str.substr(0, str.length - 1);
                        }
                        this.approverId = str;
                        // 会员模块后期加的  可传空字符串
                        let activityIds = this.dialogData.travelPointId;
                        saveActivityOrUpdate(
                            JSON.stringify(this.formLabelAlign),
                            this.approverId,
                            this.taskComment,
                            token,
                            activityIds
                        ).then((res) => {
                            let type = 'success';
                            if (res.msg == 'error') {
                                res.msg = this.$i18n.locale == 'zh' ? '您已报名成功，请勿重复报名。' : 'ou have signed up successfully, please do not repeat.';
                                type = 'warning';
                            } else {
                                res.msg = this.$i18n.locale == 'zh' ? '报名成功' : 'Successful registration';
                            }
                            this.$message({
                                message: res.msg,
                                type: type
                            });
                            this.resetToken();
                            this.centerDialogVisible = false;
                            this.dialog = false;
                        }).catch((error) => {
                            this.resetToken();
                        });
                    });
                });
            },

            // 号码
            getPassAreaCode(code) {
                this.select = code;
                this.formLabelAlign.selectCode = code;
            },
            // 单位 list
            getBaseList() {
                const that = this;
                getList({language: this.$i18n.locale.toUpperCase()}).then(res => {
                    if (JSON.stringify(res.data) !== '{}') {
                        that.projectList = res.data.baseUnitViews || [];
                    }
                })
                getDicts('unit_country_dict_en,CONTINENT_CODE_DICT_EN').then(result => {
                    this.countrydate = result.data[0];
                    this.Regiondate = result.data[1];
                });
            },
            selectBlur(e) {
                this.formLabelAlign.unitName = "";
                if (e.target.value) {
                    // 不在表单的时候不需要判断，也不需要isname字段
                    // 输入内容不在下拉框中时，formLabelAlign.unitName=e.target.value，数据传输为unitName，有内容时，添加字段unitID
                    this.formLabelAlign.unitName = e.target.value;
                    this.formLabelAlign.ifName = 'false'
                } else {
                    this.formLabelAlign.ifName = 'true'
                }
            },
        }
    }
</script>

<style scoped>
    .container-box {
        padding: 20px;
    }
    .filter-box {
        display: flex;
        justify-content: space-between;
        padding: 20px 0;
    }
    /deep/ #radioGroup .el-radio-button__inner{
        border: none;
    }
    /deep/ #radioGroup .el-radio-button.is-active .el-radio-button__inner{
        background-color: white;
        color: #ff3b00;
        box-shadow: 0 0 0 0 #409EFF;
    }

    .dcp_input /deep/ .el-input__inner {
        width: 150px;
    }

    .dcp_input /deep/ .el-select {
        width: 150px;
    }
</style>