<template>
    <div>
        <div class="communal-list">
            <div class="communal-title">
                <div>邀请/公务活动资料</div>
            </div>
            <div>
                <div class="communal-box" style="margin-top: 10px;">
                    <el-autocomplete style="margin-right: 15px;" class="inline-input" v-model="Country" :fetch-suggestions="querySearchCountry"
                        placeholder="请输入国家" clearable></el-autocomplete>
                    <el-autocomplete style="margin-right: 10px;" class="inline-input" v-model="UnitName" :fetch-suggestions="querySearchUnitName"
                        placeholder="请输入邀请方" clearable></el-autocomplete>
                    <el-autocomplete style="margin-right: 10px;" class="inline-input" v-model="Contact" :fetch-suggestions="querySearchContact"
                        placeholder="联系人" clearable></el-autocomplete>
                    <el-select  v-model="Delegation" clearable filterable placeholder="团组名称" style="width: 20%;margin-right: 15px;">
                        <el-option v-for="(items,index) in restaurantDelegation" :key="index" :label="items.teamName"
                            :value="items.id">
                        </el-option>
                    </el-select>
                    <el-select style="margin-right: 10px;width:218px;" v-model="CreateUserId" placeholder="录入者" filterable clearable>
                        <el-option v-for="item in CreateUserList" :key="item.id" :label="item.cnName" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-date-picker style="width:448px;margin-right: 10px;" v-model="InviteTime" type="daterange" align="right" unlink-panels format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" range-separator="至" start-placeholder="邀请开始日期" end-placeholder="邀请结束日期"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                    <el-autocomplete class="inline-input" v-model="Field" :fetch-suggestions="querySearchField"
                        placeholder="领域" clearable></el-autocomplete>
                    <el-button type="primary" @click="QueryData" style="margin-left: 10px;">查询</el-button>
                    <div>
                        <router-link to='/home/OpInvitationOfficialActivityData'>
                            <el-button type="primary" style="margin-left: 10px;">新增</el-button>
                        </router-link>
                    </div>
                </div>
                <div class="communal-box" style="margin-top: 10px;">
                    <!-- <el-button type="primary" @click="QueryCount" style="margin-left: 10px;">查询录入数量</el-button> -->
                    <!-- <div style="display: flex;align-items: center;justify-content: center">
                        查询结果:该人员在以上条件共录入<span style="color: red;">{{ dataCount }}</span>条数据
                    </div> -->
                </div>
            </div>
            <template>
                <el-table :data="tableData" border
                    style="width: 100%;margin-top: 10px;" v-loading="loading" element-loading-text="拼命加载中...">
                    <el-table-column prop="num" label="序 号" width="55">
                        <template slot-scope="scope">
                            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="country" width="100" label="国家">
                    </el-table-column>
                    <el-table-column prop="city" label="城市">
                    </el-table-column>
                    <el-table-column prop="unitName" label="邀请方名称">
                    </el-table-column>
                    <el-table-column prop="field" label="涉及领域">
                    </el-table-column>
                    <el-table-column prop="contact" width="100" label="联系人">
                    </el-table-column>
                    <el-table-column prop="job" label="职务">
                    </el-table-column>
                    <el-table-column prop="tel" width="120px" label="手机">
                    </el-table-column>
                    <el-table-column prop="delegationStr" label="关联团组">
                        <template slot-scope="scope">
                            <div id="delegationStr">
                                <el-tooltip v-show="scope.row.delegationStr != ''" class="item" effect="dark"
                                    :content="scope.row.delegationStr" placement="top">
                                    <span v-if="scope.row.delegationStr.length > 9">{{ scope.row.delegationStr.slice(0, 9) + "..."
                                    }}</span>
                                    <span v-else>{{ scope.row.delegationStr }}</span>
                                    <div slot="content">
                                        <div style="width: 300px;">
                                            {{ scope.row.delegationStr }}
                                        </div>
                                    </div>
                                </el-tooltip>
                            </div>
                        </template>
                        <!-- <template slot-scope="Str">
                            <div :title="Str.row.delegationStr" class="title">{{ Str.row.delegationStr }}</div>
                        </template> -->
                    </el-table-column>
                    <el-table-column width="80" prop="createUserName" label="录入者">
                    </el-table-column>
                    <el-table-column prop="createTime" label="录入时间">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="upDate(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <div class="block">
                <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[10, 12, 15, 20]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next" :total="dataCount">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    beforeRouteLeave(to, from, next) {
        if(to.name!='OpInvitationOfficialActivityData'){
            from.meta.keepAlive = false;
        }
        next()
    },
    data() {
        return {
            loading: false,
            tableData: [],
            tableDatas: [],
            currentPage: 1, // 当前页码
            pageSize: 10,// 每页的数据条数
            dataCount: 0,//总条数
            Country: "",
            restaurantsCountry: [],
            UnitName: "",
            restaurantsUnitName: [],
            Contact: "",
            restaurantContact: [],
            Delegation: "",
            restaurantDelegation: [],
            Field: "",
            restaurantField: [],
            CreateUserId: "",
            CreateUserList: [],
            InviteTime: "",
            StartCreateTime: "",
            EndCreateTime: "",
            input: '',
            token: '',
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
        }
    },
    beforeRouteLeave(to,from,next) {
        if(to.name=='OpInvitationOfficialActivityData'){
            next();
        }else{
            this.$store.state.Termsofinvitation={};
             next();
        }
        console.log(this.$store.state.Termsofinvitation)
    },
    methods: {
        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
            this.QueryInvitationOfficialActivityData()
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.QueryInvitationOfficialActivityData()
        },

        //国家搜索框处理
        querySearchCountry(queryString, cb) {
            //数据去重处理
            var arr = this.restaurantsCountry;
            for (var i = 0; i < arr.length - 1; i++) {
                for (var j = i + 1; j < arr.length; j++) {
                    if (arr[i].value == arr[j].value) {
                        arr.splice(j, 1);
                        //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
                        j--;
                    }
                }
            }
            var restaurantsCountry = arr;
            var results = queryString ? restaurantsCountry.filter(this.createFilter(queryString)) : restaurantsCountry;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        //邀请方搜索框处理
        querySearchUnitName(queryString, cb) {
            var arr = this.restaurantsUnitName;
            for (var i = 0; i < arr.length - 1; i++) {
                for (var j = i + 1; j < arr.length; j++) {
                    if (arr[i].value == arr[j].value) {
                        arr.splice(j, 1);
                        //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
                        j--;
                    }
                }
            }
            var restaurantsUnitName = arr;
            var results = queryString ? restaurantsUnitName.filter(this.createFilter(queryString)) : restaurantsUnitName;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        //联系人搜索框处理
        querySearchContact(queryString, cb) {
            var arr = this.restaurantContact;
            for (var i = 0; i < arr.length - 1; i++) {
                for (var j = i + 1; j < arr.length; j++) {
                    if (arr[i].value == arr[j].value) {
                        arr.splice(j, 1);
                        //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
                        j--;
                    }
                }
            }
            var restaurantContact = arr;
            var results = queryString ? restaurantContact.filter(this.createFilter(queryString)) : restaurantContact;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        //领域搜索框处理
        querySearchField(queryString, cb) {
            var arr = this.restaurantField;
            for (var i = 0; i < arr.length - 1; i++) {
                for (var j = i + 1; j < arr.length; j++) {
                    if (arr[i].value == arr[j].value) {
                        arr.splice(j, 1);
                        //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
                        j--;
                    }
                }
            }
            var restaurantField = arr;
            var results = queryString ? restaurantField.filter(this.createFilter(queryString)) : restaurantField;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        //查询添加vuex
        QueryData() {
            this.$store.state.Termsofinvitation = {
                Country:this.Country,
                UnitName:this.UnitName,
                Contact:this.Contact,
                Delegation:this.Delegation,
                CreateUserId:this.CreateUserId,
                InviteTime:this.InviteTime,
                Field:this.Field,

            };
            this.currentPage = 1;
            this.QueryInvitationOfficialActivityData()
        },
        //判断全局变量是否有值
        estimatevuex(){
            console.log(this.$store.state.Termsofinvitation);
            this.Country=this.$store.state.Termsofinvitation.Country?this.$store.state.Termsofinvitation.Country:'';
            this.UnitName=this.$store.state.Termsofinvitation.UnitName?this.$store.state.Termsofinvitation.UnitName:'';
            this.Contact=this.$store.state.Termsofinvitation.Contact?this.$store.state.Termsofinvitation.Contact:'';
            this.Delegation=this.$store.state.Termsofinvitation.Delegation?this.$store.state.Termsofinvitation.Delegation:'';
            this.CreateUserId=this.$store.state.Termsofinvitation.CreateUserId?this.$store.state.Termsofinvitation.CreateUserId:'';
            this.InviteTime=this.$store.state.Termsofinvitation.InviteTime?this.$store.state.Termsofinvitation.InviteTime:'';
            this.Field=this.$store.state.Termsofinvitation.Field?this.$store.state.Termsofinvitation.Field:'';
            this.currentPage=this.$store.state.Termsofinvitation.pgindex?this.$store.state.Termsofinvitation.pgindex:1;
        },
        //基础数据
        QueryIOAInitData() {
            var url = "/api/Resource/QueryIOAInitData"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data: {
                    PortType: 1
                }
            }).then(function (res) {
                console.log(res)
                if (res.data.code == 200) {
                    res.data.data.countryData.forEach(function (item, index) {
                        that.restaurantsCountry.push({
                            value: item,
                        });
                    });
                    res.data.data.contactData.forEach(function (item, index) {
                        that.restaurantContact.push({
                            value: item,
                        });
                    });
                    res.data.data.inviterData.forEach(function (item, index) {
                        that.restaurantsUnitName.push({
                            value: item,
                        });
                    });
                    res.data.data.domainData.forEach(function (item, index) {
                        that.restaurantField.push({
                            value: item,
                        });
                    });
                    that.restaurantDelegation=res.data.data.groupNameData;
                    that.CreateUserList=res.data.data.userNameData;
                }else{
                    that.$message.error(res.data.msg);
                }
            }).catch(function (error) {
                that.$message.error(error);
            });
        },
        QueryInvitationOfficialActivityData() {
            console.log(this.Delegation)
            var CreateUser = 0;
            if (this.CreateUserId == "" || this.CreateUserId == undefined || this.CreateUserId == null) {
                CreateUser = 0
            } else {
                CreateUser = this.CreateUserId
            }
            if (this.InviteTime != "" && this.InviteTime != undefined && this.InviteTime != null) {
                this.StartCreateTime = this.InviteTime[0]
                this.EndCreateTime = this.InviteTime[1]
            } else {
                this.StartCreateTime = ""
                this.EndCreateTime = ""
            }
            this.loading = true
            var url = "/api/Resource/QueryInvitationOfficialActivityData"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    portType: 1,
                    pageIndex: that.currentPage,
                    pageSize: that.pageSize,
                    Country: that.Country,
                    UnitName: that.UnitName,
                    Contact: that.Contact,
                    Delegation: that.Delegation.toString(),
                    Field: that.Field,
                    CreateUserId: CreateUser,
                    StartCreateTime: that.StartCreateTime,
                    EndCreateTime: that.EndCreateTime
                }
            }).then(function (res) {
                console.log(res)
                if (res.data.code == 200) {
                    //#endregion
                    that.tableData = res.data.data;
                    that.dataCount=res.data.count;
                } else {
                    that.tableDatas = [];
                }
                that.loading = false
            }).catch(function (error) {
                that.loading = false
                that.$message.error(error);
            });
        },
        QueryCount() {
            var CreateUser = 0;
            if (this.CreateUserId == "" || this.CreateUserId == undefined || this.CreateUserId == null) {
                CreateUser = 0
            } else {
                CreateUser = this.CreateUserId
            }
            if (this.InviteTime != "" && this.InviteTime != undefined && this.InviteTime != null) {
                this.StartCreateTime = this.InviteTime[0]
                this.EndCreateTime = this.InviteTime[1]
            } else {
                this.StartCreateTime = ""
                this.EndCreateTime = ""
            }
            this.loading = true
            var url = "/api/Resource/QueryInvitationOfficialActivityData"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    portType: 1,
                    pageIndex: 0,
                    pageSize: 0,
                    Country: '',
                    UnitName: '',
                    Contact: '',
                    Delegation: '',
                    Field: '',
                    CreateUserId: CreateUser,
                    StartCreateTime: that.StartCreateTime,
                    EndCreateTime: that.EndCreateTime
                }
            }).then(function (res) {
                console.log(res)
                if (res.data.code == 200) {
                    that.tableData = res.data.data;
                    that.tableDatas = that.tableData
                    if (that.tableDatas.slice((that.currentPage - 1) * that.pageSize, that.currentPage * that.pageSize).length == 0) {
                        if (that.currentPage > 1) {
                            that.currentPage = that.currentPage - 1;
                        }
                    }
                    if (that.CreateUserId != 0 && that.CreateUserId != "") {
                        that.dataCount = that.tableDatas.length
                    }
                } else {
                    that.tableDatas = [];
                }
                that.loading = false
            }).catch(function (error) {
                that.loading = false
                that.$message.error("网络错误,请稍后重试");
            });
        },
        
        del(index, row) {
            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var url = "/api/Resource/DelInvitationOfficialActivity"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                    data: {
                        Id: row.id,
                        DeleteUserId: this.userId
                    }
                }).then(function (res) {
                    console.log(res)

                    if (res.data.code == 200) {

                        that.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        that.QueryInvitationOfficialActivityData();
                    } else {
                        that.$message.error('删除失败!');
                    }
                    that.loading = false
                }).catch(function (error) {
                    that.loading = false
                    that.$message.error("网络错误,请稍后重试");
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '操作已取消!'
                });
            });
        },
        upDate(index, row) {
            this.$store.state.Termsofinvitation.pgindex=this.currentPage
            this.$router.push({
                path: "/home/OpInvitationOfficialActivityData",
                query: { id: row.id }
            })
        },
    },
    created(){
        this.estimatevuex()
    },
    mounted() {
        this.QueryIOAInitData();
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
        this.QueryInvitationOfficialActivityData();
    }
}
</script>
<style>
.communal-list {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    min-height: 830px;
}
.communal-list .block{
    margin-top: 15px;
    
}
.communal-title {
    display: flex;
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-top: 8px;
    margin-bottom: 10px;
    justify-content: space-between;
    align-items: center;
    
}

.communal-box {
    display: flex;
}

.communal-box>button {
    margin-left: 10px;
    padding: 8px 20px;
}

.title {
    width: 80px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
}

</style>