<template>
<div class='container'>
  <div class='list-item' v-for='(v,i) in schedule' :key='i'>
    <div class='schedule'>
      <div class='time'>{{v.schedule_Date}}</div>
      <div class='locate'><img src='/static/imgs/community.png'>{{v.comm_Name}}</div>
    </div>
    <button type='primary' @tap='changeSchedule(i)' :disabled='changing'>调班</button>
    <button type='primary' @tap='replaceSchedule(i)' :disabled='replace'>代班</button>
  </div>
  <NoData v-if='loaded && schedule.length==0' paddingTop=0 />
  <!--调班-->
  <div v-if='changing' class='change-box-mask' @touchmove.stop=''>
    <div class='change-box' @tap.stop=''>
      <div class='info'>
        <div class='title'>值班社区</div>
        <div class='value'>{{schedule[changingIndex].comm_Name}}</div>
      </div>
      <div class='info'>
        <div class='title'>值班日期</div>
        <div class='value'>{{schedule[changingIndex].schedule_Date}}</div>
      </div>
      <div class='info'>
        <div class='title'>调班日期</div>
        <picker mode='date' :start='tomorrow' :value='initialDateValue' class='value' style='color: #AA001A;' @change='pickerConfirm'>{{targetDate || '点击选择调班的目标日期'}}</picker>
      </div>
      <div class='btn'>
        <button type='primary' @tap='cancel'>取消</button>
        <button type='warn' @tap='confirm' :disabled='!targetDate || submitting'>确认</button>
      </div>
    </div>
  </div>
  <!--代班-->
  <form @submit='commit'>
    <div v-if='replace' class='change-box-mask' @touchmove.stop=''>
        <div class='change-box' @tap.stop=''>
        <div class='info'>
          <div class='title'>代班人</div>
          <picker :value='LawFirm.index' :range='LawFirm.columnOne' @change="pickerConfirmLawFirm($event,'LawFirm')" name="name">
            <div hover-class='hover'>{{LawFirm.label}}</div>
          </picker>
        </div>
        <div class='info'>
          <div class='title'>事由</div>
        </div>
        <textarea class="reason" name="cause" v-model = "cause" placeholder="请输入事由" :value="cause" ></textarea>
        <div class='btn'>
          <button type='primary' @tap='cancel'>取消</button>
          <button type='warn' form-type='submit' hover-class='fade'  :disabled='commiting'>确认</button>
        </div>
      </div>
    </div>
  </form>
</div>
</template>

<script>
import NoData from '@/components/NoData'
const week = ['日','一','二','三','四','五','六']
export default {
  components:{ NoData },
  data() {
    return {
      schedule: [],
      loaded: false,
      changing: false,
      changingIndex: 0,
      replace: false,
      replaceIndex: 0,
      tomorrow: '',
      targetDate: '',
      submitting: false,
      cause: '',
      sub_id: '',
      SCID: '',
      sub_date: '',
      LawFirm: {
        columnOne: [],
        index: 0,
        arrStruct: [],
        label: '点击选择代班人'
      }
    }
  },
  computed: {
    initialDateValue() {
      return this.targetDate.substring(0,10) ||
        (this.schedule.length ? this.schedule[this.changingIndex].schedule_Date.substring(0,10) : '')
    }
  },
  methods: {
    getSchedule(showLoading = true){
      this.loaded = false
      if(showLoading) wx.showLoading({ title: '正在加载' })
      wx.request({
        url: this.rootUrl + 'sch/schDatebyliid',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: { sessionID: wx.getStorageSync('sessionID') },
        success: res => {
          console.log(res.data)
          if (res.statusCode == '500') {
            this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => this.getSchedule(showLoading))
          } else {
            this.schedule = []
            this.schedule = res.data
            this.schedule.forEach( v => {
              v.schedule_Date = this.service.correctTime(v.schedule_Date) +
              ' (星期' + week[this.service.correctTime(v.schedule_Date,'DateObj').getDay()] + ')'
            })
            this.loaded = true
            if(showLoading) wx.hideLoading()
          }
        }
      })
    },
    changeSchedule(i) {
      this.tomorrow = this.service.formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000))
      this.changingIndex = i
      this.changing = true
    },
    replaceSchedule(i) {
      this.replaceIndex = i
      let scheduleDate = this.schedule[this.replaceIndex].schedule_Date
      // console.log(scheduleDate)
      // console.log(this.schedule[this.replaceIndex].schedule_Date.substring(0,10))
      wx.request({
        url: this.rootUrl + 'lawSubstitute/getSubstituteByApplyId',
        method: 'get',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          scheduleDate: scheduleDate.substring(0,10),
          sessionID: wx.getStorageSync('sessionID')
        },
        success: res => {
          // console.log(res.data)
          if (res.statusCode == '500') {
          } else {
            if(res.data>0){
              this.replace = false
              wx.showModal({
                title:'',
                content: '您已申请代班，请耐心等待审批！',
                showCancel: false,
                confirmText: '知道了'
              })
            }else{
              this.replace = true
            }
          }
        }
      })
      this.getLawFirmByLIID()
    },
    pickerConfirm(e) {
      const time = e.mp.detail.value
      this.targetDate = this.service.correctTime(time)
        + ' (星期' + week[this.service.correctTime(time,'DateObj').getDay()] + ')'
    },
    cancel() {
      this.changing = false
      this.replace = false
      this.targetDate = ''
    },
    confirm() {
      wx.showModal({
        title:'',
        content:`确认将该次值班调到${this.targetDate.substring(0,10)}吗?`,
        success: res => {
          if(res.confirm){
            this.changeScheduleRequest()
            // this.changing = false
            // this.targetDate = ''
          }
        }
      })
    },
    changeScheduleRequest(){
      this.submitting = true
      wx.showLoading({ title: '正在修改' })
      wx.request({
        url: this.rootUrl + 'sch/updatesch',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          lsid: this.schedule[this.changingIndex].lsid,
          schedule_date: this.targetDate.substring(0,10),
          sessionID: wx.getStorageSync('sessionID')
        },
        success: res => {
          if (res.statusCode == '500') {
            this.service.getUnionId(this.rootAvatar, this.rootUrl).then(() => this.changeScheduleRequest())
          } else if (res.data === 1) {
            wx.hideLoading()
            wx.showToast({ title: '修改成功' })
            this.getSchedule(false)
            this.changing = false
            this.submitting = false
            this.targetDate = ''
          } else if (res.data === -1) {
            wx.hideLoading()
            wx.showModal({ title: '修改失败', content:`${this.targetDate.substring(0,10)}已有您的排班`,showCancel:false})
            this.submitting = false
          }
        }
      })
    },
    getLawFirmByLIID(){
      wx.request({
        url: this.rootUrl + 'law/getLawFirmByLIID',
        method: 'get',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: { sessionID: wx.getStorageSync('sessionID') },
        success: res => {
          console.log(res.data)
          if (res.statusCode == '500') {
          } else {
            this.LawFirm.columnOne = res.data.map(v => v.name)
            this.LawFirm.arrStruct = res.data.map(v => {
              return { label: v.name, value: v.liid }
            })
            // res.data.forEach( v => {
            //   this.LawFirmArray.push(v.name)
            // })
          }
        }
      })
    },
    pickerConfirmLawFirm(e, s) {
      this.LawFirm.index = e.mp.detail.value
      this.LawFirm.label = this.LawFirm.columnOne[this.LawFirm.index]
    },
    commit(e) {
      if(this.commiting) return
      let inputs = this.service.filter(e.mp.detail.value)
      const LawFirm = this.LawFirm.label.replace('点击选择代班人','')
      if(!this.service.checkEmptyInput([LawFirm,this.cause],['代班人','事由'])){
        return
      }
      if(!this.service.checkBadWords([this.cause],['事由'])){
        return
      }
      wx.showModal({
        title:'',
        content:'确定要代班吗?',
        success: res => {
          if(res.confirm){
            this.execCommit(e)
          }
        }
      })
    },
    execCommit(e){
      console.log(this.schedule[this.replaceIndex])
      console.log(this.LawFirm.arrStruct[this.LawFirm.index].value)
      this.commiting = true
      wx.showLoading({ title: '正在提交' })
      wx.request({
        url: this.rootUrl + 'lawSubstitute/addLawSubstitute',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          sub_id: this.LawFirm.arrStruct[this.LawFirm.index].value,
          cause: this.cause,
          LSID: this.schedule[this.replaceIndex].lsid,
          sub_date: this.schedule[this.replaceIndex].schedule_Date,
          sessionID: wx.getStorageSync('sessionID')
        },
        success: res => {
          console.log(res)
          if (res.statusCode == '500') {
            this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => this.submit_exec(content))
          } else {
            // wx.hideLoading()
            if (res.data === 1) {
              wx.showModal({
                title: '提交成功',
                content: '',
                showCancel: false
              })
              this.text = ''
              wx.hideLoading()
              // this.toHomelist()
            } else {
              wx.showToast({ title: '提交失败', icon: 'none' })
            }
            this.LawFirm = {columnOne: [],index: 0,arrStruct: [],label: '点击选择代班人' }
            this.cause = ''
            this.replaceIndex = 0
            this.commiting = false
            this.changing = false
            this.replace = false
          }
        }
      })
    }
  },
  onLoad() {
    this.getSchedule()
  },
  onShow() {
    wx.showModal({
      title:'',
      content: '本页面列出您未来10次的值班\n日期，您可以进行调班请至少提前\n一天进行调班，不支持当天调班',
      showCancel: false,
      confirmText: '知道了'
    })
  },
  onUnload() {
    this.changing = false
    this.targetDate = ''
    this.submitting = false
    this.cause = ''
    this.LawFirm = {columnOne: [],index: 0,arrStruct: [],label: '点击选择代班人' }
    this.replaceIndex = 0
    this.replace = false
  }
}
</script>
<style lang='stylus' scoped>
.container
  position absolute
  width 100%
  min-height 100%
  Background()
.list-item
  margin 25rpx
  padding 25rpx
  background white
  border-radius 8rpx
  display flex
  align-items center
  .schedule
    .time
      Font(30rpx)
    .locate
      margin 25rpx 20rpx 0 0
      Flex(flex,,center)
      Font(28rpx)
      color #666
      img
        Height_Width(32rpx)
        margin-right 10rpx
  button
    margin-right 0
    Font(30rpx,60rpx)
    height 60rpx
    padding 0 40rpx
.change-box-mask
  position fixed
  left 0
  top 0
  background rgba(0,0,0,.5)
  Height_Width(100%)
  Flex(flex,center,center)
  .change-box
    margin-top -110rpx
    width 80%
    Font(30rpx,80rpx)
    padding 40rpx
    background white
    border-radius 10rpx
    .info
      Flex(flex,space-between,center)
      .title
        font-weight bold
    .btn
      padding 0 20%
      margin-top 20rpx
      Flex(flex,space-between,center)
      button
        Font(30rpx,70rpx)
        margin 0
        padding 0 40rpx
        height 70rpx
.reason
  margin-bottom 30rpx
  width 100%
  padding 15rpx
  box-sizing border-box
  height 150rpx
  background-color #eee
  border-radius 8rpx
  color #333
  line-height 50rpx
</style>
