<template>
	<view :class="isUps == true ? 'prevent' : ''">
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true" >
			<block slot="backText">返回</block>
			<block slot="content">离岗管理</block>
      <block slot="right">
        <view @click="$noMultipleClicks(goToAdd)">申请</view>
      </block>
		</cu-custom>
    <view class="select-fixed top-fixed">
<!--      <view class="cu-bar search bg-white">
        <view class="search-form radius" style="margin-left: 0;">
          <text class="cuIcon-search"></text>
          <input @input="InputBlur" placeholder="请输入关键字"
                 confirm-type="search"></input>

        </view>
        <view class="action">
          <button class="cu-btn bg-green shadow-blur radius" @click="getQuery">搜索</button>
        </view>
      </view>
      <view class="line"></view>-->
    </view>
    <scroll-view class="dy-scroll" @scrolltolower="scrolltolower" scroll-y :style="'top:'+sTop+'px;height:calc(100vh - '+totalHeight+'px)'">
      <view v-if="list.length>0" >
        <view class="dy-list">
          <view v-for="(item,index) of list" :key="index" :data-id="item.OFFDUTY_ID"  class="dy-list-item p20">
            <view class="dy-title-flex align-center" @click="$noMultipleClicks(goToDetail,item)">
              <text>申请人:{{item.USER_NAME}}</text>
              <text v-if="item.REVIEW_USER_ID">审批人:{{ item.REVIEW_USER_NAME + ' [' + item.REVIEW_USER_DEPARTMENTNAME + ']' }}</text>
              <text v-else></text>
            </view>
            <view class="dy-subtitle-flex" @click="$noMultipleClicks(goToDetail,item)">
              <text>部门:{{item.DEPARTMENTNAME_ALL}}</text>
            </view>
            <view class="dy-subtitle-flex" @click="$noMultipleClicks(goToDetail,item)">
              <text>岗位:{{item.POSTNAME}}</text>
            </view>
            <view class="dy-subtitle-flex" @click="$noMultipleClicks(goToDetail,item)">
              <text>离岗时间:{{ item.STARTTIME }} 至 {{ item.ENDTIME }}</text>
            </view>
            <view class="dy-subtitle-flex" style="height: 34upx;" @click="$noMultipleClicks(goToDetail,item)">
              <text>
                审核状态：
                <template v-if="item.REVIEW_STATUS === '0'">待审批</template>
                <template v-else-if="item.REVIEW_STATUS === '1'">审批通过</template>
                <template v-else-if="item.ISDELETE === '1' && item.REVIEW_STATUS === '-1'">
                  <template v-if="item.CREATOR === item.OPERATOR">申请人取消</template>
                  <template v-else>审批人取消</template>
                </template>
                <template v-else-if="item.REVIEW_STATUS === '-1'">审批打回</template>
                <template v-else-if="item.REVIEW_STATUS === '2'">无需审批</template>
              </text>
              <view>
                <text v-if="item.REVIEW_STATUS === '0'
                  && item.ENDTIME >= todayDate
                    && (item.REVIEW_USER_ID === LoginUserId || !validStr(item.REVIEW_USER_ID) && LoginUserIsleader === '1')">
                  <button class="cu-btn bg-blue margin-tb-sm" @click="$noMultipleClicks(handleReview,item.OFFDUTY_ID)">审批</button>
                </text>
                <text v-if="item.REVIEW_STATUS === '0' && item.STARTTIME >= todayDate
                  && (item.REVIEW_USER_ID === LoginUserId || item.USER_ID === LoginUserId)">
                  <button class="cu-btn bg-red margin-tb-sm" style="margin-left: 15px" @click="$noMultipleClicks(handleCancel,item.OFFDUTY_ID)">取消</button>
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-else-if="dataFlag=='noData'" class="dy-null">
        <view class="dy-null-img">
          <image :src="background[dataFlag].url" mode=""></image>
        </view>
        <view class="dy-null-title">
          {{background[dataFlag].msg}}
        </view>
      </view>
      <view class="cu-tabbar-height"></view>
    </scroll-view>

    <view :class="['cu-modal',{'show':modalShow}]" v-if="modalShow">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">{{ modalType === 'review' ? '离岗审批' : '取消原因' }}</view>
          <view class="action" @tap="modalShow = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view>
          <view class="wrapper">
            <view class="handCenter">
              <view class="form">
                <view class="wui-form-list">
                <radio-group v-if="modalType === 'review'" v-model="form.REVIEW_STATUS" @change = "radioChange">
                  <label class="answer-lable">
                    <radio class="blue" :class="form.REVIEW_STATUS=='1'?'checked':''" :checked="form.REVIEW_STATUS=='1'?true:false" value="1"></radio>
                    <text class="title">通过</text>
                  </label>
                  <label class="answer-lable">
                    <radio class="blue" :class="form.REVIEW_STATUS=='-1'?'checked':''" :checked="form.REVIEW_STATUS=='-1'?true:false" value="-1"></radio>
                    <text class="title">打回</text>
                  </label>
                </radio-group>
                </view>
                <view class="wui-form-list">
                  <textarea v-model="form.REVIEW_DESC" :placeholder="'请输入'+ (modalType === 'review' ? '审批意见' : '取消原因')"></textarea>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button :loading = "buttonloading" class="cu-btn bg-green margin-left" @click="$noMultipleClicks(goSubmit)">提交</button>
            <button class="cu-btn bg-blue margin-left" @click="modalShow = false">关闭</button>
          </view>
        </view>
      </view>
    </view>
	</view>
</template>

<script>
	import {
		basePath,corpinfoId,deptId,loginUser,formatDate,loginSession,baseImgPath,setIsRest
	} from '@/common/tool.js';
	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,
        dataFlag:'noData',
        sTop:0,
        totalHeight:0,
        list:[],//返回数据
        showCount:10,//分页参数--每页数据条数
        currentPage:1,//分页参数--页数
        totalCount:0,//分页参数--初始化页数
        isEnd:false,//防止多次刷新
        totalPage:0,//分页参数--分页数量
        NameLikes : '',
				noClick:true,

        modalShow: false, // 审批窗口控制
        modalType: 'review',
        form: {
          OFFDUTY_ID: '',
          REVIEW_STATUS: '',
          REVIEW_DESC: ''
        },
        LoginUserId: '',
        LoginUserIsleader: '',
        todayDate: ''

			}
		},
    onReady() {
      let that=this;
      let CustomBar = this.CustomBar;
      uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
        success(res) { //成功回调函数
          let titleH=uni.createSelectorQuery().select(".top-fixed"); //想要获取高度的元素名（class/id）
          titleH.boundingClientRect(data=>{
            that._data.sTop=data.height  //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
            that.totalHeight = data.height+CustomBar
          }).exec()
        }
      })
    },
		onLoad(event){
      this.LoginUserId = loginUser.USER_ID
      this.LoginUserIsleader = loginUser.ISLEADER
      this.todayDate =  formatDate(new Date(), 'yyyy-MM-dd');
		},
    onShow() {
      //页面显示或从后台跳回小程序时显示此页面时触发，从跳转页面返回时触发，不能传递参数
      var _this = this;
      _this.background = require('@/common/background.json');
      _this.showCount = -1;
      _this.currentPage = 1;
      _this.list = [];
      _this.isEnd = false;
      _this.getData();
      loginSession();
    },
		methods: {
      goToAdd(){
        uni.navigateTo({
          url: '/pages/my/offduty/offduty-detail'
        });
      },
      getQuery(){	//搜索按钮事件
        var _this = this;
        _this.showCount = -1;
        _this.currentPage = 1;
        _this.list = [];
        _this.isEnd = false;
        _this.getData();
      },
      InputBlur(e){
        this.NameLikes = e.detail.value
      },
      // 滑动到底方法
      scrolltolower(){
        var _this = this;
        _this.showCount = -1;
        _this.currentPage = _this.currentPage + 1;
        _this.isEnd = false;
        if(_this.totalPage >= _this.currentPage){
          _this.getData();//开始分页查询
        }
      },
      getData() {
        var _this = this;
        if (_this.isEnd) {
          return
        }else{
          this.isEnd =true;
        }
        uni.showLoading({
          title:"加载中..."
        });//加载中动画
        uni.request({
          url: basePath + '/app/offduty/list?showCount='+_this.showCount+'&currentPage='+_this.currentPage,
          method: 'POST',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
            // ISMAIN:loginUser.ISMAIN,
            // ISSUPERVISE:loginUser.ISSUPERVISE,
            DEPARTMENT_ID:loginUser.DEPARTMENT_ID,
            TYPE: 'edit'
          },
          success: (res) => {
            uni.hideLoading();//结束加载中动画
            if (res.data != null) {
              _this.totalPage = res.data.page.totalPage;
              if(_this.list.length == 0){
                _this.list = res.data.varList;
              }else{
                if(res.data.varList != null){
                  _this.list2 = res.data.varList;
                  _this.list = _this.list.concat(_this.list2);
                }
              }
            }
          }
        });
      },
      goToDetail(item) {
        if (item.REVIEW_STATUS === '0' && item.STARTTIME >= this.todayDate && item.USER_ID === this.LoginUserId) {
          uni.navigateTo({
            url: '/pages/my/offduty/offduty-detail?OFFDUTY_ID='+item.OFFDUTY_ID
          });
        } else {
          uni.navigateTo({
            url: '/pages/my/offduty/offduty-info?OFFDUTY_ID='+item.OFFDUTY_ID
          });
        }
      },
      resetForm() {
        this.form = {
          OFFDUTY_ID: '',
          REVIEW_STATUS: '',
          REVIEW_DESC: ''
        }
      },
      handleReview(id) {
        this.resetForm()
        this.form.OFFDUTY_ID = id
        this.modalType = 'review'
        this.modalShow = true
      },
      handleCancel(id) {
        this.resetForm()
        this.form.OFFDUTY_ID = id
        this.form.REVIEW_STATUS = '-1'
        this.modalType = 'cancel'
        this.modalShow = true
      },
      radioChange(e)  {
        this.form.REVIEW_STATUS = e.detail.value;
      },
      goSubmit() {
        var msg = (this.modalType === 'review' ? '审批意见' : '取消原因')
        if(this.modalType === 'review') {
          console.log(this.form.REVIEW_STATUS)
          if (!this.validStr(this.form.REVIEW_STATUS)) {
            uni.showToast({
              icon: 'none',
              title: '请选择审批结果',
              duration: 1500
            });
            return;
          }
        }
        if (!this.validStr(this.form.REVIEW_DESC)) {
          uni.showToast({
            icon: 'none',
            title: '请输入' + msg,
            duration: 1500
          });
          return;
        }
        var _this = this;
        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.modalType,
                method: 'POST',
                dataType: 'json',
                header: {
                  'Content-type':'application/x-www-form-urlencoded'
                },
                data: {
                  OFFDUTY_ID:_this.form.OFFDUTY_ID,
                  REVIEW_STATUS:_this.form.REVIEW_STATUS,
                  REVIEW_DESC:_this.form.REVIEW_DESC,
                  OPERATOR:_this.LoginUserId
                },
                success: (res) => {
                  uni.hideLoading();
                  _this.buttonloading = false
                  if ("success" == res.data.result) {
                    uni.showToast({
                      icon:'none',
                      title: '信息保存成功',
                      duration: 1500
                    });
                    _this.modalShow = false
                    _this.getQuery()
                  }else{
                    uni.hideLoading();
                    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();
			},
      validStr(str) {
        if (str != null && ((str != '' && typeof (str) != 'undefined' && str != 'undefined' && str != {}) || typeof (str) === 'number')) { return true }
        return false
      },
		}
	}
</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;
		}
  .answer-lable{
    text-align: center;
    vertical-align: center;
    margin-bottom: 20upx;
  }
  .answer-lable:last-child{
    margin-bottom: 0;
  }
  .answer-lable radio{
    margin-left: 20upx;
    margin-right: 10upx;
  }
  .title {
    text-align: center;
    font-size: 40upx;
  }
  .cu-modal{
    z-index: 1;
  }
</style>
