<template>
  <div class="auto select-overspread" style="overflow-y: scroll;height: 100%">
    <validator name='v'>
      <form class="form-horizontal" novalidate>
        <ul class="nav nav-tabs">
          <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">
            <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 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">
            <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">
            <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 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">
            <label class="font_normal_body" for="f_price_name">气价名称</label>
            <input :disabled='isEdit' class="input_search" placeholder="气价名称" style="width:60%"
                   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="col-sm-6">
            <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='{dctest: [ 12, "<=" ] }'>
            <span style="color:red " v-if="$v.f_stairmonths.dctest">阶段月数不能大于12</span>
          </div>
          <div :class="[$v.f_stair_start_date.required ? 'has-error' : 'has-success']" class="col-sm-6">
            <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"
                        id="f_stair_start_date"
                        placeholder="阶梯开始日期"
                        v-model="model.f_stair_start_date"
            style="width: 60%">
            </datepicker>
            <span class="help-block" id="helpBlock">本年或本月1号</span>
          </div>
        </div>
        <div class="row">
          <div  class="col-sm-6" :class="[$v.f_perform_date.required ? 'has-error' : 'has-success']" 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'
                        :format="'yyyy-MM-dd'"
                        :value.sync="model.f_perform_date"
                        id="f_perform_date"
                        placeholder="生效日期"
                        v-model="model.f_perform_date" style="width: 60%">
            </datepicker>
          </div>
          <div class="col-sm-6">
          <label class="font_normal_body">是否低保</label>
          <v-select :options='isLowIncomes'
                    :value-single="true"
                    :value.sync="model.f_islow_income"
                    close-on-select
                    placeholder='请选择'
                    v-model="model.f_islow_income" style="width: 60%">
          </v-select>
          </div>
          <div class="col-sm-6" v-if="model.f_price_type === '阶梯气价'" :class="[$v.f_population_base.pattern ? 'has-error' : 'has-success']">
            <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">
            <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">
          <div class="row">
            <div :class="[$v.f_heat_start_date.required ? 'has-error' : 'has-success']" class="col-sm-6">
              <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"
                          placeholder="阶梯开始日期"
                          v-model="model.f_heat_start_date">
              </datepicker>
            </div>
            <div :class="[$v.f_heat_end_date.required ? 'has-error' : 'has-success']" class="row">
              <input class="input_search" style="width:60%" type="text" v-model="model.f_heat_end_date" v-show="false"
                     v-validate:f_heat_end_date='{required: true }'>
              <label class="font_normal_body">采暖季截止日期</label>
              <datepicker :disabled='isEdit'
                          :format="'MM-dd'"
                          :value.sync="model.f_heat_end_date"
                          placeholder="采暖季截止日期"
                          v-model="model.f_heat_end_date">
              </datepicker>
            </div>
            <span class="help-block">次年</span>
          </div>
          <div class="row">
            <label class="font_normal_body">采暖季方式</label>
            <v-select :disabled='isEdit'
                      :options='hearways'
                      :value-single="true"
                      :value.sync="model.f_heat_way"
                      close-on-select
                      placeholder='请选择'
                      v-model="model.f_heat_way">
            </v-select>
            <label class="font_normal_body">采暖季增量</label>
            <input :disabled='isEdit' class="input_search" placeholder="阶梯增量" style="width:60%"
                   type="text" v-model="model.f_add_gas" v-validate:f_add_gas='{required: true }'>
          </div>
        </div>

        <div class="col-sm-12">
          <label  class="font_normal_body " style="margin-top:-20px">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
          <textarea class="input_textarea" rows="3" style="width:80%;margin-top:5px" v-model="model.f_comments"></textarea>
        </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' :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>-->
    </validator>
    <limit-gas :f_price_id="model.id" :show.sync="limitShow" @limit="getLimitGas"></limit-gas>
  </div>
</template>
<script>
  /**
   *阶梯气价管理组件
   */

  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_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.isEdit = self.model.f_price_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: '',
          f_heat_way: '按月',
          f_islow_income: '0',
          f_comments:''
        },
        // 编辑控制
        isEdit: false,

        // 公司树状图信息
        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'}],
        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: ''}]
          this.stairshow = true
        }
      }
    },
    ready() {
      initGen(this, this.data)
    },
    methods: {

      confirm() {

        // 验证公司组织是否已选择
        if (!this.f_filialeid) {
          this.$showAlert('请选择气价使用公司', 'warning', 2000)
          return
        }

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

        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
        }
        console.log('看看分公司', this.f_filialeid, 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()
      },

      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: '删除气价失败'
          })
        }
        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:''
        }
      },
      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)
        }
      },
      limitClick() {
        this.limitShow = true
      }
    }
  }
</script>
<style lang="less">
  #gas-price-form {
    .form-group {
      margin-left: 0px;
      margin-right: 0px;
    }
  }

</style>
