<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 :disabled="forbidEdit" v-model="form.LICENSE_PLATE" placeholder="请输入车牌号"></input>
        </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>
          <picker @change="PickerModel" :value="form.MODEL_INDEX" :range="modelList" range-key="NAME" :disabled="modelList.length == 0">
            <view class="picker">
              {{form.MODEL_NAME?form.MODEL_NAME:'请选择'}}
            </view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">来港事由：</view>
          <input :disabled="forbidEdit" v-model="form.COMING_REASON" placeholder="请输入来港事由"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">驾驶证照片：</view>
          {{form.driverImageList.length}}/1
        </view>
        <view class="cu-form-group" style="padding-top:20upx">
          <view class="grid col-4 grid-square flex-sub">
            <view class="bg-img" v-for="(item,index) in form.driverImageList" :key="index" @tap="showImg($event, 'driverImageList')" :data-url="form.driverImageList[index].FILEPATH">
              <image :src="form.driverImageList[index].FILEPATH" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="delImg($event, 'driverImageList')" :data-index="index" v-if="!forbidEdit">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap="chooseImg('driverImageList')" v-if="form.driverImageList.length<1 && !forbidEdit">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>
        </view>
        <view class="cu-form-group">
          <view class="title">行驶证照片：</view>
          {{form.drivingImageList.length}}/1
        </view>
        <view class="cu-form-group" style="padding-top:20upx">
          <view class="grid col-4 grid-square flex-sub">
            <view class="bg-img" v-for="(item,index) in form.drivingImageList" :key="index" @tap="showImg($event, 'drivingImageList')" :data-url="form.drivingImageList[index].FILEPATH">
              <image :src="form.drivingImageList[index].FILEPATH" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="delImg($event, 'drivingImageList')" :data-index="index" v-if="!forbidEdit">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap="chooseImg('drivingImageList')" v-if="form.drivingImageList.length<1 && !forbidEdit">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>
        </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>
          <input type="number" :disabled="forbidEdit" v-model="form.NUMBER_PEOPLE_CAR" @input="Numinput" 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="$noMultipleClicks(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,
      other:[{"PHONO_NUMBER":'',"NAME":''}],
      msg:'add',
      FOREIGNCAR_ID: '',
      modelList: [],
      approveDeptList: [],
      form: {
        SOURCE_UNIT: '',
        LICENSE_PLATE: '',
        MODEL_INDEX: '',
        MODEL: '',
        MODEL_NAME: '',
        COMING_REASON: '',
        NUMBER_PEOPLE_CAR: '',
        STARTTIME: '',
        ENDTIME: '',
        STATE: '2',
        driverImageList: [],
        drivingImageList: [],
        APPROVE_DEPARTMENT_INDEX: '',
        APPROVE_DEPARTMENT_ID: '',
        APPROVE_DEPARTMENT_NAME: ''
      },
      rules: [
        {name: 'SOURCE_UNIT', message: '请输入来源单位'},
        {name: 'LICENSE_PLATE', message: '请输入车牌号'},
        {name: 'STARTTIME', message: '请选择开始时间'},
        {name: 'ENDTIME', message: '请选择结束时间'},
        {name: 'MODEL', message: '请输入车型'},
        {name: 'COMING_REASON', message: '请输入来港事由'},
        // {name: 'NUMBER_PEOPLE_CAR', message: '请输入人员数'},
        {name: 'APPROVE_DEPARTMENT_ID', message: '请选择审批部室'},

      ],
      treeNode: [],
      forbidEdit: false,
      todayDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
      modalShow: false,
      workUnitManagerList: [],
      branchApproverList: [],
    }
  },
  onLoad(event) {
    console.log(event)
    this.getDict();
    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
            });
          }
        }
      });
    },
    chooseImg(list) {
      var _this = this
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          for (let i = 0; i < res.tempFilePaths.length; i++) {
              let img = {};
              img.id = Math.random();
              img.FILEPATH = res.tempFilePaths[i];
              _this.form[list].push(img)
          }
        }
      })
    },
    showImg(e,list) {
      let files =[];
      for(var i = 0; i < this.form[list].length; i++){
        files.push(this.form[list][i].FILEPATH)
      }
      uni.previewImage({
        urls: files,
        current: e.currentTarget.dataset.url
      });
    },
    delImg(e, list) {
      var _this = this
      var modalText = '确定要删除驾驶证照片吗？'
      if (list === 'drivingImageList') {
        modalText = '确定要删除行驶证照片吗？'
      }
      uni.showModal({
        title: '双控平台',
        content: modalText,
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            _this.form[list].splice(e.currentTarget.dataset.index, 1)
          }
        }
      })
    },
    Numinput (e){
      const o = e.target;
      const inputRule = /[^\d]/g
      this.$nextTick(function() {
        this.form.fpNum = o.value.replace(inputRule , '');
      })

    },
    addOther(){
      let o = {"PHONO_NUMBER":'',"NAME":''};
      this.other.push(o);
    },
    removeOther(index){
      this.other.splice(index,1);
    },
    goSubmit() {
      let starttime = new Date(this.form.STARTTIME).getTime()
      let endtiem = new Date(this.form.ENDTIME).getTime()
      console.log(endtiem - starttime > 86400000)
      if(endtiem - starttime > 86400000){
        uni.showToast({
          icon: 'none',
          title: "申请时间不能超过24小时",
          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
        }
      }
      if(this.form.driverImageList.length === 0){
        uni.showToast({
          icon: 'none',
          title: '请上传驾驶证照片',
          duration: 1500
        })
        return
      }
      if(this.form.drivingImageList.length === 0){
        uni.showToast({
          icon: 'none',
          title: '请上传行驶证照片',
          duration: 1500
        })
        return
      }
      var _this = this;
      let required = true
      this.rules.map(({name,message})  => {
        if (!this.form[name]) {
          uni.showToast({
            icon: 'none',
            title: message,
            duration: 1500
          });
          required = false
        }
      })
      if (!required) {
        return
      }

      uni.showLoading({
        title: '请稍候'
      })
      var fileList = [];
      for (var i = 0; i < this.form.driverImageList.length; i++) {
        var file = {};
        file.TYPE = 22;
        file.FILEPATH = this.form.driverImageList[i].FILEPATH;
        fileList.push(file);
      }
      for (var i = 0; i < this.form.drivingImageList.length; i++) {
        var file = {};
        file.TYPE = 23;
        file.FILEPATH = _this.form.drivingImageList[i].FILEPATH;
        fileList.push(file);
      }
      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.NUMBER_PEOPLE_CAR = this.other.length
      formData.PERSONJSON = JSON.stringify(this.other)
      console.info(formData)
      console.info(fileList)
      // return
      new Promise((resolve, reject) => {
        _this.submitForm(formData).then(() => {resolve();})
      }).then(() => {
        var i=0;
        _this.uploadImg(fileList,i).then(() => {resolve();})
      }).then(() => {
        uni.showToast({
          icon:'none',
          title: '保存成功',
          duration: 2000
        });
        uni.navigateBack({
          delta: 1
        });
        uni.hideLoading();
      })

    },
    submitForm(formData){
      var _this = this;
      return new Promise((resolve, reject) => {
        uni.request({
          url: basePath + "/app/foreigncar/"+_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'){
              _this.FOREIGNCAR_ID = res.data.pd.FOREIGNCAR_ID
              resolve();
            } else if( res.data.result ==='Error'){
              console.log(res.data.result ==='Error')
              uni.showToast({
                icon:'none',
                title: res.data.msg,
                duration: 2000
              });
            }

          },
          fail: (err) => {
            console.log(err)
            uni.hideLoading();
            uni.showModal({
              content: err.errMsg,
              showCancel: false
            });
          }
        })
      })
    },
    uploadImg(tempFilePaths,i){
      return new Promise((resolve, reject) => {
        var _this = this;
        if(tempFilePaths.length==0){
          resolve();
        }
        uni.showLoading({
          title: '上传中'
        })
        uni.uploadFile({
          url: basePath+'/app/imgfiles/add',
          filePath: tempFilePaths[i].FILEPATH,
          name: 'FFILE',
          formData: {
            'TYPE': tempFilePaths[i].TYPE,
            'FOREIGN_KEY': _this.FOREIGNCAR_ID
          },
          success: (res) => {
            i++;
            if (tempFilePaths.length > i) {
              _this.uploadImg(tempFilePaths, i);
            } else {
              uni.hideLoading();
              resolve();
            }
          },
          fail: (err) => {
            uni.hideLoading();
            uni.showModal({
              content: err.errMsg,
              showCancel: false
            });
          }
        })
      })
    },
    changeJobStartTime(e) {
      this.form.STARTTIME = e
    },
    changeJobEndTime(e) {
      this.form.ENDTIME = e
    },
    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
      }
    },
    PickerModel(e) {
      this.form.MODEL_INDEX = e.detail.value;
      this.form.MODEL = this.modelList[this.form.MODEL_INDEX].BIANMA;
      this.form.MODEL_NAME = this.modelList[this.form.MODEL_INDEX].NAME;
      this.$forceUpdate();//强制刷新
    },
    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();//强制刷新
    },
    //获取数据字典数据
    getDict: function () {
      var _this = this;
      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/dictionaries/getLevels?tm=' + new Date().getTime(),
        data: {DICTIONARIES_ID: 'c1d7ddc73eea4219952f28814d33b845'},
        success: function (res) {
          _this.modelList = res.data.list;
        }
      });
    },
    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>
