<template>
  <div class="flexOne">
    <div style="padding: 30px 0;" v-loading='loading'>
      <div class="leaveApprovalItem" v-for="(item,index) in list">
        <span class="fl"><em v-if="item.required"></em>{{item.title}}</span>
        <el-select v-if="item.formType=='selectField'" v-model="item.value" @change='isYearLeave(item.value)'>
          <el-option v-for='item in newArr(item.category)' :label='item.label' :value='item.value' :key='item.value'></el-option>
        </el-select>
        <el-date-picker v-if="item.formType=='dateTimeField'&&!yearLeave" :picker-options="pickerOptions1" :clearable='false' v-model="item.value" value-format='yyyy-MM-dd HH:mm:ss' type="datetime" placeholder="选择日期时间" @change='getDuration(list,index)'></el-date-picker>
        <el-date-picker v-if="item.formType=='dateTimeField'&&yearLeave" :picker-options="pickerOptions" :clearable='false' v-model="item.value" value-format='yyyy-MM-dd' type="date" placeholder="选择日期时间" @change='getDuration(list,index)'></el-date-picker>

        <el-select class='w80' v-if="item.key=='startTime'&&yearLeave" v-model='startVal' @change='getDuration(list,index)'>
          <el-option label='上午' value='1'></el-option>
          <el-option label='下午' value='2'></el-option>
        </el-select>

        <el-select class='w80' v-if="item.key=='endTime'&&yearLeave" v-model='endVal' @change='getDuration(list,index)'>
          <el-option label='上午' value='1'></el-option>
          <el-option label='下午' value='2'></el-option>
        </el-select>

        <el-input v-if="item.formType=='durationField'" class='w220' v-model='item.value' :disabled="true"></el-input>
        <el-input v-if="item.formType=='textareaField'" type='textarea' :rows="5" maxlength='200' v-model='item.value' class='w300'></el-input>
        <el-input v-if="item.formType=='textField'" type='textarea' :rows="5" maxlength='200' v-model='item.value' class='w300'></el-input>
        <div v-if="item.formType=='childField'" style=" display: inline-block;">
          <div v-for="(i,index) in item.value" style="border-bottom: 1px solid #ccc; margin: 0 0 20px 0;">
            <P style="font-size: 12px; height:40px;">行程{{index+1}}
              <input type="button" v-if='item.value.length>1' class="hollowbtn fr" @click="deleteItem(item.value,index)" value="删除" />
            </P>
            <p v-for="(o,index) in i" style="height: 50px;">
              <span style="display: inline-block; font-size: 12px; color: #666; width: 80px; "><em class='emMust' v-if="o.required"></em>{{o.title}}</span>
              <el-select v-if="o.formType=='selectField'" v-model='o.value'>
                <el-option v-for='item in newArr(o.category)' :label='item.label' :value='item.value' :key='item.value'></el-option>
              </el-select>
              <el-input v-if="o.formType=='textField'" class='w217' v-model='o.value'></el-input>
              <el-date-picker @change='getDuration(i,index)' :clearable='false' v-if="o.formType=='dateTimeField'" v-model="o.value" value-format='yyyy-MM-dd HH:mm:ss' type="datetime" placeholder="选择日期时间"></el-date-picker>
              <el-input v-if="o.formType=='durationField'" class='w217' v-model='o.value' :disabled="true"></el-input>
            </p>
          </div>
          <p style="margin-bottom: 15px;"><input type="button" class="normalBtn" value="添加行程" @click="addNode" /></p>
        </div>
        <el-input v-if="item.formType=='totalDurationField'" v-model='item.value' class='w300' :disabled="true"></el-input>
        <el-upload v-if="item.formType=='imageField'" :file-list="fileList" :http-request="uploadTest" :multiple="true" :limit="9" list-type="picture-card" :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-exceed="handleExceed" action="">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog custom-class='w800' title='图片详情' :visible.sync="dialogVisible" center>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>
    </div>
    <div class="leaveApprovalItem">
      <span>&nbsp;</span>
      <input type="button" class="hollowFixedBtn" value="取消" @click="goback" /> &nbsp;&nbsp;
      <input type="button" class="normalBtn" value="提交" @click="saveLeaveFor" />
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {
    UploadSelfFile
  } from '../../api/common/common'
  import {
    getDictValueList,
    calculateDuration,
    getleaveCmd
  } from '../../api/administration/administration';
  export default {
    data() {
      return {
        pickerOptions: {
          disabledDate: (time) => { //disabledDate true 为禁止选择
            return time.getTime() < Date.now() + 1000 * 60 * 60 * 24 * (this.keyContentBefor - 1)
          }
        },
        pickerOptions1: {
          disabledDate: (time) => { //disabledDate true 为禁止选择
            return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
          }
        },
        startVal: '1',
        endVal: '1',
        fileList: [],
        submitFileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        loading: false,
        yearLeave: false,
        workFlowId: '0',
        type: '',
        cmd: '',
        submitCmd: '',
        msg: {},
        list: [],
        totalList: [],
        keyContent: '',
        keyContentBefor: '',
        lunchTime: '',
      }
    },
    methods: {
      getLunchTime() {
        getDictValueList({Key: 'SK_AskForLeaveSet_LunchBreak'}).then(res => {
          if(res.Code == 1) {
            this.getList()
            if(res.Data[0].Content!=''&&res.Data[0].Content!=null)
            {
              this.lunchTime = res.Data[0].Content
            }else{
              this.lunchTime='12:00-13:00'
            }
          }
        }).catch(() => {
        })
      },
      getKey() {
        getDictValueList({Key: 'SK_AskForLeaveSet_Month'}).then(res => {
          if(res.Code == 1) {
            this.keyContent = res.Data[0].Content
          }
        }).catch(() => {
        })
      },
      getKeyBefore() {
        getDictValueList({Key: 'SK_AskForLeaveSet_Befor'}).then(res => {
          if(res.Code == 1) {
            this.keyContentBefor = res.Data[0].Content
          }
        }).catch(() => {
        })
      },
      isYearLeave(val) {
        if(val == 1) {
          this.yearLeave = true
        } else {
          this.yearLeave = false
        }
        this.list.forEach(item => {
          if(item.formType == 'dateTimeField' || item.formType == 'durationField') {
            item.value = ''
          }
        })
      },
      uploadTest(file) { //上传11
        let newArr = [];
        newArr.push(file.file)
        UploadSelfFile('Temporary', file.file, x => {
          console.log(x)
          let url = x.FileUrl
          this.submitFileList.push(url)
          this.fileList.push({
            url: x.FileUrl
          })
        });
      },
      handleRemove(file) { //删除
        this.fileList.forEach((item, index) => {
          if(item.url == file.url) {
            this.fileList.splice(index, 1)
          }
        })
        this.submitFileList.forEach((item, index) => {
          if(item == file.url) {
            this.submitFileList.splice(index, 1)
          }
        })

      },
      handlePictureCardPreview(file) { //查看大图
        this.dialogVisible = true;
        this.dialogImageUrl = file.url;
      },
      handleExceed(files, fileList) {
        this.$message.warning('最多只能上传9张图片！');
      },
      goback() {
        history.back(-1)
      },
      newArr(obj) {
        let arr = []
        obj.forEach(item => {
          for(let key in item) {
            if(item.hasOwnProperty(key)) {
              arr.push({
                label: key,
                value: item[key]
              })
            }
          }
        })
        return arr;
      },
      addNode() {
        let additem = {}
        this.list.forEach(item => {
          if(item.formType == 'childField') {
            additem = JSON.parse(JSON.stringify(item.value[0]))
            additem.forEach(item => {
              item.value = '';
            })
            item.value.push(additem)
          }
        })
      },
      deleteItem(arr, index) {
        this.totalList.splice(index, 1);
        let totalDurationField = 0;
        this.totalList.forEach(item => {
          totalDurationField += item
        })
        arr.splice(index, 1)
        this.list.forEach(item => {
          if(item.formType == 'totalDurationField') {
            item.value = totalDurationField;
          }
        })
      },
      getList() {

        getleaveCmd({
          workFlowId: this.workFlowId
        },
          this.cmd
        ).then(res => {
          this.list = res.Data
          this.list.forEach(item => {
            if(item.formType == 'selectField' && item.value == 0) {
              item.value = '';
            }
            if(item.formType == 'imageField' && item.value.length > 0) {
              item.value.forEach(item => {
                this.fileList.push({
                  url: item
                })
                this.submitFileList.push(item)
              })
            }
          })
          if(this.list[0].value==1)
          {

            this.yearLeave = true
            let _start=this.list[1].value.split(' ')[1]
            let _end=this.list[2].value.split(' ')[1]
            let _startLunchTime=this.lunchTime.split('-')[0]+':00'
            let _endLunchTime=this.lunchTime.split('-')[1]+':00'
            this.list[1].value=this.list[1].value.split(' ')[0]
            this.list[2].value=this.list[2].value.split(' ')[0]
            if(_start<_startLunchTime){
              this.startVal='1'
            }else{
              this.startVal='2'
            }

            if(_end<_endLunchTime){
              this.endVal='1'
            }else{
              this.endVal='2'
            }
          }else{
            this.yearLeave = false
          }
        }).catch(() => {

        })
        // this.apipost(this.cmd, {
        //   workFlowId: this.workFlowId
        // }, res => {
        //   if(res.data.resultCode == 1) {
        //
        //   }
        // }, err => {})
      },
      getDuration(obj, index) {
        let starTime = ''
        let endTime = ''
        if(!this.yearLeave) {
          obj.forEach(item => {
            if(item.key == 'startTime') {
              starTime = item.value
            }
            if(item.key == 'endTime') {
              endTime = item.value
            }
          })
        } else {
          obj.forEach(item => {
            if(item.key == 'startTime') {
              let _startMonth = item.value.substring(6, 7)
              if(_startMonth != '' && (this.keyContent).indexOf(_startMonth) != '-1') {
                this.$message.warning("该月份不能请年假！")
                item.value = ''
              } else {
                if(this.startVal === '1') {
                  starTime = item.value + ' 00:00:00'
                }
                if(this.startVal === '2') {
                  starTime = item.value + ' ' + this.lunchTime.split('-')[1]
                }
              }
            }
            if(item.key == 'endTime') {
              let _endMonth = item.value.substring(6, 7)
              if(_endMonth != '' && (this.keyContent).indexOf(_endMonth) != '-1') {
                this.$message.warning("该月份不能请年假！")
                item.value = ''
              } else {
                if(this.endVal === '1') {
                  endTime = item.value + ' ' + this.lunchTime.split('-')[0]
                }
                if(this.endVal === '2') {
                  endTime = item.value + ' 23:59:59'
                }
              }
            }
          })
        }
        if(starTime != '' && endTime != '') {
          calculateDuration({
            startTime: starTime,
            endTime: endTime,
            templateId: this.type,
            LunchTime: this.lunchTime
          }).then(res => {
            if(res.Code == 1) {
              this.totalList = [];
              obj.forEach(item => {
                if(item.formType == 'durationField') {
                  item.value = res.Data.duration;
                  let totalDurationField = 0;
                  this.list.forEach(item => {
                    if(item.formType == 'childField') {
                      item.value.forEach(i => {
                        i.forEach(o => {
                          if(o.formType == 'durationField' && o.value != '') {
                            totalDurationField += parseFloat(o.value);
                            this.totalList.push(parseFloat(o.value))
                          }
                        })
                      })
                    }
                  })
                  this.list.forEach(item => {
                    if(item.formType == 'totalDurationField') {
                      item.value = totalDurationField;
                    }
                  })
                }
              })
            }
          }).catch(() => {

          })


        }

      },
      saveLeaveFor() {

        let _isOk = true
        this.loading = true
        this.list.forEach(item => {

          if(item.formType == 'imageField') {
            Vue.set(this.msg, item.key, this.submitFileList)
          }

          if(item.formType != "childField" && item.formType != 'imageField') {
            Vue.set(this.msg, item.key, item.value)
            if(item.required == true) {
              if(item.value != '' && item.value != 0) {} else {
                _isOk = false
              }
            }
          }

          if(item.formType == "childField") {
            let insideMsg = []
            item.value.forEach(i => {
              if(i.formType == "childField") {
                insideMsg = item.key
              }
              let objItem = {}
              i.forEach(o => {
                Vue.set(objItem, o.key, o.value)
                if(o.required == true) {
                  if(o.value != '') {} else {
                    _isOk = false
                  }
                }
              })
              insideMsg.push(objItem)
            })
            Vue.set(this.msg, item.key, insideMsg)
          }

        })
        if(!_isOk) {
          this.$message.error('带红色星号为必填项！')
          this.loading = false
          return
        }
        this.msg.Id = this.workFlowId;
        this.msg.LunchTime = this.lunchTime;

        if(this.msg.askforleaveType == '1') {
          if(this.startVal === '1') {
            this.msg.startTime = this.msg.startTime + ' 00:00:00'
          }
          if(this.startVal === '2') {
            this.msg.startTime = this.msg.startTime + ' ' + this.lunchTime.split('-')[1]
          }
          if(this.endVal === '1') {
            this.msg.endTime = this.msg.endTime + ' ' + this.lunchTime.split('-')[0]
          }
          if(this.endVal === '2') {
            this.msg.endTime = this.msg.endTime + ' 23:59:59'
          }
        }
        getleaveCmd(this.msg,this.submitCmd).then(res => {
          if(res.Code == 1) {
            this.$message.success(res.Message)
            this.loading = false
          }else {
            this.$message.warning(res.Message)
            this.loading = false
          }
        }).catch(() => {
          this.loading = false

        })
      },
    },
    mounted() {
      this.getLunchTime()
      this.msg.templateId = this.$route.query.templateId
      this.type = this.$route.query.templateId
      this.workFlowId = this.$route.query.workFlowId
      this.cmd = this.$route.query.cmd
      this.submitCmd = this.$route.query.submitCmd
      this.getKey()
      this.getKeyBefore()

    },
  }
</script>

<style>
  @import "../financial/css/cssReset.css";

  .leaveApprovalTitle {
    margin: 30px 0;
    height: 14px;
    line-height: 14px;
    text-indent: 10px;
    border-left: 3px solid #E95252;
    font-size: 14px;
  }

  .leaveApprovalItem {
    min-height: 40px;
    margin-bottom: 20px;
  }

  .emMust:before {
    content: "*";
    color: red;
    margin-right: 5px;
    font-style: normal;
    font-size: 16px;
  }

  .leaveApprovalItem>span>em:before {
    content: "*";
    color: red;
    margin-right: 5px;
    font-style: normal;
    font-size: 16px;
  }

  .leaveApprovalItem>span {
    font-size: 12px;
    color: #666;
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 20px;
  }
</style>
