<template>
  <el-dialog
    title="出差申请"
    :visible.sync="dialogShow"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    @closed="diaClose"
    width="580px"
  >
    <el-form :model="dataForm" ref="applicationForm" :rules="rules" id="Form" label-width="90px">
      <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">
        <!-- <v-distpicker 
          :province="dataForm.province"
          :city="dataForm.city"
          :province-source="province_sorce"
          :city-source="city_sorce"
          hide-area 
          @selected="selectRegion"
          @province="provinceChange"
        ></v-distpicker> -->
        <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="Itinerary">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入行程说明"
          v-model="dataForm.Itinerary">
        </el-input>
      </el-form-item>
      <el-form-item label="同行人" prop="companion" >
        <el-cascader :options="userList" v-model="companionSelectList" filterable 
        ref="companionCascader" @remove-tag="removeTag"
        :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>

<script>
import {businessTripInterence} from "api/api.js"
//import{province_sorce,city_sorce} from '@/utils/distpicker';
import searchDistPicker from '@/components/searchDistPicker.vue';
  export default {
  components: { searchDistPicker },
    name:"tripApplicationDia",
    props:{
      dialogShow:{
        type:Boolean,
        required:true
      },
      userList:{
        type:Array,
        required:true
      },
      reapply:{
        type:Object,
        default:()=>{}
      }
    },
    watch:{
      dialogShow(value){
        if(value&&this.reapply.BusinessApplyId){
          this.dataForm={
            BusinessApplyId:this.reapply.BusinessApplyId,
            arriveTime:this.reapply.ArriveDate,
            backTime:this.reapply.ReturnDate,
            province:this.reapply.Province,
            city:this.reapply.City,
            tripReason:this.reapply.Reason,
            vehicle:this.reapply.Transportation.indexOf('其他')!=-1?'其他':this.reapply.Transportation,
            companion:this.reapply.PeerPeopleId,
            companionName:this.reapply.PeerPeopleName,
            otherVehicle:this.reapply.Transportation.indexOf('其他')!=-1?this.reapply.Transportation.substring(this.reapply.Transportation.indexOf('-')+1):''
          }
          this.companionSelectList = this.reapply.PeerPeopleId.split(',')
        }
      },
      userList(value){
        this.setUserDisable(value)
      }
    },
    data() {
      this.vehicleArr=['飞机','火车','汽车','其他']
      this.tripReasonArr=['路演','调研','培训','会议']
      /* this.province_sorce = province_sorce
      this.city_sorce = city_sorce */
      return {
        dataForm:{
          arriveTime:'',
          backTime:'',
          province:'',
          city:'',
          tripReason:'',
          vehicle:'',
          companion:'',
          companionName:'',
          otherVehicle:'',
          Itinerary:''
        },
        companionSelectList:[],
        rules:{
          Itinerary:{required:true,message:"行程说明不能为空",trigger:'blur'},
          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(!this.dataForm.otherVehicle&&value=='其他'){
                  callback(new Error('请输入其他交通工具'))
                  return
                }
                callback()
              },
              trigger:['blur']
          }]
        },
        adminId:localStorage.getItem('AdminId')||0
      }
    },
    methods:{
      // 递归用户列表，设置置灰项 - 不能选择自己
      setUserDisable(list){
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if(element.ChildrenList){
            this.setUserDisable(element.ChildrenList)
          }else{
            if(element.AdminId == this.adminId){
              this.$set(element,'disabled',true)
              break
            }
          }
        }
      },
      // 工作位置选择
      selectRegion(data) {
        this.dataForm.province = data.province.value;
        this.dataForm.city = data.city.value =='市'?'':data.city.value;
      },
      //切换省份时，市的值置为空
      provinceChange(){
        this.dataForm.city=''
      },
      // 选择交通工具
      vehicleChange(value){
        if(value!='其他'){
          this.dataForm.otherVehicle=''
        }
      },
      // 选择同行人
      selectCompanions(value){
        // 取出同行人Id
        this.dataForm.companion = value.join(',')
        this.$nextTick(()=>{
          this.getCompanionsName()
        })
      },
      // 取得同行人姓名
      getCompanionsName(){
        // 取出同行人姓名
        let checkNodes = this.$refs.companionCascader.getCheckedNodes()
        let valueLength = checkNodes?checkNodes.length:0
        let companionNameList=[]
        this.dataForm.companionName=''
        for (let i = 0; i < valueLength; i++) {
          const element = checkNodes[i];
          if(element.hasChildren){
            continue
          }
          companionNameList.push(element.label)
        }
        this.dataForm.companionName = companionNameList.join(',')
      },
      diaClose(){
        this.dataForm={
          arriveTime:'',
          backTime:'',
          province:'',
          city:'',
          tripReason:'',
          vehicle:'',
          companion:'',
          companionName:'',
          otherVehicle:'',
          Itinerary:''
        }
        this.companionSelectList=[]
        this.$nextTick(()=>{
          this.$refs.applicationForm.clearValidate()
        })
        this.$emit("update:dialogShow",false)
      },
      approveSubmit(){
        this.$refs.applicationForm.validate(valid=>{
          if(valid){
            if(new Date(this.dataForm.arriveTime).getTime()<new Date(this.$moment(new Date()).format('YYYY-MM-DD')).getTime()){
              this.$message.warning('到达日期不能小于当前日期')
              return
            }
            if(new Date(this.dataForm.arriveTime).getTime()>new Date(this.dataForm.backTime).getTime()){
              this.$message.warning('返程日期不得早于到达日期')
              return
            }
            const params={
              ArriveDate:this.dataForm.arriveTime,
              ReturnDate:this.dataForm.backTime,
              Province:this.dataForm.province,
              City:this.dataForm.city,
              Reason:this.dataForm.tripReason,
              Transportation:this.dataForm.vehicle=='其他'?`${this.dataForm.vehicle}-${this.dataForm.otherVehicle}`:this.dataForm.vehicle,
              PeerPeopleId:this.dataForm.companion,
              PeerPeopleName:this.dataForm.companionName,
              Itinerary:this.dataForm.Itinerary
            }
            // console.log(params);
            if(this.dataForm.BusinessApplyId){
              // 重新申请
              params.BusinessApplyId = this.dataForm.BusinessApplyId
              businessTripInterence.editTripApplication(params).then(res=>{
                if(res.Ret == 200){
                  this.$message.success('重新申请成功')
                  this.$emit("applicationSuccess")
                  this.diaClose()
                }
              })
            }else{
              // 第一次申请
              businessTripInterence.addTripApplication(params).then(res=>{
                if(res.Ret == 200){
                  this.$message.success('申请成功')
                  this.$emit("applicationSuccess")
                  this.diaClose()
                }
              })
            }
          }
        })
      }
    }
  }
</script>

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

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

</style>