<template>
    <view class="add-apply-page">
        <view class="form-item has-arrow">
            <view class="label">到达日期</view>
            <view class="content">
                <picker
                    class="picker-box" 
                    mode="date" 
                    :value="formData.arriveDate" 
                    :start="startDate" 
                    :end="endDate" 
                    @change="arriveDateChange"
                >
					<view :class="['text',formData.arriveDate?'':'placeholde-text']">{{formData.arriveDate||'请选择日期'}}</view>
				</picker>
            </view>
        </view>
        <view class="form-item has-arrow">
            <view class="label">返程日期</view>
            <view class="content">
                <picker
                    class="picker-box" 
                    mode="date" 
                    :value="formData.backDate" 
                    :start="startDate" 
                    :end="endDate" 
                    @change="backDateChange"
                >
					<view :class="['text',formData.backDate?'':'placeholde-text']">{{formData.backDate||'请选择日期'}}</view>
				</picker>
            </view>
        </view>
        <view class="form-item has-arrow">
            <view class="label">目的地</view>
            <view class="content" @click="showDestination=true">
                <view :class="['text',formData.destination.length==0?'placeholde-text':'']">{{formData.destination.join('')||'请选择目的地'}}</view>
            </view>
        </view>
        <view class="form-item has-arrow">
            <view class="label">出差事由</view>
            <view class="content" @click="showReason=true">
                <view :class="['text',formData.reason?'':'placeholde-text']">{{formData.reason||'请选择出差事由'}}</view>
            </view>
        </view>
        <view class="form-item has-arrow">
            <view class="label">交通工具</view>
            <view class="content" @click="showVehicle=true">
                <view :class="['text',formData.vehicle?'':'placeholde-text']">{{formData.vehicle||'请选择交通工具'}}</view>
            </view>
        </view>
        <view class="form-item" v-if="formData.vehicle=='其他'">
            <view class="label">其他工具</view>
            <view class="content">
                <input v-model="formData.otherVehicle" style="width:100%;height:100%" type="text" placeholder="请输入交通工具">
            </view>
        </view>
        <view class="form-item itinerary-form">
            <view class="label">行程说明</view>
            <view class="content">
                <textarea
                    disable-default-padding
                    maxlength="-1"
                    style="width:100%;margin-top: 2px;" 
                    v-model="formData.Itinerary" 
                    placeholder="请输入行程说明" 
                    auto-height
                />
            </view>
        </view>

        <view class="partner-box" style="margin-top:20rpx">
            <view class="form-item" v-for="(item,index) in formData.partner" :key="item.AdminId">
                <view class="label">同行人</view>
                <view class="content">{{item.RealName}}</view>
                <image class="del-icon" src="../static/del.png" mode="aspectFill" @click="handleDelPartner(index)"/>
            </view>
            <view class="add-partner-box" @click="showPartner=true">
                <image class="del-icon" src="../static/add.png" mode="aspectFill"/>
                <text>同行人</text>
            </view>
              
        </view>

        <view class="fix-bottom-wrap btns-wrap flex">
            <button class="refuse-btn" @click="handleRefuse">取消</button>
			<button class="pass-btn" @click="handleApply">确定</button>
		</view>
          


        <!-- 选择目的地弹窗 -->
        <van-popup :show="showDestination" @close="showDestination=false" position="bottom">
            <van-area
				:value="formData.destination"
				:area-list="areaList" 
				:columns-num="2"
				@confirm="confrimDestination" 
				@cancel="showDestination = false"
			/>
        </van-popup>

        <!-- 出差事由 -->
        <van-popup :show="showReason" @close="showReason=false" position="bottom">
            <van-picker 
                show-toolbar 
                title="出差事由" 
                :columns="reasonOpt" 
                @confirm="onReasonChange" 
                @cancel="showReason=false"
            />
        </van-popup>

        <!-- 交通工具 -->
        <van-popup :show="showVehicle" @close="showVehicle=false" position="bottom">
            <van-picker 
                show-toolbar 
                title="交通工具" 
                :columns="vehicleOpts" 
                @confirm="onvehicleChange" 
                @cancel="showVehicle=false"
            />
        </van-popup>

        <!-- 选择同行人 -->
        <van-popup :show="showPartner" @close="showPartner=false" position="bottom">
            <van-cascader
                v-if="showPartner"
                title="请选择同行人"
                :options="systemUserList"
                :field-names="systemUserListOpt"
                @close="showPartner=false"
                @finish="onSelectPartnerFinish"
            />
        </van-popup>
    </view>

      
      
</template>

<script>
import { areaList } from '@/utils/area.js';
import {apiSystemUsers} from '@/api/common'
import {apiAddApply,apiEditApply,apiBusinessTripDetail} from '@/api/businessTrip/index'
export default {
    computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        }
    },
    data() {
        const currentDate = this.getDate()
        return {
            id:0,
            formData:{
                arriveDate:'',
                backDate:'',
                destination:[],
                reason:'',
                vehicle:'',
                otherVehicle:'',
                partner:[],
                Itinerary:''
            },
            areaList,
            showDestination:false,

            showReason:false,
            reasonOpt:['路演','调研','培训','会议'],

            showVehicle:false,
            vehicleOpts:['飞机','火车','汽车','其他'],

            showPartner:false,
            systemUserList:[],
            systemUserListOpt:{
                text: 'RealName',
                value: 'AdminId',
                children: 'ChildrenList',
            }
        }
    },
    onLoad(opt){
        this.id=opt.id
        if(opt.id){
            this.getDetail()
            uni.setNavigationBarTitle({
                title: '重新申请',
                success: (result) => {},
                fail: () => {},
                complete: () => {}
            });
              
        }
        this.getSystemUsers()
    },
    methods: {
        async handleApply(){
            const pids=[],pnames=[];
            this.formData.partner.forEach(item => {
                pids.push(item.AdminId)
                pnames.push(item.RealName)
            });
            let params={
                ArriveDate:this.formData.arriveDate,
                ReturnDate:this.formData.backDate,
                Province:this.formData.destination[0],
                City:this.formData.destination[1],
                Reason:this.formData.reason,
                Transportation:this.formData.otherVehicle?`${this.formData.vehicle}-${this.formData.otherVehicle}`:this.formData.vehicle,
                PeerPeopleId:pids.join(','),
                PeerPeopleName:pnames.join(','),
                Itinerary:this.formData.Itinerary
            }
            if(!params.ArriveDate){
                uni.showToast({
                    title:'请选择到达日期',
                    icon:'none'
                })
                return
            }
            if(!params.ReturnDate){
                uni.showToast({
                    title:'请选择返程日期',
                    icon:'none'
                })
                return
            }
            if(!params.City){
                uni.showToast({
                    title:'请选择目的地',
                    icon:'none'
                })
                return
            }
            if(!params.Reason){
                uni.showToast({
                    title:'请选择出差事由',
                    icon:'none'
                })
                return
            }
            if(!params.Transportation){
                uni.showToast({
                    title:'请选择交通工具',
                    icon:'none'
                })
                return
            }
            if(!params.Itinerary){
                uni.showToast({
                    title:'请输入行程说明',
                    icon:'none'
                })
                return
            }

            const res=this.id?await apiEditApply({...params,BusinessApplyId:Number(this.id)}):await apiAddApply(params)
            if(res.code===200){
                setTimeout(() => {
                    uni.showToast({
                        title:"提交成功",
                        icon:'success'
                    })
                }, 200);
                
                uni.$emit('businessApproveListUpdate')
                setTimeout(()=>{
					this.handleRefuse()
				},1800)
            }
            
        },

        handleRefuse(){
            uni.navigateBack({
                delta:1
            })
        },


        getDate(type) {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        arriveDateChange(e){
            this.formData.arriveDate=e.detail.value
        },
        backDateChange(e){
            this.formData.backDate=e.detail.value
        },

        confrimDestination(e){
            this.formData.destination=[e.detail.values[0].name,e.detail.values[1].name]
            this.showDestination=false
        },

        onReasonChange(e){
            this.formData.reason=e.detail.value
            this.showReason=false
        },

        onvehicleChange(e){
            this.formData.vehicle=e.detail.value
            this.showVehicle=false
        },

        // 选择同行人
        onSelectPartnerFinish(e){
            // console.log(e);
            const item=e.detail.selectedOptions[e.detail.selectedOptions.length-1]
            this.formData.partner.push(item)
            this.showPartner=false
        },
        handleDelPartner(index){
            this.formData.partner.splice(index,1)
        },

        getSystemUsers(){
            apiSystemUsers().then(res=>{
                if(res.code===200){
                    this.systemUserList=res.data.List||[]
                }
            })
        },

        // 获取详情
        getDetail(){
            apiBusinessTripDetail({BusinessApplyId:this.id}).then(res=>{
                if(res.code===200){
                    this.formData.arriveDate=res.data.ArriveDate
                    this.formData.backDate=res.data.ReturnDate
                    this.formData.destination=[res.data.Province,res.data.City]
                    this.formData.reason=res.data.Reason
                    this.formData.Itinerary=res.data.Itinerary
                    this.formData.vehicle=res.data.Transportation.split('-')[0]
                    this.formData.otherVehicle=res.data.Transportation.split('-')[1]?res.data.Transportation.split('-')[1]:''
                    if(res.data.PeerPeopleName){
                        const temPartnerName=res.data.PeerPeopleName.split(',')
                        const temPartnerId=res.data.PeerPeopleId.split(',')
                        console.log(temPartnerName);
                        temPartnerName.forEach((item,index)=>{
                            this.formData.partner.push({
                                AdminId:temPartnerId[index],
                                RealName:item
                            })
                        })
                    }
                    
                }
            })
        }

    },
}
</script>

<style lang="scss" scoped>
.add-apply-page{
    padding-top: 10rpx;
    padding-bottom: calc(150rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(150rpx + env(safe-area-inset-bottom));
    .form-item{
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5f5;
        padding: 20rpx 34rpx;
        position: relative;
        background-color: #fff;
        font-size: 32rpx;
        .label{
            width: 130rpx;
            flex-shrink: 0;
            text-align: right;
            margin-right: 30rpx;
        }
        .content{
            flex: 1;
            min-height: 40rpx;
            .picker-box{
                width: 100%;
                height: 100%;
            }
            .placeholde-text{
                color: #999;
            }
        }
        .del-icon{
            width: 34rpx;
            height: 34rpx;
        }
        
    }
    .has-arrow::after{
            content: '';
            display: block;
            transform:rotate(45deg);
            width: 18rpx;
            height: 18rpx;
            border-top: 2rpx solid #333;
            border-right: 2rpx solid #333;
    }
    .picker-box{
        height: 500rpx;
        .item {
            line-height: 100rpx;
            text-align: center;
        }
    }
    .destination-popup-top-btn{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 34rpx;
        view:first-child{
            color: #999;
        }
        view:last-child{
            color: #3385FF;
        }
    }
    .add-partner-box{
        display: flex;
        padding: 20rpx 34rpx;
        align-items: center;
        font-size: 32rpx;
        color: #3385FF;
        background-color: #fff;
        image{
            width: 34rpx;
            height: 34rpx;
            margin-right: 20rpx;
            display: block;
        }
    }

    .btns-wrap {
		justify-content: center;
		button {
			width: 260rpx;
			height: 70rpx;
			border-radius: 28px;
			border: none;
			margin: 0 15px;
			font-size: 15px;
			color: #fff;
			line-height: 70rpx;
		}

		.pass-btn {
			background-color: #3385FF;
		}

		.refuse-btn {
			background-color: #fff;
            color: #3385FF;
            border: 1px solid #3385FF;
		}
	}
    .itinerary-form{
        align-items: flex-start;
    }
}
</style>