<template>
  <div class="auto select-overspread" v-if="refreshDisplay">
    <validator name='v'>
      <form class="form-horizontal" novalidate>
        <ul class="nav nav-tabs" style="margin-bottom: 10px">
          <li class="active"><a href="#">抄表册信息</a></li>
        </ul>
        <div class="row">
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">所属公司&emsp;</label>
            <res-select :initresid='curorgid'
                        @res-select="getorg"
                        is-mul="false"
                        restype='organization'>
            </res-select>
          </div>
          <div :class="[$v.f_book_slice_area.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <label class="font_normal_body" for="f_book_name">表册片区</label>
            <input v-show="false" v-model="model.f_book_slice_area" v-validate:f_book_slice_area='{required: true }'>
            <v-select :value.sync="model.f_book_slice_area" v-model='model.f_book_slice_area'
                      style="width:60%"
                      :options='bookSliceArea'
                      :value-single="true"
                      placeholder='表册片区'
                      close-on-select
                      v-el:cc></v-select>
          </div>
          <div :class="[$v.f_book_name.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <label class="font_normal_body" for="f_book_name">抄表册名称</label>
            <input :disabled='isEdit' class="input_search" placeholder="抄表册名称" style="width:60%"
                   type="text" v-model="model.f_book_name" v-validate:f_book_name='{required: true }'>
          </div>

          <div :class="[$v.f_inputtor.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_inputtor" v-show="false"
                   v-validate:f_inputtor='{required: true }'>
            <label class="font_normal_body">抄表员&ensp;&ensp;</label>
            <v-select :value.sync="model.f_inputtor" v-model='model.f_inputtor'
                      style="width:60%"
                      :value-single="true"
                      :options='inputtores' placeholder='抄表员'
                      close-on-select
                      v-el:cc></v-select>
          </div>
          <div :class="[$v.f_period.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_period" v-show="false"
                   v-validate:f_period='{required: true }'>
            <label class="font_normal_body">抄表周期&ensp;&ensp;</label>
            <v-select :value.sync="model.f_period" v-model='model.f_period'
                      style="width:60%"
                      :value-single="true"
                      :options='period' placeholder='抄表周期'
                      close-on-select
                      v-el:cc></v-select>
          </div>


          <div :class="[$v.f_hand_begin_date.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_hand_begin_date" v-show="false"
                   v-validate:f_hand_begin_date='{required: true }'>
            <label class="font_normal_body" for="f_hand_begin_date">执行时间</label>
            <datepicker :disabled='isEdit'
                        :value.sync="model.f_hand_begin_date"
                        id="f_hand_begin_date"
                        placeholder="执行时间"
                        :format="'yyyy-MM-dd 00:00:00'"
                        style="width: 60%" v-model="model.f_hand_begin_date">
            </datepicker>
          </div>

          <div :class="[$v.f_hand_end_date.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_hand_end_date" v-show="false"
                   v-validate:f_hand_end_date='{required: true }'>
            <label class="font_normal_body" for="f_hand_end_date">结束时间&emsp;</label>
            <datepicker :disabled='isEdit'
                        :value.sync="model.f_hand_end_date"
                        id="f_hand_end_date"
                        placeholder="抄表结束时间"
                        :format="'yyyy-MM-dd 00:00:00'"
                        style="width: 60%" v-model="model.f_hand_end_date">
            </datepicker>
          </div>
        </div>


        <div class="row">
          <div class="col-sm-12 form-group" style="height: auto !important;">
            <label class="font_normal_body ">备&emsp;&emsp;注</label>
            <textarea class="input_textarea" rows="3" style="width:80%;margin-top:5px;"
                      v-model="model.f_book_remark"></textarea>
          </div>
        </div>

      </form>

      <!--<div style="width: 40%;overflow-y: scroll">-->


      <div style="text-align:right;height:auto;margin-top:6px;">
        <button :disabled='!$v.valid' @click="confirm()" class="button_search" v-if="!isEdit">确认</button>
        <button @click="deletemeterbook()" class="button_delete" v-if="!isEdit && data.usercount === 0">删除</button>
        <button @click="close()" class="button_clear">取消</button>
      </div>

      <!--</div>-->
    </validator>

  </div>
</template>
<script>
  import {HttpResetClass} from 'vue-client'

  /**
   *阶梯气价管理组件
   */

  let initGen = async function (self, val) {
    console.log('===================ready了！', self.$login.f.orgid)
    await self.initSlice(self.$login.f.orgid)
    let http = new HttpResetClass()
    self.blodid = self.data.id
    let hasUnAudit = false
    console.log('当前信息', val)
    self.model = Object.assign({}, self.model, val)

    self.model.f_book_name = self.model.f_book_name ? self.model.f_book_name : self.f_book_name
    self.model.f_inputtor = self.model.f_inputtor ? self.model.f_inputtor : self.f_inputtor
    self.model.f_period = self.model.f_period ? self.model.f_period : self.f_period
    if (self.model.f_book_slice_area) {
      if (self.model.f_book_slice_area.name) {
        self.model.f_book_slice_area = self.model.f_book_slice_area.name
      }
    }
    self.model.f_hand_begin_date = self.model.f_hand_begin_date ? self.model.f_hand_begin_date : self.f_hand_begin_date
    self.model.f_book_remark = self.model.f_book_remark ? self.model.f_book_remark : self.f_book_remark

    self.model.f_filiale_id = self.model.f_filiale_id ? self.model.f_filiale_id : self.f_filiale_id
    self.model.f_filiale_name = self.model.f_filiale_name ? self.model.f_filiale_name : self.f_filiale_name
    self.model.f_orgid = self.model.f_orgid ? self.model.f_orgid : self.$login.f.orgid
    self.model.f_orgname = self.model.f_orgname ? self.model.f_orgname : self.$login.f.orgs
    self.model.f_depid = self.model.f_depid ? self.model.f_depid : self.$login.f.depids
    self.model.f_depname = self.model.f_depname ? self.model.f_depname : self.$login.f.deps
    self.curorgid = [self.model.f_orgid]
    self.model.f_islow_income = self.model.f_islow_income + ''
    self.model.f_isheat = self.model.f_isheat + ''
  }

  export default {
    data () {
      return {
        unitshow: false,
        mixshow: false,
        blodid: '',
        //  handDate:null,
        stairshow: false,
        model: {
          f_book_slice_area: '',
          f_price_type: [],
          f_stairmonths: 1,
          f_perform_date: '',
          detailprice: [],
          f_population_base: 4,
          f_population_increment: 0,
          f_stair_start_date: '',
          f_heat_way: '按月',
          f_deduction_way: this.config.deductionWay,
          f_islow_income: '0',
          f_isheat: '0',

          f_book_name: '',
          f_inputtor: '',
          f_period: '',
          // 明天
          f_hand_begin_date: this.$login.addDate(this.$login.toStandardDateString() + ' 00:00:00', 1),
          f_hand_end_date: '',
          f_book_remark: '',
          f_filiale_id: '',
          f_filiale_name: '',
          f_comments: '',
          f_priority: 100
        },
        // 编辑控制
        isEdit: false,

        // 公司树状图信息
        curorgid: [this.$login.f.orgid],
        f_filiale_id: '',  // 所属公司
        f_filiale_name: '',  // 所属公司名称

        // 下拉框数据
        usertype: this.$appdata.getParam('用户类型'),
        pricetype: this.$appdata.getParam('气价类型'),
        bookSliceArea: [],
        period: [{label: '1', value: '1'}, {label: '2', value: '2'}, {label: '3', value: '3'},
          {label: '4', value: '4'}, {label: '5', value: '5'}, {label: '6', value: '6'},
          {label: '7', value: '7'}, {label: '8', value: '8'}, {label: '9', value: '9'},
          {label: '10', value: '10'}, {label: '11', value: '11'}, {label: '12', value: '12'}

        ],

        inputtores: [{label: '全部', value: ''}],
        refreshDisplay: true,
        currentTime: this.$login.toStandardDateString() + ' 00:00:00'
      }
    },
    props: ['data', 'config'],
    watch: {
      'data' (val) {
        if (val) {
          initGen(this, val)
        } else {
          this.initModel()
        }
        this.refreshDisplay = false
        this.$nextTick(() => {
          this.refreshDisplay = true
        })
      }
    },
    computed: {
      dateEdit () {
        return this.model.f_hand_end_date && this.model.f_hand_begin_date && this.model.f_hand_end_date <= this.model.f_hand_begin_date
      }
    },
    ready () {
      initGen(this, this.data)
    },
    methods: {
      async initSlice (val) {
        if (val) {
          let getAllArea = await this.$resetpost('/rs/search', {
            source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
            userid: this.$login.f.id
          }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})
          let arr = getAllArea.data.filter((res) => {
            return res.parentid == val
          })
          this.bookSliceArea = []
          arr.forEach((res) => {
            this.bookSliceArea.push({label: res.name, value: res.name})
          })
        }
      },
      // 机表结束时间范围检测, 返回true表上通过
      endTimeDetection () {
        let result = false
        if (!this.model.f_period) {
          this.$showMessage('请先选择抄表周期')
          this.model.f_hand_end_date = ''
          return result
        }
        if (!this.model.f_hand_begin_date) {
          this.$showMessage('请先选择执行时间')
          this.model.f_hand_end_date = ''
          return result
        }
        if (this.model.f_hand_begin_date <= this.currentTime) {
          this.$showMessage('执行时间不能小于当前时间')
          return result
        }
        // if (this.model.f_hand_end_date <= this.model.f_hand_begin_date) {
        //   this.$showMessage('抄表结束时间不能小于等于执行时间')
        //   this.model.f_hand_end_date = ''
        //   return result
        // }
        // 根据执行时间与抄表周期,计算最大能选中的结束时间
        let arr = this.model.f_hand_begin_date.split(' ')
        let maxSelectDate = this.addMonth(arr[0], this.model.f_period - 0) + ` ${arr[1]}`
        if (this.model.f_hand_end_date >= maxSelectDate) {
          this.$showMessage(`根据选择的抄表周期, 当前抄表结束时间选择范围: ${this.model.f_hand_begin_date} ~ ${maxSelectDate}`)
          this.model.f_hand_end_date = ''
          return result
        }
        result = true
        return result
      },
      addMonth (d, m) {
        var ds = d.split('-'), _d = ds[2] - 0
        var nextM = new Date(ds[0], ds[1] - 1 + m + 1, 0)
        var max = nextM.getDate()
        d = new Date(ds[0], ds[1] - 1 + m, _d > max ? max : _d)
        let month = d.getMonth() + 1
        let date = d.getDate()
        return d.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
      },
      async confirm () {
        try {
          // 提交之前进行验证
          let result = this.endTimeDetection()
          if (!result) return
          this.model.f_filiale_id = this.f_filiale_id ? this.f_filiale_id : this.$login.f.orgid
          this.model.f_filiale_name = this.f_filiale_name ? this.f_filiale_name : this.$login.f.orgs
          await this.$LogicService.gasMeterBook(this.model, this.data)
          // this.$dispatch('success', '表册管理', this.data)
          this.initModel()
        } catch (e) {
          this.$dispatch('error', '表册管理', this.data, res)
        }
      },

      async deletemeterbook () {
        let res = await this.$showMessage(`您确定要删除此表册信息吗？`, ['confirm', 'cancel'])
        if (res === 'confirm') {
          await this.$resetpost('rs/logic/deleteMeterBook', {data: {id: this.model.id}}, {
            resolveMsg: '删除表册成功',
            rejectMsg: '删除表册失败'
          })
        }
        this.$dispatch('success')
      },
      getorg (id, name) {
        if (id.length && name.length) {
          this.f_filiale_id = id[0]
          this.f_filiale_name = name[0].split(' -')[0]
          this.updateParams()
        }
        console.log('11111', id, name, this.model, this.f_filiale_name)
      },
      async updateParams () {
        console.log('重新加载抄表员！！！！！')
        // await this.$LoadParams.loadParam(this.f_filiale_id)
        // await this.$GetSaleParam.initinputtor()
        this.inputtores = []
        this.inputtores.push({label: '全部', value: ''})
        this.initSlice(this.f_filiale_id)
        this.inputtores = this.inputtores.concat(this.$GetSaleParam.getresinputtor(this.f_filiale_id))
      },
      initModel () {
        this.model = {
          f_user_type: '',
          f_gasproperties: '',
          f_price_type: '',
          f_stairmonths: 1,
          f_perform_date: '',
          detailprice: [],
          f_stair_start_date: '',
          f_hand_end_date: '',
          f_population_increment: 0,
          f_population_base: 4,
          f_comments: '',
          f_deduction_way: this.config.deductionWay
        }
      },
      close () {
        this.$dispatch('close')
      }
    }
  }
</script>
<style lang="less">
  #gas-price-form {
    .form-group {
      margin-left: 0px;
      margin-right: 0px;
    }
  }

</style>
