<template>
  <div class="auto select-overspread" >
    <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="[$v.f_user_type.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_user_type" v-show="false"
                   v-validate:f_user_type='{required: true }'>
            <label title="参数:用户类型" class="font_normal_body" for="f_user_type">客户类型</label>
            <v-select :disabled='isEdit'
                      :options='usertype'
                      :value-single="true"
                      :value.sync="model.f_user_type"
                      @change="usertypeChange"
                      close-on-select
                      placeholder='请选择'
                      v-model="model.f_user_type">
            </v-select>
          </div>
          <div :class="[$v.f_gasproperties.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_gasproperties" v-show="false"
                   v-validate:f_gasproperties='{required: true }'>
            <label class="font_normal_body" for="f_gasproperties">用气性质</label>
            <v-select :disabled='isEdit'
                      :options='gastype'
                      :value-single="true"
                      :value.sync="model.f_gasproperties"
                      close-on-select
                      placeholder='请选择'
                      v-model="model.f_gasproperties">
            </v-select>
          </div>
          <div :class="[$v.f_price_type.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_price_type" v-show="false"
                   v-validate:f_price_type='{required: true }'>
            <label title="参数:气价类型" class="font_normal_body" for="f_price_type">气价类型</label>
            <v-select :disabled='isEdit'
                      :options='pricetype'
                      :value-single="true"
                      :value.sync="model.f_price_type"
                      close-on-select
                      id="f_price_type"
                      placeholder='请选择'
                      v-model="model.f_price_type">
            </v-select>
          </div>
          <div :class="[$v.f_price_name.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <label class="font_normal_body" for="f_price_name">气价名称</label>
            <input :disabled='isEdit' class="input_search" placeholder="气价名称" style="width:60%" @blur="CheckDuplicate"
                   type="text" v-model="model.f_price_name" v-validate:f_price_name='{required: true }'>
          </div>
        </div>
        <div class="row" v-if="model.f_price_type === '阶梯气价'">
          <div :class="[$v.f_stairmonths.required || $v.f_stairmonths.dctest ? 'has-error' : 'has-success']" class="col-sm-6 form-group">
            <label class="font_normal_body" for="f_stairmonths">阶段月数</label>
            <input :disabled='isEdit' class="input_search" style="width:60%" type="number"
                   v-model="model.f_stairmonths" v-validate:f_stairmonths='{required: true}'>
<!--            <span class="help-block" v-if="$v.f_stairmonths.dctest">阶段月数不能大于36</span>-->
          </div>
          <div  :class="[$v.f_stair_start_date.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group" v-if="stairStartShow">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_stair_start_date" v-show="false"
                   v-validate:f_stair_start_date='{required: true }'>
            <label class="font_normal_body"  for="f_stair_start_date">开始日期</label>
            <datepicker :disabled='isEdit'
                        :format="'yyyy-MM-dd'"
                        :value.sync="model.f_stair_start_date"
                        class="datepicker"
                        id="f_stair_start_date"
                        placeholder="阶梯开始日期"
                        style="width: 60%"
                        v-model="model.f_stair_start_date">
            </datepicker>
            <span class="help-block" id="helpBlock" style="font-size: 1.4rem">本年或<br/>本月1号</span>
          </div>
        </div>
        <div class="row">
          <div  :class="[$v.f_perform_date.required ? 'has-error' : 'has-success']" class="col-sm-6 form-group" class="col-sm-6">
            <input class="input_search" style="width:60%" type="text" v-model="model.f_perform_date" v-show="false"
                   v-validate:f_perform_date='{required: true }'>
            <label class="font_normal_body" for="f_perform_date">生效日期</label>
            <datepicker :disabled='isEdit'
                        :value.sync="model.f_perform_date"
                        id="f_perform_date"
                        placeholder="生效日期"
                        :format="'yyyy-MM-dd HH:mm:ss'"
                        style="width: 60%" v-model="model.f_perform_date">
            </datepicker>
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">是否低保</label>
            <v-select :options='isLowIncomes'
                      :value-single="true"
                      :value.sync="model.f_islow_income"
                      close-on-select
                      placeholder='请选择'
                      style="width: 60%" v-model="model.f_islow_income">
            </v-select>
          </div>
          <div :class="[$v.f_population_base.pattern ? 'has-error' : 'has-success']" class="col-sm-6 form-group" v-if="model.f_price_type === '阶梯气价'">
            <label class="font_normal_body" for="f_population_base">人口基数</label>
            <input :disabled='isEdit' :value.sync="model.f_population_base" class="input_search" placeholder="人口基数"
                   style="width:60%"
                   type="text" v-model="model.f_population_base" v-validate:f_population_base="{pattern: '/^[1-9]\\d*$/'}">
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">使用公司</label>
            <res-select :initresid='curorgid'
                        @res-select="getorg"
                        is-mul="false"
                        restype='organization'>
            </res-select>
          </div>
          <unit-price :is-disable.sync='isEdit' :unitmodel.sync='model.detailprice' v-if="unitshow"></unit-price>
        </div>

        <div v-if="config.heatingSeason && model.f_price_type == '阶梯气价'">
          <div class="row">
            <div class="col-sm-6 form-group">
              <label class="font_normal_body">是否采暖</label>
              <v-select :options='isLowIncomes'
                        :value-single="true"
                        :value.sync="model.f_isheat"
                        close-on-select
                        placeholder='请选择'
                        style="width: 60%" v-model="model.f_isheat">
              </v-select>
            </div>
            <div class="col-sm-6 form-group">
              <input class="input_search" style="width:60%" type="text" v-model="model.f_deduction_way" v-show="false"
                     v-validate:f_deduction_way='{required: true }'>
              <label class="font_normal_body">扣费方式</label>
              <v-select :options='deductionWays'
                        :value-single="true"
                        :value.sync="model.f_deduction_way"
                        @change="deductionChange"
                        close-on-select
                        placeholder='请选择'
                        style="width: 60%" v-model="model.f_deduction_way">
              </v-select>
            </div>

          </div>
          <div class="row" v-if="model.f_isheat == '1'">
            <div :class="[$v.f_heat_start_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_heat_start_date" v-show="false"
                     v-validate:f_heat_start_date='{required: true }'>
              <label class="font_normal_body">采暖起始</label>
              <datepicker :disabled='isEdit'
                          :format="'MM-dd'"
                          :value.sync="model.f_heat_start_date"
                          class="datepicker"
                          placeholder="阶梯开始日期"
                          style="width: 60%" v-model="model.f_heat_start_date">
              </datepicker>
            </div>
            <div :class="[$v.f_heat_cycle.dctest ? 'has-error' : 'has-success']" class="col-sm-6 form-group" >
              <label class="font_normal_body">采暖周期</label>
              <input class="input_search" style="width:60%" type="number"
                     v-model="model.f_heat_cycle" v-validate:f_heat_cycle='{dctest: [ 12, "<=" ] }'>
            </div>
          </div>
        </div>
        <div class="row" >
          <div class="col-sm-6 form-group">
            <label  class="font_normal_body ">优&ensp;先&ensp;级</label>
            <input :disabled='isEdit' class="input_search" placeholder="优先级" style="width:60%"
                   type="text" v-model="model.f_priority" v-validate:f_priority='{required: true }'>
          </div>
          <div  class="col-sm-6 form-group" >
            <label class="font_normal_body">预收气价</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_add_price" />
          </div>
        </div>
        <div class="row" v-if="model.f_price_type === '固定气价'">
          <div  class="col-sm-6 form-group" >
            <label class="font_normal_body">政府定价</label>
            <input class="input_search" style="width:60%"
                :value.sync="(model.detailprice[0].f_price-model.f_add_price).toFixed(2)"  readonly="true" />
          </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_comments"></textarea>
          </div>
        </div>

      </form>

      <!--<div style="width: 40%;overflow-y: scroll">-->
      <div class='auto' style="margin-top: 10px;">

        <mix-price :is-disable.sync='isEdit' :mixmodel.sync='model.detailprice' v-if="mixshow"></mix-price>
        <stair-price :is-disable.sync='isEdit' :isheat.sync="model.f_isheat" :f_add_price="model.f_add_price" :stairmodel.sync='model.detailprice' style="height: 40%;"
                     v-if="stairshow"></stair-price>
      </div>

      <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="deletePrice()" class="button_delete" v-if="!isEdit && data.usercount === 0">删除</button>
        <button @click="limitClick" class="button_search" type="button" v-if="config.isLimit">限购配置</button>
        <button @click="close()" class="button_clear">取消</button>
      </div>
      <div v-if="data" style="text-align:right;height:auto;margin-top:6px;">
        <a @click="showChangeView">查看变更记录</a>
      </div>
      <!--</div>-->
    </validator>
    <limit-gas :f_price_id="model.id" :show.sync="limitShow" @limit="getLimitGas"></limit-gas>
   <upload  v-if="data" :blodid="blodid" cols="col-sm-12" isremark="true" fusetype="气价修改"></upload>
  </div>
</template>
<script>
  /**
 *阶梯气价管理组件
 */

import {HttpResetClass} from 'vue-client'
let initGen = async function (self, val) {
  let http = new HttpResetClass()
  self.blodid = self.data.id
  // 启动流程的情况下 获取改气价有无正在审核的气价，若有则禁止编辑，若无则可编辑
  let hasUnAudit = false
  console.log('当前信息', val)
  if (self.config.audit) {
    let res = await http.load('POST', 'rs/sql/saleSingleTable', {
      data: {
        tablename: 't_stairprice',
        condition: `f_price_id = '${val.f_price_id}' and f_filialeid = '${val.f_filialeids}' and f_state = '待审核'`
      }
    }, {resolveMsg: null, rejectMsg: '获取有无待审核气价时出错！！！'})
    console.log('获取有无待审核气价', res)
    // 这里默认待审核气价只有一条
    if (res.data.length === 1) {
      // 判断当前气价是否是待审核气价
      hasUnAudit = res.data[0].id !== val.id
    } else if (res.data.length > 1) {
      self.$showAlert('意外获取到多条待审核记录！请联系管理人员！', 'danger', 0)
    }
  }
  self.model = Object.assign({}, self.model, val)

  self.model.f_filialeid = self.model.f_filialeid ? self.model.f_filialeid : self.f_filialeid
  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.push(self.model.f_filialeid)
  self.model.f_islow_income = self.model.f_islow_income + ''
  self.model.f_isheat = self.model.f_isheat + ''

  self.stairStartShow = !self.model.f_deduction_way.includes('day')
  self.isEdit = self.model.f_price_state === '已作废' || hasUnAudit
  console.log('观察data里面的model', self.model, val)
  if (self.model.id) {
    let price = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
      data: {
        items: 'f_price_name, f_gas, f_price, isnull(f_add_gas, 0) f_add_gas, isnull(f_add_gas_heat, 0) f_add_gas_heat',
        tablename: 't_detailprice',
        condition: `f_stairprice_id = '${self.model.id}'`,
        orderitem: 'f_price_name asc'
      }
    }, {resolveMsg: null, rejectMsg: '获取气价明细出错！！！'})

    if (self.model.f_price_type[0] === '混合气价') {
      price.data[0].f_mixprice = [price.data[0].f_mixprice]
      price.data[1].f_mixprice = [price.data[1].f_mixprice]
    }
    self.model.detailprice = price.data
  }
}

  export default {
    data () {
      return {
        unitshow: false,
        mixshow: false,
        blodid: '',
        stairshow: false,
        model: {
          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_comments: '',
          f_priority: 100,
          f_add_price: 0
        },
        // 编辑控制
        isEdit: false,

        // 扣费方式的改变 如果涉及日运算，则阶梯开始时间和生效时间不做显示
        stairStartShow: true,

        // 公司树状图信息
        curorgid: [],

        f_filialeid: '',  // 所属公司
        f_filialename: '',  // 所属公司名称

        // 限购配置
        limitShow: false,
        limit_gas: null,

        // 下拉框数据
        usertype: this.$appdata.getParam('用户类型'),
        pricetype: this.$appdata.getParam('气价类型'),
        hearways: [{label: '按月', value: '按月'}, {label: '按季', value: '按季'}],
        isLowIncomes: [{label: '是', value: '1'}, {label: '否', value: '0'}],
        deductionWays: [{label: '周期扣费', value: 'cycle'}, {label: '周期平均扣费', value: 'cycleMM'}, {label: '日运算扣费', value: 'day'}, {label: '采暖季独立扣费', value: 'singleHS'}, {label: '采暖季日扣费', value: 'dayHS'}],
        gastype: []
      }
    },
    props: ['data', 'config', 'f_filialeid'],
    watch: {
      'data' (val) {
        if (val) {
          initGen(this, val)
        } else {
          this.initModel()
        }
      },
      'model.f_price_type' (val) {
        this.unitshow = false
        this.mixshow = false
        this.stairshow = false
        if (val === '固定气价') {
          this.model.detailprice = []
          this.unitshow = true
        } else if (val === '混合气价') {
          this.model.detailprice = []
          this.mixshow = true
        } else if (val === '阶梯气价') {
          this.model.detailprice = [{f_gas: '', f_price: '', f_add_gas: 0, f_add_gas_heat: 0}]
          if (this.model.f_deduction_way == undefined || this.model.f_deduction_way == '') {
            this.model.f_deduction_way = 'cycle'
          }
          this.stairshow = true
        }
      }
    },
    ready () {
      console.log('看看都传了什么', this.data, this.config)
      initGen(this, this.data)
    },
    methods: {
      async CheckDuplicate () {
        if (!this.data) {
          let http = new HttpResetClass()
          let res = await http.load('post', 'rs/sql/getGasPriceInfo', {data: {condition: ` f_filialeid  in ('${this.$login.f.orgid}') and  1=1 `, orderitem: 'f_price_id'}}, {resolveMsg: null, rejectMsg: null})
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].f_price_name == this.model.f_price_name) {
              this.$showAlert('气价名称重复,请重新输入', 'warning', 3000)
              this.model.f_price_name = ''
              return
            }
          }
        }
      },
      async confirm () {
        // 验证公司组织是否已选择
        try {
          if (!this.f_filialeid) {
            this.$showAlert('请选择气价使用公司', 'warning', 2000)
            return
          }
          if (this.data) {
            if (this.data.f_perform_date == this.model.f_perform_date) {
              this.$showAlert('请更改生效日期', 'warning', 2000)
              return
            }
            let datenow = new Date()
            let a = datenow.setDate(datenow.getDate() - 1)
            let month = datenow.getMonth() + 1
            let date = datenow.getDate()
            let hour = datenow.getHours()
            let min = datenow.getMinutes()
            let sec = datenow.getSeconds()
            a = datenow.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
            a = a + ' 23:59:59'
            if (this.model.f_perform_date <= this.data.f_perform_date) {
              this.$showAlert('生效日期不能小于上次生效时间', 'warning', 2000)
              return
            }
          }

          // 验证此生效时间之后是否有待使用气价， 如果有提示是否作废待使用气价，
          let validateResult = await this.$resetpost('rs/logic/sale_validatePrice', {data: this.model}, {
            resolveMsg: null,
            rejectMsg: '验证气价出错！！'
          })
          console.log('验证气价:', validateResult)
          if (validateResult.data.toBeUsePrice.length > 0) {
            // 有待使用气价， 将待使用气价信息展示
            let awaitOper = await this.$showMessage(`此气价存在待使用记录, 将于${validateResult.data.toBeUsePrice[0].f_perform_date} 开始使用！是否将其作废?`, ['confirm', 'cancel'])
            console.log('用户点击了:', {awaitOper})
            if (awaitOper == 'confirm') {
              // 传至后台用于新版本号的处理
              this.model.toBeUsePriceId = validateResult.data.toBeUsePrice[0].id
              this.model.toBeUsePriceVersion = validateResult.data.toBeUsePrice[0].f_version
              this.savePrice()
            }
          } else {
            this.savePrice()
          }
        } catch (e) {
          this.$dispatch('error', '气价管理', this.data, res)
        }
      },

      async savePrice () {
        // 去除重复或者空的明细
        if (this.model.f_price_type[0] === '阶梯气价') {
          this.removeDuplication(this.model)
        }
        // 审核配置
        this.model.audit = this.config.audit

        console.log('进入保存气价方法')
        this.model.f_filialeid = this.f_filialeid ? this.f_filialeid : this.$login.f.orgid

        if (this.limit_gas) {
          this.model.limit_gas = this.limit_gas
          //this.model.limit_gas.f_start_date = this.model.f_perform_date
        }
        // 现调用气价修改的逻辑   返回：version 和之前的对比 增加的话， 进行提示操作 反之 结束
        await this.$LogicService.gasPrice(this.model, this.data)
        // 操作了气价 清空分公司initdata缓存
        let http = new HttpResetClass()
        await http.load('POST', 'rs/logic/delSaleInitData', {data: {}}, {resolveMsg: null, rejectMsg: null})

        this.$dispatch('success', '气价管理', this.data)
        this.initModel()
      },

      async deletePrice () {
        let res = await this.$showMessage(`您确定要删除此气价吗？`, ['confirm', 'cancel'])
        if (res === 'confirm') {
          await this.$resetpost('rs/logic/delprice', {data: {id: this.model.id}}, {
            resolveMsg: '删除气价成功',
            rejectMsg: '删除气价失败'
          })
          let http = new HttpResetClass()
          await http.load('POST', 'rs/logic/delSaleInitData', {data: {}}, {resolveMsg: null, rejectMsg: null})
        }
        this.$dispatch('success')
      },

      getLimitGas (val) {
        console.log('获取到限购值。', val)
        this.limit_gas = val
      },

      getorg (id, name) {
        this.f_filialeid = id[0]
        this.f_filialename = name[0]
      },
      initModel () {
        this.model = {
          f_user_type: '',
          f_gasproperties: '',
          f_price_type: '',
          f_stairmonths: 1,
          f_perform_date: '',
          detailprice: [],
          f_stair_start_date: '',
          f_population_increment: 0,
          f_population_base: 4,
          f_comments: '',
          f_deduction_way: this.config.deductionWay
        }
      },
      close () {
        this.$dispatch('close')
      },
      removeDuplication (val) {
        if (val.detailprice.length > 0) {
          let hash = []
          let arr = []
          for (var i = 0; i < val.detailprice.length; i++) {
            // hash[val.detailprice[i].f_gas] != null
            if (!val.detailprice[i].f_gas) {
              continue
            }
            if (!hash[val.detailprice[i].f_gas]) {
              arr.push(val.detailprice[i])
              hash[val.detailprice[i].f_gas] = true
            }
          }
          val.detailprice = arr
        }
      },
      usertypeChange (val) {
        if (val) {
          this.gastype = this.$appdata.getParam(this.model.f_user_type)
        }
      },
      deductionChange (val) {
        // 扣费方式的改变 如果涉及日运算，则阶梯开始时间和生效时间不做显示
        this.stairStartShow = !val.includes('day')
      },
      limitClick () {
        this.limitShow = true
      },
      showChangeView () {
        this.$parent.changeView = true
      }
    }
  }
</script>
<style lang="less">
  #gas-price-form {
    .form-group {
      margin-left: 0px;
      margin-right: 0px;
    }
  }

</style>
