<template>
    <div v-loading.fullscreen.lock="fullscreenLoading">
        <div class="paymentfiled-all">
            <div class="paymentfiled-haed-box">
                <div class="paymentfiled-haed">
                    <el-date-picker style="width:400px" v-model="value2" type="daterange" align="left" unlink-panels range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" @change="datechange"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                    <div class="haed-btn">
                        <el-button @click="PostPayRequestCheckedChange(1)" type="primary">保存勾选</el-button>
                        <el-button @click="PostPayRequestCheckedChange(2)" type="primary">清空勾选</el-button>
                        <el-button @click="checkCheckbox" type="primary">查看勾选</el-button>
                        <el-button @click="datechange" type="primary">查看全部</el-button>
                        <el-select style="width:200px" v-model="value" filterable placeholder="请选择">
                            <el-option
                              v-for="item in options"
                              :key="item.id"
                              :label="item.conpamyName"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        <el-button @click="generatebtn" type="primary">生成</el-button>
                        <el-button @click="paymentbtn" type="primary">付款</el-button>
                    </div>
                </div>
            </div>
            <div class="paymentfiled-info">
                <div class="paymentfiled-info-li">
                    <label>付款申请人:</label>
                    <span>{{applicant}}</span>
                </div>
                <div class="paymentfiled-info-li">
                    <label>申请付款日期:</label>
                    <span>{{application}}</span>
                </div>
                <!-- <div class="paymentfiled-info-li">
                    <label>申请付款金额:</label>
                    <span>公转：{{revolution}} CNY</span>
                    &nbsp;
                    &nbsp;
                    <span>私转：{{privateTransfer}} CNY</span>
                </div> -->
            </div>
            <div class="paymentfiled-form">
                <el-collapse v-model="activeNames" @change="handleChange">
                    <el-collapse-item name="2">
                        <template slot="title">
                            <div style="width: 100%;">
                                <p style="float: left;user-select: none;">
                                    团组付款申请
                                </p>
                                <p align="right" style="user-select: none;">
                                    <span>公转：{{tzrevolution}} CNY</span>
                                    &nbsp;
                                    &nbsp;
                                    <span>私转：{{tzprivateTransfer}} CNY</span>
                                    &nbsp;
                                    &nbsp;
                                    &nbsp;
                                    &nbsp;
                                </p>
                            </div>
                        </template>
                        <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)+'&nbsp;&nbsp;&nbsp;汇率：':'' }}
                                    </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>
                    </el-collapse-item>
                    <el-collapse-item name="1">
                        <template slot="title">
                            <div style="width: 100%;">
                                <p style="float: left;user-select: none;">
                                    日付申请
                                </p>
                                <p align="right" style="user-select: none;">
                                    <span>公转：{{rfrevolution}} CNY</span>
                                    &nbsp;
                                    &nbsp;
                                    <span>私转：{{rfprivateTransfer}} CNY</span>
                                    &nbsp;
                                    &nbsp;
                                    &nbsp;
                                    &nbsp;
                                </p>
                            </div>
                        </template>
                        <div class="tree-box">
                            <el-tree 
                            @check="everydayChange"
                            :data="everydayData" 
                            ref="abc"
                            show-checkbox 
                            :default-expand-all="false" 
                            :default-checked-keys="everydayarr"
                            node-key="id" 
                            :check-strictly="true"
                            :props="everydayProps"
                            highlight-current>
                                <span class="custom-tree-node" slot-scope="{ data }">
                                    <span >
                                        {{ data.companyName?'【'+data.companyName+'】':'' }}
                                    </span>
                                    <span>
                                        {{ data.transferParentIdStr?' 【'+data.transferParentIdStr+'】':'' }}
                                    </span>
                                    <span>
                                        {{ data.priceTypeStr?' 【'+data.priceTypeStr+'】':'' }}
                                    </span>
                                    <span>
                                        {{ data.instructions?'('+data.instructions+'):':'' }}
                                    </span>
                                    <span>
                                        {{ data.sumPrice?' CNY: '+twonumder(data.sumPrice):'' }}
                                    </span>
                                    <span>
                                        {{ data.createUser?'【申请人: '+data.createUser:'' }}
                                    </span>
                                    <span>
                                        {{ data.createTime?'申请时间: '+data.createTime+'】':'' }}
                                    </span>
                                    <span style="color:rgb(149 149 149);">
                                        {{ data.remaksDescription?data.remaksDescription:'' }}
                                    </span>
                                </span>
                            </el-tree>
                        </div>
                    </el-collapse-item>
                    
                </el-collapse>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
      return {
        value:2,
        options:[],
        pageId:'',
        token:'',
        userId:'',
        applicant:'',
        application:'',
        rfrevolution:'0.00',//日付公转
        rfprivateTransfer:'0.00',//日付私转
        tzrevolution:'0.00',//团组公转
        tzprivateTransfer:'0.00',//团组私转

        defaultProps: {
            children: 'childList',
            label: 'groupName'
        },
    
        everydayProps: {
            children: 'childList',
            label: 'instructions',
            disabled:function(data, node) {
                if(data.transferParentIdStr==undefined){
                    return true
                }
            }
        },
        
        activeNames: ['1','2'],

        multipleSelection: [],
        //选择日期快捷选项
        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]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }
          , {
            text: '最近两年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 730);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: '',
        checked:'',
        groupstableData:[],//团组付款申请
        everydayData:[],//日常付款申请
        defaultarr:[],//团组勾选中
        everydayarr:[],//日付勾选中
        fullscreenLoading:false,
        hotelSubIdarr:[],
    };
    },
    methods:{
        //两位小数
        twonumder(val){
            return val.toFixed(2)
        },
        handleChange(val) {
            console.log(val);
        },
        //获取基础数据
        PostPayRequestInit(){
            var url = "/api/Financial/PostPayRequestInit"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
            }).then(function (res) {
                if(res.data.code==200){
                    console.log(res)
                    that.options=res.data.data.conpanyData;
                }else{
                    that.$message({
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        //处理数组
        filt(array) {
            return array.filter(x => Number.isFinite(x));
        },
        //勾选
        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.hotelSubIdarr=Array.from(new Set(this.hotelSubIdarr))
            // console.log(this.arrstring(this.hotelSubIdarr));
            // var arrid=[]
            // for(let i=0;i<node.checkedKeys.length;i++){
            //     if(Number(node.checkedKeys[i].split('p')[1])==Number(node.checkedKeys[i].split('p')[1])){
            //         arrid.push(Number(node.checkedKeys[i].split('p')[1]));
            //     }
            // }
            
            // for(let j=0;j<this.groupstableData.length;j++){
            //     for(let s=0;s<this.groupstableData[j].childList.length;s++){
            //         for(let x=0;x<arrid.length;x++){
            //             if(arrid[x]==Number(this.groupstableData[j].childList[s].id.split("p")[1])){
            //                 console.log(this.groupstableData[j].childList[s].id);
            //                 this.defaultarr.push(this.groupstableData[j].childList[s].id)
            //             }
            //         }
            //     }
            // }
            // arrid=Array.from(new Set(arrid))
            this.defaultarr=node.checkedKeys
            // console.log(this.arrstring(this.defaultarr));
        },
        //日付勾选
        everydayChange(data,node){
            this.everydayarr=node.checkedKeys
            console.log(this.arrstring(this.everydayarr));
        },
        //数组处理成字符串
        arrstring(val){
            var stringarr='';
            for(let s=0;s<val.length;s++){
                stringarr += val[s].toString()+',';
            }
            return stringarr.substring(0, stringarr.length-1);
        },
        //处理时间
        getdate(val){
            var date=new Date(val);
            var y=date.getFullYear();
            var m=date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1;
            var d=date.getDate()<10?'0'+date.getDate():date.getDate();
            return y+'-'+m+'-'+d
        },
        //查看勾选
        checkCheckbox(){
            console.log(this.defaultarr)
            console.log(this.everydayarr)
            if(this.defaultarr.length==0&&this.everydayarr.length==0){
                this.$message({
                    message:'请保存勾选后再查看！',
                    type: 'warning'
                });
                return;
            }

            //初始化
            this.groupstableData=[];
            this.everydayData=[];
            this.rfrevolution='0.00';//日付公转
            this.rfprivateTransfer='0.00';//日付私转
            this.tzrevolution='0.00';//团组公转
            this.tzprivateTransfer='0.00';//团组私转
            this.PostPayRequest_Center(this.getdate(this.value2[0]),this.getdate(this.value2[1]),2);
            // this.PostPayRequest_Center('2023-01-01','2024-03-25',2);
        },
        //选择日期
        datechange(){
            //初始化
            this.groupstableData=[];
            this.everydayData=[];
            this.rfrevolution='0.00';//日付公转
            this.rfprivateTransfer='0.00';//日付私转
            this.tzrevolution='0.00';//团组公转
            this.tzprivateTransfer='0.00';//团组私转
            this.PostPayRequest_Center(this.getdate(this.value2[0]),this.getdate(this.value2[1]),1);
            // this.PostPayRequest_Center('2023-01-01','2024-03-25',1);
        },
        //汇率更改
        inputblur(id,raet,hotelSubId){
            this.PostPayRequestRateChange(id,raet,hotelSubId)
        },
        //获取付款申请list
        PostPayRequest_Center(beginDt,endDt,status){
            this.fullscreenLoading=true;

            var url = "/api/Financial/PostPayRequest_Center"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data:{
                    portType:1,
                    status:status,
                    beginDt:beginDt,
                    endDt:endDt,
                    pageId: that.pageId,
                    userId: that.userId,
                }
            }).then(function (res) {
                if(res.data.code==200){
                    console.log(res)
                    that.rfrevolution=res.data.data.daily.gz;
                    that.rfprivateTransfer=res.data.data.daily.sz;
                    that.tzrevolution=res.data.data.group.gz;
                    that.tzprivateTransfer=res.data.data.group.sz;
                    that.groupstableData=res.data.data.group.dataList;
                    if(that.groupstableData!=null){
                        var arrid=[]
                        for(let i=0;i<that.groupstableData.length;i++){
                            for(let j=0;j<that.groupstableData[i].childList.length;j++){
                                that.groupstableData[i].childList[j].id=j+'p'+that.groupstableData[i].childList[j].id
                                arrid.push(that.groupstableData[i].childList[j].id)
                                if(that.groupstableData[i].childList[j].isChecked==true){
                                    that.defaultarr.push(that.groupstableData[i].childList[j].id)
                                    that.hotelSubIdarr.push(that.groupstableData[i].childList[j].hotelSubId)
                                }
                            }
                        }
                        console.log(that.hotelSubIdarr);
                        console.log(that.defaultarr);
                    }
                    that.everydayData=res.data.data.daily.dataList;
                    if(that.everydayData!=null){
                        for(let s=0;s<that.everydayData.length;s++){
                            if(that.everydayData[s].isChecked==true){
                                that.everydayarr.push(that.everydayData[s].id)
                            }
                        }
                    }
                    that.fullscreenLoading=false;
                }else{
                    that.$message({
                        message: '加载失败！原因：'+res.data.msg,
                        type: 'warning'
                    });
                    that.fullscreenLoading=false;
                }
            })
        },
        //保存勾选
        PostPayRequestCheckedChange(type){
            var hotelSubIdarrs=[]
            for(let n=0;n<this.hotelSubIdarr.length;n++){
                if(this.hotelSubIdarr[n]!=undefined&&this.hotelSubIdarr[n]!=-1){
                    hotelSubIdarrs.push(this.hotelSubIdarr[n]);
                }
            }
            this.hotelSubIdarr=Array.from(new Set(hotelSubIdarrs))
            var arrid=[]
            for(let i=0;i<this.defaultarr.length;i++){
                if(typeof this.defaultarr[i]!== 'number'){
                    if(Number(this.defaultarr[i].split('p')[1])==Number(this.defaultarr[i].split('p')[1])){
                        arrid.push(Number(this.defaultarr[i].split('p')[1]));
                    }
                }
            }
            arrid=Array.from(new Set(arrid))
            this.defaultarr=this.filt(arrid);
            var url = "/api/Financial/PostPayRequestCheckedChange"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data:{
                    userId:that.userId,
                    hotelSubIds:that.arrstring(that.hotelSubIdarr),
                    groupIds:that.arrstring(that.defaultarr),
                    dailyPaymentIds:that.arrstring(that.everydayarr),
                    type:type
                }
            }).then(function (res) {
                if(res.data.code==200){
                    // that.$message({
                    //     message: res.data.msg,
                    //     type: 'success'
                    // });
                    if(type==2){
                        that.$refs.tree.setCheckedKeys([]);
                        that.$refs.abc.setCheckedKeys([]);
                        that.defaultarr=[];
                        that.everydayarr=[];
                    }
                }else{
                    that.$message({
                        message: '保存失败！原因：'+res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        //修改汇率
        PostPayRequestRateChange(id,rate,hotelSubId){
            var url = "/api/Financial/PostPayRequestRateChange"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data:{
                    portType:1,
                    pageId:that.pageId,
                    userId:that.userId,
                    status:1,
                    beginDt:that.getdate(that.value2[0]),
                    endDt:that.getdate(that.value2[1]),
                    id:Number(id.split('p')[1]),
                    hotelSubId:hotelSubId,
                    rate:rate
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                }else{
                    that.$message({
                        message: '保存失败！原因：'+res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        //付款btn
        paymentbtn(){
            this.$confirm('是否确认付款?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.PostPayRequestCheckedChange(1)
                setTimeout(this.PostPayRequestPayChange(),1000)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消付款'
                });
            });
        },
        //付款api
        PostPayRequestPayChange(){
            var hotelSubIdarrs=[]
            for(let n=0;n<this.hotelSubIdarr.length;n++){
                if(this.hotelSubIdarr[n]!=undefined&&this.hotelSubIdarr[n]!=-1){
                    hotelSubIdarrs.push(this.hotelSubIdarr[n]);
                }
            }
            this.hotelSubIdarr=Array.from(new Set(hotelSubIdarrs))
            var url = "/api/Financial/PostPayRequestPayChange"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data:{
                    userId:that.userId,
                    hotelSubIds:that.arrstring(that.hotelSubIdarr),
                    groupIds:that.arrstring(that.defaultarr),
                    dailyPaymentIds:that.arrstring(that.everydayarr),
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.datechange()
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                }else{
                    that.$message({
                        message:res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        //生成btn
        generatebtn(){
            this.PostPayRequestCheckedChange(1)
            setTimeout(this.PostPayRequestFileDownload,1000)
        },
        //生成api
        PostPayRequestFileDownload(){
            // this.PostPayRequestCheckedChange(1)
            var url = "/api/Financial/PostPayRequestFileDownload"
            var that = this
            console.log(that.value2);
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data:{
                    portType:1,
                    userId:that.userId,
                    pageId:that.pageId,
                    beginDt:that.getdate(that.value2[0]),
                    endDt:that.getdate(that.value2[1]),
                    conpanyId:that.value
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    window.open(res.data.data.url)
                }else{
                    that.$message({
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
    },
    filters: {
        numFilter(value) {
            let realVal = "";
            if (!isNaN(value) && value !== "") {
            // 截取当前数据到小数点后两位,改变toFixed的值即可截取你想要的数值
            realVal = parseFloat(value).toFixed(2);
            } else {
            realVal = "--";
            }
            return realVal;
        },
    },
    mounted(){
        this.pageId = localStorage.getItem('indexs').split('-')[1];
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.applicant=JSON.parse(localStorage.getItem('userinif')).userInfo.cnName;
        this.application=this.getdate(new Date());
        //调用获取基础数据
        this.PostPayRequestInit()
    }
}
</script>
<style>
    .paymentfiled-all{
        background-color: #fff;
        padding: 10px;
        box-shadow: 0 0 5px #0005;
        border-radius: 10px;
        height: 100%;
        min-height: 830px;
    }
    .paymentfiled-haed{
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
    }
    .paymentfiled-info{
        display: flex;
        margin-bottom: 15px;
    }
    .paymentfiled-info-li{
        margin-right: 30px;
    }
    .paymentfiled-info-li label{
        color: #606266;
        font-size: 15px;
        font-weight: 600;
    }
    .paymentfiled-info-li span{
        color: #606266;
        font-size: 14px;
    }
    .paymentfiled-form{
        max-height: 700px;
        overflow: auto;
    }
    .paymentfiled-form-li:nth-child(1){
        border-top:2px solid #409EFF ;
    }
    .paymentfiled-form-li{
        border-bottom:1px solid #ccc ;
        padding: 10px 0;
    }
    .paymentfiled-haed .el-date-editor--monthrange.el-input__inner{
        width: 300px;
    }
    .childtable{
        text-align: -webkit-center;
    }
    .childtable .el-table tr {
        background-color: #f2f6fd !important;
        font-weight: bold;
    }
    .custom-tree-node {
        
        font-size: 16px;
        white-space: normal;
    }
    .custom-tree-nodes {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
    .paymentfiled-form .el-tree-node__content{
        height:70px;
    }
    .paymentfiled-form .el-input__inner{
        height:30px;
        line-height:30px;
    }
    .tree-box{
        border: 1px solid #EBEEF5;
        padding: 10px;
    }
    ::v-deep .el-tree .el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner {
        display: none;
    }
    ::v-deep .el-tree .el-tree-node .el-checkbox .el-checkbox__inner {
        display: inline-block;
    }
</style>
