<template>
  <div class="span">
    <validator name='v'>
      <form novalidate class="form-horizontal select-overspread">
        <ul class="nav nav-tabs">
          <li class="active"><a href="#">气价信息</a></li>
        </ul>
        <div class="form-group">
          <div :class="[$v.f_user_type.required ? 'has-error' : 'has-success']">
            <input type="text" v-show="false" v-model="model.f_user_type" v-validate:f_user_type='{required: true }'>
            <label for="f_user_type" class=" col-sm-2 control-label">用户类型</label>
            <div class="col-sm-3" id="f_user_type">
              <v-select id="f_user_type"
                        v-model="model.f_user_type"
                        placeholder='请选择'
                        :value.sync="model.f_user_type"
                        :options='usertype'
                        @change="usertypeChange"
                        :value-single="true"
                        :disabled='isEdit'
                        close-on-select>
              </v-select>
            </div>
          </div>
          <div :class="[$v.f_gasproperties.required ? 'has-error' : 'has-success']">
            <input type="text" v-show="false" v-model="model.f_gasproperties"
                   v-validate:f_gasproperties='{required: true }'>
            <label for="f_gasproperties" class=" col-sm-2 control-label">用气性质</label>
            <div class="col-sm-3" id="f_gasproperties">
              <v-select v-model="model.f_gasproperties"
                        placeholder='请选择'
                        :value.sync="model.f_gasproperties"
                        :options='gastype'
                        :disabled='isEdit'
                        :value-single="true"
                        close-on-select>
              </v-select>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div :class="[$v.f_price_type.required ? 'has-error' : 'has-success']">
            <input type="text" v-show="false" v-model="model.f_price_type" v-validate:f_price_type='{required: true }'>
            <label for="f_price_type" class=" col-sm-2 control-label">气价类型</label>
            <div class="col-sm-3" id="choose">
              <v-select id="f_price_type"
                        v-model="model.f_price_type"
                        placeholder='请选择'
                        :value.sync="model.f_price_type"
                        :options='pricetype'
                        :disabled='isEdit'
                        :value-single="true"
                        close-on-select>
              </v-select>
            </div>
          </div>
          <div :class="[$v.f_price_name.required ? 'has-error' : 'has-success']">
            <label for="f_price_name" class=" col-sm-2 control-label">气价名称</label>
            <div class="col-sm-3">
              <input class="form-control" type="text" v-model="model.f_price_name"
                     v-validate:f_price_name='{required: true }' :disabled='isEdit' placeholder="气价名称">
            </div>
          </div>
        </div>
        <div v-if="model.f_price_type === '阶梯气价'">
          <div class="form-group">
            <label for="f_stairmonths" class=" col-sm-2 control-label">阶段月数</label>
            <div class="col-sm-3">
              <input class="form-control" type="number" v-model="model.f_stairmonths"
                     v-validate:f_stairmonths='{dctest: [ 12, "<=" ] }' :disabled='isEdit'>
              <span v-if="$v.f_stairmonths.dctest" style="color:red ">阶段月数不能大于12</span>
            </div>
            <div :class="[$v.f_stair_start_date.required ? 'has-error' : 'has-success']">
              <input type="text" v-show="false" v-model="model.f_stair_start_date"
                     v-validate:f_stair_start_date='{required: true }'>
              <label for="f_stair_start_date" class=" col-sm-2 control-label">阶梯开始日期</label>
              <div class="col-sm-3">
                <datepicker id="f_stair_start_date"
                            placeholder="阶梯开始日期"
                            v-model="model.f_stair_start_date"
                            :value.sync="model.f_stair_start_date"
                            :format="'yyyy-MM-dd'"
                            :disabled='isEdit'>
                </datepicker>
              </div>
            </div>
            <span id="helpBlock" class="help-block">本年或本月1号</span>
          </div>
          <div class="form-group">
            <div :class="[$v.f_population_base.pattern ? 'has-error' : 'has-success']">
              <label for="f_population_base" class=" col-sm-2 control-label">人口基数</label>
              <div class="col-sm-3">
                <input class="form-control" type="text" v-model="model.f_population_base"
                       :value.sync="model.f_population_base"
                       :disabled='isEdit' v-validate:f_population_base="{pattern: '/^[1-9]\\d*$/'}" placeholder="人口基数">
              </div>
            </div>
            <div :class="[$v.f_population_increment.pattern ? 'has-error' : 'has-success']">
              <label for="f_population_increment" class=" col-sm-2 control-label">人口增量</label>
              <div class="col-sm-3">
                <input class="form-control" type="text" v-model="model.f_population_increment"
                       :value.sync="model.f_population_increment"
                       :disabled='isEdit' v-validate:f_population_increment="{pattern: '/^[0-9]\\d*$/'}"
                       placeholder="人口增量">
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div :class="[$v.f_perform_date.required ? 'has-error' : 'has-success']">
            <input type="text" v-show="false" v-model="model.f_perform_date"
                   v-validate:f_perform_date='{required: true }'>
            <label for="f_perform_date" class=" col-sm-2 control-label">生效日期</label>
            <div class="col-sm-3">
              <datepicker id="f_perform_date"
                          placeholder="生效日期"
                          v-model="model.f_perform_date"
                          :value.sync="model.f_perform_date"
                          :format="'yyyy-MM-dd'"
                          :disabled='isEdit'>
              </datepicker>
            </div>
          </div>
          <label for="f_orgstr" class=" col-sm-2 control-label">使用公司</label>
          <div class="col-sm-3 form-group form-input-group">
            <right-tree :userid.sync='userid' :source.sync='source' @re-res="getRes"></right-tree>
          </div>
        </div>

        <div class="form-group" v-if="config.isLimit">
          <label for="f_limit_cycle" class=" col-sm-2 control-label">限购周期</label>
          <div class="col-sm-3">
            <input class="form-control" type="number" v-model="model.f_limit_cycle" placeholder="限购周期">
          </div>
          <label for="f_limit_gas" class=" col-sm-2 control-label">限购气量</label>
          <div class="col-sm-3">
            <input class="form-control" type="number" v-model="model.f_limit_gas" placeholder="限购气量">
          </div>
        </div>
        <div v-if="config.heatingSeason">
          <div class="form-group">
            <div :class="[$v.f_heat_start_date.required ? 'has-error' : 'has-success']">
              <input type="text" v-show="false" v-model="model.f_heat_start_date"
                     v-validate:f_heat_start_date='{required: true }'>
              <label class=" col-sm-2 control-label">采暖季开始日期</label>
              <div class="col-sm-3">
                <datepicker placeholder="阶梯开始日期"
                            v-model="model.f_heat_start_date"
                            :value.sync="model.f_heat_start_date"
                            :format="'MM-dd'"
                            :disabled='isEdit'>
                </datepicker>
              </div>
            </div>
            <div :class="[$v.f_heat_end_date.required ? 'has-error' : 'has-success']">
              <input type="text" v-show="false" v-model="model.f_heat_end_date"
                     v-validate:f_heat_end_date='{required: true }'>
              <label class=" col-sm-2 control-label">采暖季截止日期</label>
              <div class="col-sm-3">
                <datepicker placeholder="采暖季截止日期"
                            v-model="model.f_heat_end_date"
                            :value.sync="model.f_heat_end_date"
                            :format="'MM-dd'"
                            :disabled='isEdit'>
                </datepicker>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class=" col-sm-2 control-label">阶梯增量</label>
            <div class="col-sm-3">
              <input class="form-control" type="text" v-model="model.f_add_gas"
                     v-validate:f_add_gas='{required: true }' :disabled='isEdit' placeholder="阶梯增量">
            </div>
          </div>
        </div>
      </form>
      <div class="auto">
        <unit-price v-if="unitshow" :unitmodel.sync='model.detailprice' :is-disable.sync='isEdit'></unit-price>
        <mix-price v-if="mixshow" :mixmodel.sync='model.detailprice' :is-disable.sync='isEdit'></mix-price>
        <stair-price v-if="stairshow" :stairmodel.sync='model.detailprice' :is-disable.sync='isEdit'></stair-price>
      </div>
      <div style="text-align:right;height:auto;margin-top:6px;">
        <button class="btn btn-success" @click="confirm()" v-if="!isEdit" title="演示系统暂不支持" :disabled="true">确认</button>
        <button class="btn btn-default" @click="close()">取消</button>
      </div>
    </validator>
  </div>
</template>
<script>
  /**
   *阶梯气价管理组件
   */

  import {HttpResetClass} from 'vue-client'

  let initGen = async function (self, val) {
    // 启动流程的情况下 获取改气价有无正在审核的气价，若有则禁止编辑，若无则可编辑
    let hasUnAudit = false
    console.log('当前信息', val)
    if (self.config.audit) {
      let res = await self.$resetpost('rs/sql/saleSingleTable', {
        data: {
          tablename: 't_stairprice',
          condition: `f_price_id = '${val.f_price_id}' and f_filialeids = '${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_orgstr = self.model.f_orgstr ? self.model.f_orgstr : self.$login.f.filialestr
    self.model.f_filiale = self.model.f_filiale ? self.model.f_filiale : self.$login.f.f_fengongsi
    self.model.f_filialeids = self.model.f_filialeids ? self.model.f_filialeids : self.$login.f.f_orgids
    self.isEdit = self.model.f_state === '无效' || hasUnAudit
    console.log('观察data里面的model', self.model, val)
    if (self.model.id) {
      let price = await self.$SqlService.singleTable('t_detailprice', 'f_stairprice_id=' + "'" + self.model.id + "'")
      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,
        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: ''
        },
        // 编辑控制
        isEdit: false,

        // 公司树状图信息
        filialeNameStr: null,
        filialeCodeStr: null,
        userid: this.$login.f.id,
        source: `tool.getFullTree(this.getRights().where(row.getType() == $organization$))`,

        // 下拉框数据
        usertype: this.$appdata.getParam('用户类型'),
        pricetype: this.$appdata.getParam('气价类型'),
        gastype: []
      }
    },
    props: ['data', 'config'],
    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: ''}]
          this.stairshow = true
        }
      }
    },
    ready() {
      initGen(this, this.data)
    },
    methods: {

      confirm() {
        // 去除重复或者空的明细
        if (this.model.f_price_type[0] === '阶梯气价') {
          this.removeDuplication(this.model)
        }
        //处理，准备修改气价时，直接点了新建。
        if (!this.model.f_orgstr) {
          this.model.f_orgstr = this.$login.f.orgpathstr
        }

        // 审核配置
        this.model.audit = this.config.audit

        // 如果选择了分公司，直接赋选择值
        this.model.f_filiale = this.filialeNameStr ? this.filialeNameStr : this.$login.f.f_fengongsi
        this.model.f_filialeids = this.filialeCodeStr ? this.filialeCodeStr : this.$login.f.f_orgids
        console.log('看看分公司', this.filialeNameStr, this.filialeCodeStr, this.model)
        this.$LogicService.gasPrice(this.model, this.data).then((res) => {
          this.$dispatch('success', '气价管理', this.data, res)
        }).catch((error) => {
          this.$dispatch('error', '气价管理', this.data, error)
        })
        this.initModel()
      },

      getRes(obj) {
        this.filialeNameStr = obj.res
        this.filialeCodeStr = obj.resids
      },
      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
        }
      },
      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)
        }
      }
    }
  }
</script>
<style lang="less">
  #gas-price-form {
    .form-group {
      margin-left: 0px;
      margin-right: 0px;
    }
  }

</style>
