<template>
	<view :class="isUps == true ? 'prevent' : ''">
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true" >
			<block slot="backText">返回</block>
			<block slot="content">离岗申请</block>
		</cu-custom>
		<scroll-view scroll-y="false" >
		<view class="form">
			<view class="de-card-list de-list">
				<view class="cu-form-group ">
					<view class="title">离岗开始时间</view>
          <picker mode="date" :value="pd.STARTTIME?pd.STARTTIME:'请选择'" :start="todayDate" @change="changeStartDate">
            <view class="uni-input">{{ pd.STARTTIME }}</view>
          </picker>
				</view>
				<view class="cu-form-group bb">
					<view class="title">离岗结束时间</view>
          <picker mode="date" :value="pd.ENDTIME?pd.ENDTIME:'请选择'" :start="todayDate" @change="changeEndDate">
            <view class="uni-input">{{ pd.ENDTIME }}</view>
          </picker>
				</view>
				<view class="cu-form-textarea bb-default" style="border-top: 1upx solid #eee;" >
					<view class="cu-form-title" >离岗原因</view>
					<textarea maxlength="-1" v-model="pd.DESCR" placeholder="请输入离岗原因"></textarea>
				</view>
        <view class="cu-form-group ">
          <view class="title">申请人</view>
          <input name="input" disabled="true" v-model="username" placeholder="请输入申请人"></input>
        </view>
        <view class="cu-form-group" v-if="SETUP_STATE === '2'">
          <view class="title">审批人</view>
          <picker @change="PickerApprover" :value="approverindex" :range="approverUserList" range-key="NAME" :disabled="approverUserList.length == 0" @click="isBlankList('approver')">
            <view class="picker">
              {{pd.REVIEW_USER_NAME?pd.REVIEW_USER_NAME:'请选择'}}
            </view>
          </picker>
        </view>
			</view>
		</view>
		<view class="padding flex flex-direction">
			<button :loading="buttonloading" class="cu-btn bg-blue margin-tb-sm lg" @click="$noMultipleClicks(goSubmit)">提交</button>
		</view>
		<view class="padding flex flex-direction">

		</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		basePath,corpinfoId,deptId,loginUser,formatDate,loginSession,baseImgPath,setIsRest
	} from '@/common/tool.js';
  import moment from 'moment';
	import tkiTree from "@/components/select-tree/select-tree.vue"
	import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
	export default {
		components: {
			tkiTree,ruiDatePicker
		},
		data() {
			return {
				isUps:false,
				buttonloading: false,
				msg:'add',
				noClick:true,
				pd: {
          OFFDUTY_ID: '',
          USER_NAME: '',
          REVIEW_USER_NAME: '',
          REVIEW_USER_DEPARTMENTNAME: '',
          REVIEW_STATUS: '',
          REVIEW_DESC: '',
          STARTTIME: '',
          ENDTIME: '',
          DESCR: '',
          REVIEW_USER_ID: ''
        },// 数据
        approverUserList:[],
        approverindex:-1,
        SETUP_STATE: '2', // 离岗设置状态1.无需审批 2.需审批
				todayDate:'',
				username:''		//当前登录用户名称

			}
		},
    onLoad(event){
			this.todayDate =  formatDate(new Date(), 'yyyy-MM-dd');
      var tomorrowDate = moment().add(1, 'days').format('YYYY-MM-DD');  // 使用Moment.js库获取明天的日期

      this.pd.STARTTIME = tomorrowDate;
      this.pd.ENDTIME = tomorrowDate;
			this.username = loginUser.NAME;
      if (event.OFFDUTY_ID) {
        this.pd.OFFDUTY_ID = event.OFFDUTY_ID;
      }
		},
    async onShow(options) {
      this.getSetupData();
      await this.getUserList('approverUserList');
      if (this.pd.OFFDUTY_ID) {
        this.msg = 'edit'
        await this.getData()
      }
      loginSession();
    },
    methods: {
      getData() {
        var _this = this;
        return new Promise((resolve, reject) => {
          uni.showLoading({
            title: '请稍候'
          })
          uni.request({
            url: basePath + '/app/offduty/goEdit',
            method: 'POST',
            header: {
              'Content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              OFFDUTY_ID:_this.pd.OFFDUTY_ID
            },
            success: (res) => {
              if ("success" == res.data.result) {
                uni.hideLoading();
                _this.pd = res.data.pd; //参数map
                if (res.data.pd.REVIEW_USER_ID) {
                  _this.approverUserList.forEach((item, index) => {
                    if (item.USER_ID === res.data.pd.REVIEW_USER_ID) {
                      _this.approverindex = index
                      _this.pd.REVIEW_USER_NAME = _this.approverUserList[_this.approverindex].NAME;
                    }
                  })
                }
              } else if ("exception" == data.result) {
                uni.showToast({
                  title: '错误',
                  duration: 2000
                });
              }
              resolve(true)
            }
          })
        })
      },
      getSetupData() {
        var _this = this;
        uni.showLoading({
          title: '请稍候'
        })
        uni.request({
          url: basePath + '/app/offduty/getSetup',
          method: 'POST',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            CORPINFO_ID:loginUser.CORPINFO_ID
          },
          success: (res) => {
            if ("success" == res.data.result) {
              uni.hideLoading();
              _this.SETUP_STATE = res.data.pd.SETUP_STATE; //参数map
            } else if ("exception" == data.result) {
              uni.showToast({
                title: '错误',
                duration: 2000
              });
            }
          }
        });
      },
      //获取人员列表
      getUserList(list,i){
        var _this=this
        return new Promise((resolve, reject) => {
          //发送 post 请求
          uni.request({
            method: 'POST',
            dataType: 'json',
            header: {
              'Content-type':'application/x-www-form-urlencoded'
            },
            url: basePath+'/app/sys/listUserLeader',
            data: {
              tm:new Date().getTime(),
              CORPINFO_ID:loginUser.CORPINFO_ID,
              DEPARTMENT_ID:loginUser.DEPARTMENT_ID,
              USER_ID:loginUser.USER_ID
            },
            success: function(res){
              if("success" == res.data.result){
                _this[list]=res.data.userList;
              }else{
                uni.showToast({
                  title: res.data.message,
                  duration: 2000
                });
              }
              resolve(true)
            }
          })
        })
      },
			//获取数据字典数据
			getDict: function () {
			},
			changeStartDate(e) {
				this.pd.STARTTIME = e.detail.value
        this.$forceUpdate();//强制刷新
			},
			changeEndDate(e) {
				this.pd.ENDTIME = e.detail.value
				this.$forceUpdate();//强制刷新
			},
      PickerApprover(e) {
        this.approverindex = e.detail.value;
        this.pd.REVIEW_USER_ID=this.approverUserList[this.approverindex].USER_ID;
        this.pd.REVIEW_USER_NAME=this.approverUserList[this.approverindex].NAME;
        console.log(this.approverindex)
        console.log(this.approverUserList)
        console.log(this.pd.REVIEW_USER_ID)
        this.$forceUpdate();//强制刷新
      },
      isBlankList(userType) {
        switch(userType) {
          case 'approver':
            if(this.approverUserList.length == 0) {
              uni.showToast({
                icon: 'none',
                title: '审批人列表暂无数据',
                duration: 1500
              })
            }
            break
        }
      },
		/* 	goSubmit1(){
				setIsRest(1);
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 1});
				uni.hideLoading();
			}, */
			goSubmit() {
				var _this = this;
				if (!_this.pd.STARTTIME || _this.pd.STARTTIME == '请选择') {
					uni.showToast({
						icon: 'none',
						title: '请选择离岗起始时间',
						duration: 1500
					});
					return;
				}
				if (!_this.pd.ENDTIME || _this.pd.ENDTIME == '请选择') {
					uni.showToast({
						icon: 'none',
						title: '请选择离岗结束时间',
						duration: 1500
					});
					return;
				}
				if(new Date(_this.pd.STARTTIME) > new Date(_this.pd.ENDTIME)){
					uni.showToast({
						icon: 'none',
						title: '离岗结束时间不能早于开始时间',
						duration: 1500
					});
					return;
				}
				if (!_this.pd.DESCR) {
					uni.showToast({
						icon: 'none',
						title: '请输入离岗原因',
						duration: 1500
					});
					return;
				}
        if (this.SETUP_STATE === '2' && !_this.pd.REVIEW_USER_ID) {
          uni.showToast({
            icon: 'none',
            title: '请选择审批人',
            duration: 1500
          });
          return;
        }
        uni.showLoading({
          title: '请稍候'
        })
				uni.showModal({
					title: '温馨提示',
					content: '确定要提交申请么？',
					cancelColor: "#000000",
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.buttonloading = true
							uni.request({
								url: basePath+'/app/offduty/'+_this.msg,
								method: 'POST',
								dataType: 'json',
								header: {
									'Content-type':'application/x-www-form-urlencoded'
								},
								data: {
                  					OFFDUTY_ID:_this.pd.OFFDUTY_ID,
									STARTTIME: _this.pd.STARTTIME,
									ENDTIME: _this.pd.ENDTIME,
									DESCR: _this.pd.DESCR,
                  					REVIEW_USER_ID: _this.pd.REVIEW_USER_ID,
									CREATOR: loginUser.USER_ID,
									OPERATOR: loginUser.USER_ID,
									CORPINFO_ID: loginUser.CORPINFO_ID,
									USER_ID: loginUser.USER_ID,
								},
								success: (res) => {
									uni.hideLoading();
									this.buttonloading = false
									if ("success" == res.data.result) {
										console.info(res.data.ISREST);
										setIsRest(res.data.ISREST);
										uni.showToast({
											icon:'none',
											title: '提交申请成功',
											duration: 1500
										});
										setTimeout(function(){
											var pages = getCurrentPages();	// 获取当前页面栈
											var prePage = pages[pages.length - 2];	// 上二级页面
											prePage.$vm.initflag = true;    // A 页面 init方法 为true
											uni.navigateBack({delta: 1});
											uni.hideLoading();
										},1500);
									}else{
										uni.showToast({
											icon:'none',
											title: '系统错误',
											duration: 2000
										});
									}
								}
							});
						} else {
              uni.hideLoading();
            }
					}
				})
			},
			goback(){
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 1});
				uni.hideLoading();
			},
		}
	}
</script>

<style>
	.prevent {
			width: 100%;
			height: 100%;
			position: fixed;
			top: 0;
			left: 0;
			overflow: hidden;
		}
	.cu-form-title{
		padding: 20upx 0;
	}
	.cu-form-textarea{
		background-color: #ffffff;
		padding: 1upx 30upx 20upx;
		min-height: 100upx;
	}
	.cu-form-textarea textarea {
		height: 4.6em;
		width: 100%;
		line-height: 1.2em;
		flex: 1;
		font-size: 28upx;
		padding: 0;
	}
	.selected{
		display: flex;
		align-items: center;
		height: 100upx;
	}
	.selected .radio{
		 transform:scale(0.8);
		 margin-right: 10upx;
	}
	.group{
		display: flex;
		align-items: center;
	}
	.cu-form-group .title{
		font-size: 28upx;
		color: #000;
		font-weight: bold;
	}
	.cu-bar .action:first-child {
	    font-size: 28upx;
	}
	.cu-form-group .picker{
			color: #808080;
		}
		.picker-tree{
			color: #808080;
		}
</style>
