<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">外来人员入场申请</block>
    </cu-custom>
    <view class="form">
      <view class="wui-form-list">
        <view class="cu-form-group">
          <view class="title">来源单位:</view>
          <input :disabled="forbidEdit" v-model="form.SOURCE_UNIT" placeholder="请输入来源单位"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">人数:</view>
          <input type="number" :disabled="forbidEdit" v-model="form.ADMISSION_NUMBER" @input="Numinput" placeholder="请输入人数"></input>
        </view>
        <view class="add_pard_box">
          <view class="add_pard_btns">
            <view class="add_pard_b" style="width: 100px;">
              <button class="cu-btn round bg-blue" @click="addOther">添加人员</button>
            </view>
          </view>
          <view class="add_pard_item" v-for="(item,index) of other">
            <view class="add_pard_del" v-if="index>0" @click="removeOther(index)">
              <text class="cuIcon-roundclosefill text-red f40"></text>
            </view>
            <view class="cu-form-group">
              <view class="title">姓名</view>
              <input :disabled="forbidEdit" v-model="item.NAME" placeholder="请输入姓名"></input>
            </view>
            <view class="cu-form-group">
              <view class="title">手机号</view>
              <input :disabled="forbidEdit" v-model="item.PHONO_NUMBER" maxlength="11" placeholder="请输入手机号"></input>
            </view>
          </view>
        </view>
        <view class="cu-form-group">
          <view class="title">申请用时(开始):</view>
          <ruiDatePicker v-if="!forbidEdit" :start="todayDate" fields="minute" :value="form.STARTTIME"
                         @change="changeJobStartTime"></ruiDatePicker>
          <text v-else>{{ form.BOARD_INSTALL_TIME }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">申请用时(结束):</view>
          <ruiDatePicker v-if="!forbidEdit" :start="todayDate" fields="minute" :value="form.ENDTIME"
                         @change="changeJobEndTime"></ruiDatePicker>
          <text v-else>{{ form.BOARD_DISASSEMBLE_TIME }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">入场事由:</view>
          <input :disabled="forbidEdit" v-model="form.SUBJECT_MATTER" placeholder="请输入入场事由"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">审批部室</view>
          <picker @change="PickerApprove" :value="form.APPROVE_DEPARTMENT_INDEX" :range="approveDeptList" range-key="NAME" :disabled="approveDeptList.length == 0" @click="isBlankList('approve')">
            <view class="picker">
              {{form.APPROVE_DEPARTMENT_NAME?form.APPROVE_DEPARTMENT_NAME:'请选择'}}
            </view>
          </picker>
        </view>
      </view>
    </view>
    <view class="cu-bar btn-group" style="margin-top: 30upx;">
      <button v-if="!forbidEdit" class="cu-btn bg-blue margin-tb-sm lg" @click="goSubmit()">提交
      </button>
      <button v-if="forbidEdit" class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goback)">返回</button>
    </view>
    <view class="padding flex flex-direction"></view>
  </view>
</template>

<script>
import {
  basePath,
  corpinfoId,
  loginUser,
  loginSession,
  formatDate,
  baseImgPath
} from '@/common/tool.js';
import tkiTree from "@/components/select-tree/select-tree.vue"
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
import sign from '@/components/sign/sign.vue';

export default {
  components: {
    tkiTree,
    ruiDatePicker,
    sign
  },
  data() {
    return {
      noClick: true,
      BLINDBOARD_ID: '',
      otherUserList:[] ,
      other:[],
      msg:'add',
      approveDeptList: [],
      form: {
        SOURCE_UNIT: '',
        LICENSE_PLATE: '',
        MODEL: '',
        STARTTIME: '',
        ENDTIME: '',
        STATE: '2',
        APPROVE_DEPARTMENT_INDEX: '',
        APPROVE_DEPARTMENT_ID: '',
        APPROVE_DEPARTMENT_NAME: ''
      },
      rules: [
        {name: 'SOURCE_UNIT', message: '请输入来源单位'},
        {name: 'ADMISSION_NUMBER', message: '请输入人数'},
        {name: 'SUBJECT_MATTER', message: '请选择入场事由'},
        {name: 'STARTTIME', message: '请输入开始时间'},
        {name: 'ENDTIME', message: '请选择结束时间'},
        {name: 'APPROVE_DEPARTMENT_ID', message: '请选择审批部室'}
      ],
      treeNode: [],
      forbidEdit: false,
      todayDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
      modalShow: false,
      imgList: [],
      workUnitManagerList: [],
      branchApproverList: [],
    }
  },
  onLoad(event) {
    console.log(event)
    this.getUserList('approveDeptList')
    if (event.id) {
      this.FOREIGNCAR_ID = event.id
      this.forbidEdit = true
      this.getData();
    }
  },
  methods: {
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/foreigncar/getForeignCarById',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          FOREIGNCAR_ID: _this.FOREIGNCAR_ID,
        },
        success: (res) => {
          if ("success" === res.data.result) {
            this.form = res.data.varList[0];
            uni.hideLoading();
          } else if ("exception" === res.data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    Numinput (e){
      const o = e.target;
      const inputRule = /[^\d]/g
      this.$nextTick(function() {
        this.form.fpNum = o.value.replace(inputRule , '');
      })

    },
    goSubmit() {
      let starttime = new Date(this.form.STARTTIME).getTime()
      let endtiem = new Date(this.form.ENDTIME).getTime()
      if(endtiem - starttime > 86400000){
        uni.showToast({
          icon: 'none',
          title: "申请时间不能超过24小时",
          duration: 1500
        });
        return
      }
      if (this.other.length <= 0) {
        uni.showToast({
          icon: 'none',
          title: "请录入来访人员",
          duration: 1500
        });
        return
      }
      var myreg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      for (let i=0;i<this.other.length;i++){
        var item = this.other[i]
        if (item.NAME === '') {
          uni.showToast({
            icon: 'none',
            title: "人员姓名不能为空",
            duration: 1500
          });
          return
        }
        if (item.PHONO_NUMBER === '') {
          uni.showToast({
            icon: 'none',
            title: "手机号不能为空",
            duration: 1500
          });
          return
        }
        if (item.PHONO_NUMBER.length !== 11 || !myreg.test(item.PHONO_NUMBER)) {
          uni.showToast({
            icon: 'none',
            title: "请输入正确的11位手机号",
            duration: 1500
          });
          return
        }
      }
      var _this = this;
      let required = true
      uni.showLoading({
        title: '请稍候'
      })
      this.rules.map(({name,message})  => {
        if (!this.form[name]) {
          uni.showToast({
            icon: 'none',
            title: message,
            duration: 1500
          });
          required = false
        }
      })
      if (!required) {
        return
      }
      const formData={}
      Object.keys(this.form).map(key => {
        formData[key]=this.form[key]
      })
      formData.CORPINFO_ID=corpinfoId
      formData.loginUserId=loginUser.USER_ID
      formData.loginUserName=loginUser.USERNAME
      formData.DEPARTMENT_ID=loginUser.DEPARTMENT_ID
      formData.other = JSON.stringify(_this.other)
      uni.request({
        url: basePath + "/app/outsiders/"+_this.msg,
        method: 'POST',
        dataType: 'json',
        header:{
          'Content-type':'application/x-www-form-urlencoded'
        },
        data: formData,
        success: (res) => {
          uni.hideLoading();
          console.log(res.data.result)
          if(res.data.result == 'success'){
            uni.showToast({
              icon:'none',
              title: '保存成功',
              duration: 2000
            });
            _this.goback()
          } else if( res.data.result ==='Error'){
            console.log(res.data.result ==='Error')
            uni.showToast({
              icon:'none',
              title: res.data.msg,
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
    changeJobStartTime(e) {
      this.form.STARTTIME = e
    },
    changeJobEndTime(e) {
      this.form.ENDTIME = e
    },
    zgtreeCancel(e) {
      this.isUps = false;
    },
    addOther(){
      var _this=this;
      let o = {"PHONO_NUMBER":'',"NAME":'',index:-1};
      _this.other.push(o);
      let index=_this.other.length-1;
      _this.otherUserList[index]=[];
    },
    removeOther(index){
      this.other.splice(index,1);
      this.otherUserList.splice(index,1);
    },
    getUserList(list) {
      //发送 post 请求
      var _this = this;
      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/app/sys/listForDoor',
        data: {
          FIELD_ITEM: 'IS_EXAMINE_AND_APPROVE',
          CORPINFO_ID: corpinfoId,
          tm: new Date().getTime()
        },
        success: function (res) {
          if ("success" == res.data.result) {
            _this[list] = res.data.list;
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },
    isBlankList(userType) {
      switch(userType) {
        case 'approve':
          if(this.approveDeptList.length == 0) {
            uni.showToast({
              icon: 'none',
              title: '暂无对应部门,请先配置审核审批权限',
              duration: 1500
            })
          }
          break
      }
    },
    PickerApprove(e) {
      this.form.APPROVE_DEPARTMENT_INDEX = e.detail.value;
      this.form.APPROVE_DEPARTMENT_ID=this.approveDeptList[this.form.APPROVE_DEPARTMENT_INDEX].DEPARTMENT_ID;
      this.form.APPROVE_DEPARTMENT_NAME=this.approveDeptList[this.form.APPROVE_DEPARTMENT_INDEX].NAME;
      this.$forceUpdate();//强制刷新
    },
    goback() {
      uni.navigateBack({
        delta: 1
      });
      uni.hideLoading();
    },
  }
}
</script>

<style>
.right_icon {
  position: relative;
  padding-right: 36upx;
  width: 200upx;
  text-align: right;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.right_icon ::after {
  font-family: cuIcon;
  display: block;
  content: "\e6a3";
  position: absolute;
  font-size: 17px;
  color: #8799a3;
  line-height: 50px;
  width: 30px;
  text-align: center;
  top: -28upx;
  bottom: 0;
  right: -22upx;
  margin: auto;
}

.modal_content {
  display: flex;
  text-align: left;
}

.modal_left {
  flex-basis: 50%;
  padding: 50upx 20upx;
  border-right: 1px solid #000000;
}

.modal_right {
  flex-basis: 50%;
  padding: 50upx;
}

.modal_left_title, .modal_right_title {
  font-size: 16px;
  color: #000000;
  font-weight: 700;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 0 30upx;
  min-height: 100upx;
  background-color: #ffffff;
  border-bottom: 1upx solid #ddd;
}

.checkbox-item:last-child {
  border-bottom: none;
}
</style>