<script setup>
import { businessTripInterence } from "@/api/api.js"
import { reactive,ref,nextTick,watch } from "vue";
import { ElMessage } from 'element-plus'
import moment from "moment";

import searchDistPicker from '@/components/searchDistPicker.vue';

const props = defineProps({
    dialogShow:{
      type:Boolean,
      default:false
    },
    userList:{
      type:Array,
      required:true
    },
    reapply:{
      type:Object,
      default:()=>{
        return {}
      }
    }
})
const emits = defineEmits(["update:dialogShow","applicationSuccess"])

const vehicleArr=['飞机','火车','汽车','其他']
const tripReasonArr=['路演','调研','培训','会议']

const dataForm=reactive({
  BusinessApplyId:'',
  arriveTime:'',
  backTime:'',
  province:'',
  city:'',
  tripReason:'',
  vehicle:'',
  companion:'',
  companionName:'',
  otherVehicle:''
})
const companionSelectList=ref([])

const adminId=localStorage.getItem('AdminId')||0

const rules={
  arriveTime:{required:true,message:"到达日期不能为空",trigger:'change'},
  backTime:{required:true,message:"返程日期不能为空",trigger:'change'},
  city:{required:true,message:"目的地不能为空",trigger:'change'},
  tripReason:{required:true,message:"出差事由不能为空",trigger:'change'},
  vehicle:[{required:true,message:"请选择交通工具",trigger:'change'},
    {
      validator:(rule, value, callback)=>{
        if(!dataForm.otherVehicle&&value=='其他'){
          callback(new Error('请输入其他交通工具'))
          return
        }
        callback()
      },
      trigger:['blur']
  }]
}

watch(() => props.dialogShow, (value) => {
  if(value && props.reapply.BusinessApplyId){
    dataForm.BusinessApplyId=props.reapply.BusinessApplyId,
    dataForm.arriveTime=props.reapply.ArriveDate,
    dataForm.backTime=props.reapply.ReturnDate,
    dataForm.province=props.reapply.Province,
    dataForm.city=props.reapply.City,
    dataForm.tripReason=props.reapply.Reason,
    dataForm.vehicle=props.reapply.Transportation.indexOf('其他')!=-1?'其他':props.reapply.Transportation,
    dataForm.companion=props.reapply.PeerPeopleId,
    dataForm.companionName=props.reapply.PeerPeopleName,
    dataForm.otherVehicle=props.reapply.Transportation.indexOf('其他')!=-1?props.reapply.Transportation.substring(props.reapply.Transportation.indexOf('-')+1):''

    companionSelectList.value = props.reapply.PeerPeopleId.split(',')
  }
})

watch(() => props.userList, (value) => {
  setUserDisable(value)
})

// 递归用户列表，设置置灰项 - 不能选择自己
const setUserDisable=(list)=>{
  for (let i = 0; i < list.length; i++) {
    const element = list[i];
    if(element.ChildrenList){
      setUserDisable(element.ChildrenList)
    }else{
      if(element.AdminId == adminId){
        element.disabled=true
        break
      }
    }
  }
}

// 工作位置选择
const selectRegion=(data)=>{
  dataForm.province = data.province.value;
  dataForm.city = data.city.value =='市'?'':data.city.value;
}

// 选择交通工具
const vehicleChange=(value)=>{
  if(value!='其他'){
    dataForm.otherVehicle=''
  }
}

// 选择同行人
const selectCompanions=(value)=>{
  // 取出同行人Id
  dataForm.companion = value.join(',')
  nextTick(()=>{
    getCompanionsName()
  })
}

const companionCascader=ref(null)

// 取得同行人姓名
const getCompanionsName=()=>{
  let checkNodes = companionCascader.value.getCheckedNodes()
  let valueLength = checkNodes?checkNodes.length:0
  let companionNameList=[]
  dataForm.companionName=''
  for (let i = 0; i < valueLength; i++) {
    const element = checkNodes[i];
    if(element.hasChildren){
      continue
    }
    companionNameList.push(element.label)
  }
  dataForm.companionName = companionNameList.join(',')
}

const applicationFormRef=ref(null)

const diaClose=()=>{
  dataForm.BusinessApplyId='',
  dataForm.arriveTime='',
  dataForm.backTime='',
  dataForm.province='',
  dataForm.city='',
  dataForm.tripReason='',
  dataForm.vehicle='',
  dataForm.companion='',
  dataForm.companionName='',
  dataForm.otherVehicle=''

  companionSelectList.value=[]
    setTimeout(()=>{
      applicationFormRef.value.clearValidate()
    },0)
  emits("update:dialogShow",false)
}

const approveSubmit=()=>{
  applicationFormRef.value.validate(valid=>{
    if(valid){
      if(new Date(dataForm.arriveTime).getTime()<new Date(moment(new Date()).format('YYYY-MM-DD')).getTime()){
        ElMessage.warning('到达日期不能小于当前日期')
        return
      }
      if(new Date(dataForm.arriveTime).getTime()>new Date(dataForm.backTime).getTime()){
        ElMessage.warning('返程日期不得早于到达日期')
        return
      }
      const params={
        ArriveDate:dataForm.arriveTime,
        ReturnDate:dataForm.backTime,
        Province:dataForm.province,
        City:dataForm.city,
        Reason:dataForm.tripReason,
        Transportation:dataForm.vehicle=='其他'?`${dataForm.vehicle}-${dataForm.otherVehicle}`:dataForm.vehicle,
        PeerPeopleId:dataForm.companion,
        PeerPeopleName:dataForm.companionName,
      }
      if(dataForm.BusinessApplyId){
        // 重新申请
        params.BusinessApplyId = dataForm.BusinessApplyId
        businessTripInterence.editTripApplication(params).then(res=>{
          if(res.Ret == 200){
            ElMessage.success('重新申请成功')
            emits("applicationSuccess")
            diaClose()
          }
        })
      }else{
        // 第一次申请
        businessTripInterence.addTripApplication(params).then(res=>{
          if(res.Ret == 200){
            ElMessage.success('申请成功')
            emits("applicationSuccess")
            diaClose()
          }
        })
      }
    }
  })
}
</script>

<template>
  <el-dialog
    title="出差申请"
    :model-value="props.dialogShow"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    @closed="diaClose"
    width="580px"
  >
    <el-form :model="dataForm" ref="applicationFormRef" :rules="rules" id="Form" label-width="90px" size="large">
      <el-form-item label="到达日期" prop="arriveTime">
        <el-date-picker v-model="dataForm.arriveTime" style="width: 100%;"
        placeholder="请选择到达日期" value-format="YYYY-MM-DD" :clearable="false">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="返程日期" prop="backTime">
        <el-date-picker v-model="dataForm.backTime" placeholder="请选择返程日期" :clearable="false"
        value-format="YYYY-MM-DD" style="width: 100%;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="目的地" prop="city">
        <search-dist-picker 
            :provinceInfo="dataForm.province"
            :cityInfo="dataForm.city"
            @selected="selectRegion"/>
      </el-form-item>
      <el-form-item label="出差事由" prop="tripReason">
        <el-select v-model="dataForm.tripReason" placeholder="请选择出差事由" style="width: 100%;">
          <el-option :label="item" :value="item" v-for="item in tripReasonArr" :key="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="交通工具" prop="vehicle">
        <div class="vehicle-form-item">
          <el-select v-model="dataForm.vehicle" placeholder="请选择交通工具" @change="vehicleChange" style="flex-grow: 1;">
            <el-option :label="item" :value="item" v-for="item in vehicleArr" :key="item"></el-option>
          </el-select>
          <el-input v-model="dataForm.otherVehicle" style="min-width: 148px;margin-left: 6px;"
          placeholder="请输入交通工具" v-if="dataForm.vehicle=='其他'"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="同行人" prop="companion" >
        <el-cascader :options="userList" v-model="companionSelectList" filterable 
        ref="companionCascader"
        :props="{
					label: 'RealName',
					value: 'AdminId', 
					children: 'ChildrenList',
					emitPath: false,
					multiple: true
				}" placeholder="请选择同行人"
				:show-all-levels="false" @change="selectCompanions"></el-cascader>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="approveSubmit" style="width: 120px;height: 40px;">确定</el-button>
      <el-button @click="diaClose" style="width: 120px;height: 40px;margin-right: 26px;">取消</el-button>
    </div>
  </el-dialog>	
</template>

<style lang="scss" scoped>
.vehicle-form-item{
  display: flex;
  width: 100%;
}
.dialog-footer{
  text-align: center;
  padding:60px 40px 20px ;
}
</style>

<style lang="scss">
@import "../style/trip-dialog";
</style>
<style lang="scss">
#Form{
  .el-cascader{
    width: 100%;
  }
  .el-cascader{
    .el-input--suffix{
      width: 100%;
    }
  }
  .el-input{
    width: 100%;
  }
}

</style>