<template>
    <div class="wozhengcaoles" v-loading="fullscreenLoading">
        <el-dialog :close-on-click-modal="false" width="1200px" title="近期未审核费用" :visible.sync="reviewlistVisible">
            <div class="wozhengcaole-all" v-loading.fullscreen.lock="groupunreviewedLoading">

                <div class="wozhengcaole-haed">
                    <div>
                        <el-date-picker size="small" @change="datechange" style="width:350px" v-model="valueone" type="daterange" align="left"
                            unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                        <el-autocomplete
                        size="small"
                        style="width:300px;margin-left: 10px;"
                        v-model="teamName"
                        :fetch-suggestions="querySearchAsync"
                        :trigger-on-focus="false"
                        placeholder="请输入或选择团组"
                        @select="handleSelects"
                        >
                            <template slot-scope="{ item }">
                                <div>{{ item.teamName }}</div>
                            </template>
                        </el-autocomplete>
                        <!-- <el-select size="small" style="width:300px;margin-left: 10px;" v-model="teamName" clearable filterable remote :remote-method="GroupItemKeywordSearch" :loading="selectLoading" @change="inquirebtn" placeholder="请选择">
                            <el-option
                            v-for="item in inputArr"
                            :key="item.id"
                            :label="item.teamName+' '+item.clientUnit"
                            :value="item.teamName">
                            </el-option>
                        </el-select> -->
                        <!-- <el-input
                        size="small"
                        style="width:250px"
                        placeholder="请输入团组名称"
                        v-model="teamName"
                        clearable>
                        </el-input> -->
                        <el-button size="small" @click="inquirebtn" type="primary">查 询</el-button>
                    </div>
                    <div v-if="jurisdiction">
                        <el-button size="small" @click="examinebtn(1)" type="primary">审核通过</el-button>
                        <el-button size="small" @click="examinebtn(2)" type="danger">审核不通过</el-button>
                    </div>
                </div>
                <div class="tree-box">
                    <el-tree 
                    @check="handleSelectionChange" 
                    :data="groupstableData" 
                    ref="tree"
                    show-checkbox 
                    :default-expand-all="false" 
                    :default-checked-keys="defaultarr"
                    node-key="id" 
                    :props="defaultProps"
                    highlight-current>
                        <span class="custom-tree-node" slot-scope="{ data }">
                            <span>{{data.groupName?'（团组：'+data.groupName+'）':'' }}</span>
                            <span>
                                {{ data.applicant?'申请人：'+data.applicant:''}}
                            </span>
                            <span>
                                {{ data.payType?'【'+data.payType+'】':''}}
                            </span>
                            <span>
                                {{ data.moduleName?'['+data.moduleName+']':''}}
                            </span>
                            <span>
                                {{ data.priceName?data.priceName:''}}
                            </span>
                            <span>
                                {{ data.payee?'（收款方：'+data.payee+'）':'' }}
                            </span>
                            <span>
                                {{ data.payCurrCode?'  : '+data.payCurrCode+' ':'' }}
                            </span>
                            <span>
                                {{ data.paymentAmount!=undefined?'  '+twonumder(data.paymentAmount):'' }}
                            </span>
                            <span>
                                {{ data.cnyTotalAmount!=undefined?'&nbsp;&nbsp;&nbsp;付款金额&nbsp;&nbsp;&nbsp;CNY  '+twonumder(data.cnyTotalAmount):'' }}
                            </span>
                            <span>
                                {{ data.cnySubTotalAmount!=undefined?'  、 CNY  '+twonumder(data.cnySubTotalAmount=data.paymentAmount*data.payRate)+'、':'' }}
                            </span>
                            <span>
                                {{ data.payRate!=undefined?'&nbsp;&nbsp;&nbsp;汇率：'+twonumders(data.payRate):'' }}
                            </span>
                            <!-- <el-input-number v-if="data.payRate!=undefined" style="width:100px" @blur="inputblur(data.id,data.payRate,data.hotelSubId)" :precision="4" placeholder="公务翻译费" v-model="data.payRate" :controls='false'>
                            </el-input-number> -->
                        </span>
                    </el-tree>
                </div>
            </div>
        </el-dialog>
        <div class="group-list">
            <div>
                <el-select style="width:120px" v-model="value" clearable placeholder="请选择" @change="filterStatus(value)">
                    <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                <el-autocomplete
                style="width:300px;margin-left: 10px;"
                v-model="input"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                placeholder="请输入或选择团组"
                @select="handleSelect"
                >
                    <template slot-scope="{ item }">
                        <div>{{ item.teamName }}</div>
                    </template>
                </el-autocomplete>
                <!-- <el-select style="width:300px;margin-left: 10px;" v-model="input" clearable filterable remote :remote-method="GroupItemKeywordSearch" :loading="selectLoading" @change="Inquireclick()" placeholder="请选择">
                    <el-option
                    v-for="item in inputArr"
                    :key="item.id"
                    :label="item.teamName+' '+item.clientUnit"
                    :value="item.teamName">
                    </el-option>
                </el-select> -->
                <el-button 
                type="primary"
                size=""
                @click="Inquireclick()">查 询</el-button>
                <el-button 
                v-if="jurisdiction&&userid==21"
                style="margin-right: 10px;"
                type="primary"
                title="最近费用"
                @click="Recentexpenses()">近期未审核费用</el-button>
                <!-- <el-input
                style="width:300px;"
                placeholder="请输入查询内容"
                v-model="input"
                clearable>
                </el-input> -->
            </div>
            <div class="group-title">
                <div>团组列表</div>
            </div>
            <template>
                <el-table
                :data="groupDatas"
                border
                style="width: 100%">
                    <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="tourCode"
                        width="100"
                        label="团 号">
                    </el-table-column>
                    <!-- <el-table-column
                        width="100" 
                        prop="salesQuoteNo"
                        label="销售报价号">
                    </el-table-column> -->
                    <el-table-column
                        prop="teamType"
                        label="团组类型"
                        width="110">
                    </el-table-column>
                    <el-table-column
                        prop="teamLev"
                        label="级 别"
                        width="80">
                    </el-table-column>
                    <el-table-column
                        prop="teamName"
                        label="团队名称"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="clientName"
                        label="客户名称">
                    </el-table-column>
                    <el-table-column
                        prop="clientUnit"
                        label="客户单位">
                    </el-table-column>
                    <el-table-column
                        prop="visitDate"
                        :formatter="filteryear"
                        label="出访时间"
                        width="110">
                    </el-table-column>
                    <el-table-column
                        prop="visitDays"
                        label="天数"
                        width="50">
                    </el-table-column>
                    <el-table-column
                        prop="visitPNumber"
                        label="人数"
                        width="50">
                    </el-table-column>
                    <el-table-column
                        prop="jietuanOperator"
                        label="接团操作人"
                        width="110">
                    </el-table-column>
                    <el-table-column label="操作" width="135">
                        <template slot-scope="scope">
                          <el-button Inquireclick
                            type="primary"
                            size="mini"
                            title="查看费用清单"
                            @click="handleView(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="count">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    beforeRouteLeave(to, from, next) {
        if(to.name!='FeesPage'){
            localStorage.removeItem('fyshval');
        }
        next()
    },
    data() {
        return {
            
            pageId:0,
            options: [
                {
                    value: '-1',
                    label: '全部'
                }, {
                    value: '0',
                    label: '已完成'
                }, {
                    value: '1',
                    label: '未完成'
                }
            ],
            value: '-1',
            groupDatas:[],
            groupData: [],
            groupDatass:[],
            currentPage: 1, // 当前页码
            pageSize: 12 ,// 每页的数据条数
            count:0,//总数
            input:'',
            inputArr: [],
            selectLoading: false,
            token:'',
            fullscreenLoading:false,
            userid:'',
            //--------------------------------
            reviewlistVisible:false,
            pickerOptions: {
                shortcuts: [{
                    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]);
                    }
                }, {
                    text: '最近六个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一年',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // userid:'',
            valueone:[],
            defaultarr:[],//团组勾选中
            groupstableData:[],//团组付款申请
            defaultProps: {
                children: 'childList',
                label: 'groupName'
            },
            groupunreviewedLoading:false,
            hotelSubIdarr:[],
            jurisdiction:false,//审核权限
            teamName:''
        }
    },
    methods:{
        // 异步搜索方法
        querySearchAsync(queryString, cb) {
            if (queryString === '' || queryString.trim() === '') {
                cb(this.inputArr);
                return;
            }

            this.selectLoading = true;
            var url = "/api/Groups/GroupItemKeywordSearch?keyword=" + queryString;
            var that = this;

            this.$axios({
                method: 'get',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    const results = res.data.data || [];
                    // 如果没有搜索结果，添加一个自定义选项
                    if (results.length === 0 && queryString.trim() !== '') {
                        results.push({
                            id: 'custom',
                            teamName: queryString,
                            clientUnit: '自定义输入',
                            isCustom: true
                        });
                    }
                    cb(results);
                } else {
                    cb([]);
                }
            }).finally(() => {
                that.selectLoading = false;
            });
        },

        // 处理选择
        handleSelect(item) {
            if (item.isCustom) {
                // 如果是自定义输入，直接使用输入的值
                this.input = item.teamName;
                this.Inquireclick();
            } else {
                this.input = item.teamName;
                this.Inquireclick();
            }
        },
        handleSelects(item) {
            console.log(item);
            
            if (item.isCustom) {
                // 如果是自定义输入，直接使用输入的值
                this.teamName = item.teamName;
                this.inquirebtn();
            } else {
                this.teamName = item.teamName;
                this.inquirebtn();
            }
        },




        //搜索提示
        GroupItemKeywordSearch(query) {
            if (query !== '') {
                this.selectLoading=true;
                var url = "/api/Groups/GroupItemKeywordSearch?keyword=" + query
                var that = this
                this.$axios({
                    method: 'get',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                }).then(function (res) {
                    if (res.data.code == 200) {
                        that.inputArr = res.data.data;
                    }else{
                        that.inputArr=[];
                    }
                }).finally(()=>{
                    that.selectLoading=false;
                })
            }
        },
        //分页api
        PostGroupPageList(){
            var url = "/api/Groups/PostExpenseAuditGroupPageItems"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    portType: 1,
                    pageId:47,
                    userId:that.userid,
                    pageIndex: that.currentPage,
                    pageSize: that.pageSize,
                    isSure: that.value,
                    searchCriteria: that.input,
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.groupDatas=res.data.data.data
                    that.count=res.data.count
                }
            })
        },
         //每页条数改变时触发 选择一页显示多少行
         handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
            this.PostGroupPageList();
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.PostGroupPageList();
        },
        //查看费用申请
        handleView(index, row) {
            var fyshval={
                currentPage:this.currentPage,
                value:this.value,
                input:this.input,
            }
            localStorage.setItem('fyshval', JSON.stringify(fyshval));
            this.$router.push({path: '/home/FeesPage?id=' + row.id +''});
        },
        //模糊查询
        Inquireclick(){
            this.currentPage=1;
            this.PostGroupPageList()
        },
        //处理时间
        filteryear(val){
            let gstime=val.visitDate.split(' ')[0]
            return gstime;
        },
        //筛选状态
        filterStatus(){
            this.currentPage=1;
            this.PostGroupPageList();
        },
        //----------------------------------
        //两位小数
        twonumder(val){
            return val.toFixed(2)
        },
        //4位小数
        twonumders(val){
            return val.toFixed(4)
        },
        //处理日期
        datetime(val){
            var date=new Date(val);
            var y=date.getFullYear();
            var m=date.getMonth()+1>=10?date.getMonth()+1:'0'+(date.getMonth()+1).toString();
            var d=date.getDate()>=10?date.getDate():'0'+(date.getDate()).toString();
            return y+'-'+m+'-'+d
        },
        //查询
        inquirebtn(){
            if (this.valueone.length==0) {
                this.$message.error("请选择时间！");
                return
            }
            this.GroupUnAuditFeeList(this.datetime(this.valueone[0]),this.datetime(this.valueone[1]))
        },
        Recentexpenses(){
            this.reviewlistVisible=true;
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
            this.valueone=[start,end]
            this.GroupUnAuditFeeList(this.datetime(this.valueone[0]),this.datetime(this.valueone[1]))
        },
        //切换时间
        datechange(){
            if(this.valueone==null){
                return
            }
            this.GroupUnAuditFeeList(this.datetime(this.valueone[0]),this.datetime(this.valueone[1]))
        },
        //获取团组未审核数据
        GroupUnAuditFeeList(beginDt,endDt){
            this.groupunreviewedLoading=true;
            this.groupstableData=[];
            var that = this;
            var url = "/api/Financial/GroupUnAuditFeeList?beginDt="+beginDt+"&endDt="+endDt+"&teamName="+that.teamName
            this.$axios({
                method: 'get',
                url: url,
                headers: {
                    Authorization: 'Bearer '
                },
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.groupstableData=res.data.data.dataList;
                    that.groupunreviewedLoading=false;
                } else {
                    that.$message.error(res.data.msg);
                    that.groupunreviewedLoading=false;
                }
            })
        },
        //勾选
        handleSelectionChange(data,node) {
            for(let i=0;i<node.checkedNodes.length;i++){
                for(let j=0;j<node.checkedKeys.length;j++){
                    if(node.checkedNodes[i].id==node.checkedKeys[j]){
                        this.hotelSubIdarr.push(node.checkedNodes[i].hotelSubId)
                    }
                }
            }
            this.defaultarr=node.checkedKeys
        },
        //审核通过
        examinebtn(val){
            var auditarr=''
            for (var i = 0; i < this.defaultarr.length; i++) {
                if (!isNaN(Number(this.defaultarr[i]))) {
                    auditarr += this.defaultarr[i] + ','
                }
            }
            auditarr=auditarr.substring(0, auditarr.length - 1)
            this.PostAuditGrpCreditCardPayment(val,auditarr);
        },
        //审核接口
        PostAuditGrpCreditCardPayment(val,auditarr) {
            var url = "/api/Groups/PostAuditGrpCreditCardPayment"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data: {
                    portType:1,
                    userId:that.userid,
                    pageId:47,
                    CreditIdStr:auditarr,
                    auditCode: val,//1审核通过，2审核未通过
                }
            }).then(function (res) {
                console.log(res);
                if (res.data.code == 200) {
                    that.$message({
                        message: res.data.msg,
                        type: 'success',
                        offset: 50
                    });
                    that.GroupUnAuditFeeList(that.datetime(that.value[0]),that.datetime(that.value[1]))
                }else{
                    that.$message({
                        message: res.data.msg,
                        type: 'warning',
                        offset: 50
                    });
                }
            })
        },
    },
    created(){
        if(JSON.parse(localStorage.getItem('fyshval'))){
            this.currentPage=JSON.parse(localStorage.getItem('fyshval')).currentPage;
            this.value=JSON.parse(localStorage.getItem('fyshval')).value;
            this.input=JSON.parse(localStorage.getItem('fyshval')).input;
        }
    },
    mounted(){
        this.token=JSON.parse(localStorage.getItem('userinif')).token;
        this.pageId=Number(localStorage.getItem('indexs').split('-')[1]);//页面id
        this.userid=JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.PostGroupPageList();
        //--------------------------------
        var Permissions=JSON.parse(localStorage.getItem('Permissions'));
        for(let y=0;y<Permissions.length;y++){
            if(Permissions[y].functionName=='审核'){
                this.jurisdiction=true
            }
        }
    }
}
</script>
<style>
    .group-list{
        background-color: #fff;
        padding: 10px;
        box-shadow: 0 0 5px #0005;
        border-radius: 10px;
        min-height: 830px;
    }
    .group-title{
        display: flex;
        font-size: 17px;
        font-weight:600 ;
        color: #555;
        margin-top: 8px;
        margin-bottom: 2px;
        justify-content: space-between;
        align-items: center;
    }
    .group-box>button{
        margin-left: 10px;
    }
    .group-list .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
        text-align: center;
    }
    .group-box>.el-input{
        margin-left: 10px;
    }
    .group-list .block{
        margin-top: 15px;
    }









    .wozhengcaole-title{
        color: #555;
        margin-bottom: 5px;
    }
    .wozhengcaole-haed{
        display: flex;
        justify-content: space-between;
    }
    .wozhengcaoles .wozhengcaole-all .tree-box{
        margin-top: 10px;
        border: 1px solid #EBEEF5;
        padding: 10px;
        max-height: 500px;
        overflow-y: auto;
    }
    .wozhengcaoles .el-dialog__body{
        padding-top: 0;
    }
    .wozhengcaole-all .custom-tree-node{
        line-height: 25px;
        display: flex;
        flex-wrap: wrap;
        font-size: 15px;
    }
    .wozhengcaole-all .el-tree-node__content {
        height: 50px;
    }
</style>