<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <div class="row" style="margin-top:10px;">
          <div class="col-sm-4"  :class="[$v.f_pregas.required || $v.f_pregas.dctest ? 'has-error' : 'has-success']">
            <label class=" font_normal_body" >*补气量</label>
            <input class="input_search" style="width:60%" type="text" v-model="model.f_pregas" :readonly="!applyButtonShow"
                   v-validate:f_pregas='{required: true, dctest: [0, ">=" ]}'  placeholder="补气量">
          </div>
          <div class="col-sm-4">
            <label  for="f_pregas" class=" font_normal_body" >补气金额</label>
            <input class="input_search" style="width:60%" type="text" v-model="model.f_fillamount"
                   v-validate:f_pregas='{required: true }' :readonly="!applyButtonShow" placeholder="补气金额">
          </div>
          <div class="col-sm-4">
            <label for="f_reason" class=" font_normal_body" >补气原因</label>
            <v-select id="f_reason"
                      v-model="model.f_reason"
                      placeholder='补气原因'
                      :value.sync="model.f_reason"
                      :options='addGasReason'
                      :disabled="!applyButtonShow"
                      close-on-select ></v-select>
          </div>
          <div class="col-sm-4">
            <label for="f_write_card" class=" font_normal_body">是否写卡</label>
            <v-select id="f_write_card"
                      v-model="model.f_write_card"
                      placeholder='是否写卡'
                      value-single
                      :value.sync="model.f_write_card"
                      :options='writecard'
                      :disabled="!applyButtonShow"
                      close-on-select clear-button></v-select>
          </div>
        </div>

        <div class="row" style="margin-top:10px;" v-if="model.f_reason[0] ==='其他'">
          <div class="col-sm-offset-2 col-sm-8" :class="[$v.f_othereason.required ? 'has-error' : '']">
            <label for="f_reason" class=" font_normal_body" >其他原因</label>
            <input class="input_search" style="width:60%" v-validate:f_othereason='{required: true }' rows="3" :readonly="!applyButtonShow" v-model="model.f_othereason" placeholder="请填写补气原因">
          </div>
        </div>
      </form>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' :data='row' @toggle="clean" @printok="printok"  v-ref:printbill></print-bill>
      <accept-bill :show="acceptprint" :bill-url='acceptUrl' v-on:toggle="close" :data='row' :billdata="printData" v-ref:acceptbill @closeaccept="closeAccept"></accept-bill>
      <div style="text-align:right;">
        <button class="button_search button_spacing" @click="accept()" v-if="config.hasAcceptance" :disabled='!$v.valid'>受理单</button>
        <button class="button_search button_spacing" v-show="config.approve == true ? applyButtonShow : false"  @click="apply()"  :disabled='!$v.valid'>掉气补气审核</button>
        <button class="button_search button_spacing" v-show="config.approve == true ? !applyButtonShow : true"  @click="confirm()"  :disabled='!$v.valid || buttonDisable'>确认</button>
        <button class="button_clear" v-show="applyButtonShow" @click="clean()">取消</button>
      </div>
    </validator>
    <modal :show.sync="addTaskModalShow" backdrop="false" width="40%" title="创建任务" small="true" @modal-close="addTaskModalClose()">
      <article slot="modal-body" class="row" style="padding: 10px">
        <add-apply-task :applytaskobj.sync="addTaskModel" @valid="addTaskValid = true" @invalid="addTaskValid = false">
        </add-apply-task>
      </article>
      <footer slot="modal-footer" class="modal-footer" style="text-align: right;border: 0">
        <button class="btn button_search" @click="addTask()"
                :disabled="!addTaskValid">新增审核任务
        </button>
      </footer>
    </modal>
  </div>
</template>
<script>

import {HttpResetClass} from "vue-client";

let asyncOffGasManage = async function (self, val) {
  await self.$getConfig(self, 'OffGasAddGas')
  console.log('掉气补气config', self.config)
  self.model.f_user_id = val.f_user_id
  self.model.f_userinfo_id = val.f_userinfo_id
  self.model.f_card_id = val.f_card_id
  self.model.f_meter_brand = val.f_meter_brand
  let data = {
    items: '*',
    tablename: 't_sellinggas',
    condition: 'f_user_id=' + "'" + self.model.f_user_id + "'" + 'and f_userinfo_id=' + "'" + self.model.f_userinfo_id + "'" + 'and (f_type=' + "'" + '卡表收费' + "'" + 'or f_type=' + "'" + '发卡售气' + "'" + 'or f_type=' + "'" + '转气转入' + "'" + 'or f_type=' + "'" + '物联网收费' + "')" + "and f_state='有效'",
    orderitem: 'id desc'
  }
  await self.$SqlService.singleTableOrderBy(data).then((res) => {
    console.log('看下吧返回的是什么：' + JSON.stringify(res))
    self.model.f_pregas = res.data[0].f_pregas
    self.model.f_fillamount = res.data[0].f_preamount
    self.model.f_lastremain_fillgas = self.model.f_pregas
    self.model.f_theremain_fillgas = self.model.f_lastremain_fillgas - self.model.f_pregas
  }).catch((error) => {
    self.$dispatch('error', '掉气补气', self.row, error)
  })
}
export default {
  title: '掉气补气',
  data () {
    return {
      config: {
        hasPrint: false,  // 默认打票
        hasBillManage: false,  // 默认不启用发票管理
        billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费',
        hasAcceptance: false, // 是否需要打印受理单
        approve: false
      },
      print: false,
      billData: {
        url: 'rs/report/acceptOffGasAddGas_bill',
        billnumber: ''
      },
      model: {
        f_pregas: '',
        f_write_card: '写卡',
        f_lastremain_fillgas: '',
        f_fillamount: '',
        f_theremain_fillgas: '',
        f_reason: '掉气补气',
        f_othereason: '',
        f_meter_brand: '',
        f_card_id: ''
      },
      hasValidateBill: false,
      validateOk: false,
      writecard: [{label: '写卡',value:'写卡'},{label: '不写卡',value:'不写卡'}],

      // 受理单
      acceptprint: false,
      acceptUrl: '',
      printData: {
        reason: '',
        fillgas: '',
        fillamount: ''
      },
      addGasReason: this.$appdata.getParam('补气原因'),
      addTaskModel: {
        f_task_name: '',
        f_userinfo_code: '',
        f_work_flow_name: '',
        f_approval: this.$appdata.getSingleValue('审核员角色') ? this.$appdata.getSingleValue('审核员角色') : '',
        f_memorandum: ''
      },
      addTaskValid: false,
      addTaskModalShow: false,
      buttonDisable: false
    }
  },
  props: {
    row: {
      type: Object,
      default: undefined
    },
    applyButtonShow: {
      type: Boolean,
      default: true
    },
    dataModel: {
      type: Object,
      default: undefined
    }
  },
  ready () {
    this.model.f_user_id = this.row.f_user_id
    this.model.f_userfiles_id = this.row.f_userfiles_id
    this.model.f_userinfo_id = this.row.f_userinfo_id
    this.model.f_card_id = this.row.f_card_id
    asyncOffGasManage(this, this.row).then(() => {
      this.$emit(ready())
    }).catch((error) => {
      this.$emit('error', error)
    })
  },
  watch: {
    // 'row' (val) {
    //   this.model.f_user_id = val.f_user_id
    //   this.model.f_userinfo_id = val.f_userinfo_id
    //   this.model.f_card_id = val.f_card_id
    //   this.model.f_meter_brand = val.f_meter_brand
    //   let data = {
    //     items: '*',
    //     tablename: 't_sellinggas',
    //     condition: 'f_user_id=' + "'" + this.model.f_user_id + "'" + 'and f_userinfo_id=' + "'" + this.model.f_userinfo_id + "'" + 'and (f_type=' + "'" + '卡表收费' + "'" + 'or f_type=' + "'" + '发卡售气' + "')" +"and f_state='有效'",
    //     orderitem: 'f_operate_date desc, id desc'
    //   }
    //   this.$SqlService.singleTableOrderBy(data).then((res) => {
    //     console.log('看下吧返回的是什么：' + JSON.stringify(res))
    //     this.model.f_pregas = res.data[0].f_pregas
    //     this.model.f_fillamount = res.data[0].f_preamount
    //     this.model.f_lastremain_fillgas = this.model.f_pregas
    //     this.model.f_theremain_fillgas = this.model.f_lastremain_fillgas - this.model.f_pregas
    //   }).catch((error) => {
    //     this.$dispatch('error', '掉气补气', this.row, error)
    //   })
    // }
    'dataModel' (val) {
      console.log('看看dataModel的值：', val)
      if (val) {
        this.$nextTick(() => {
          this.model=Object.assign({},this.model,val)
        })
      }
    }
  },
  methods: {
    addTaskModalClose () {
      this.addTaskModel.f_work_flow_name = ''
      this.addTaskModel.f_task_name = ''
      this.addTaskModel.f_userinfo_code = ''
      this.addTaskModel.f_memorandum = ''
    },
    addTask () {
      if (this.addTaskModel.f_userinfo_code != this.row.f_userinfo_code) {
        this.$showAlert('请填写正确的用户编号！！！', 'warning', 3000)
        return
      }
      let memorandum = {
        f_memorandum: this.addTaskModel.f_memorandum
      }
      this.model.f_business_name = '掉气补气'
      this.model.f_user_name = this.row.f_user_name
      let data = {
        f_created_by: this.$login.f.name,
        f_orgid: this.$login.f.orgid,
        f_orgname: this.$login.f.orgs,
        f_depid: this.$login.f.depids,
        f_depname: this.$login.f.deps,
        addModel: this.addTaskModel,
        f_memorandum: JSON.stringify(memorandum),
        f_userinfo_json: this.model,
        f_userinfo_id: this.row.f_userinfo_id
      }
      this.$resetpost('rs/logic/future_createWorkFlowTask', {'data': data}
        , {resolveMsg: null, rejectMsg: '新增任务失败！！'}).then(
        (res) => {
          this.$showAlert(res.data.msg + '请等待审批完成后去流程页面进行操作！！！', 'info', 3000)
          this.addTaskModalClose()
          this.addTaskModalShow = false
          this.$dispatch('refresh')
        }
      )
    },
    async apply () {
      let http = new HttpResetClass()
      let param = {
        items: 'id',
        condition: `f_userinfo_id = '${this.row.f_userinfo_id}' and f_state = '0' and f_delete = '0'`,
        tablename: '"t_flow"',
        orderitem: '"id"'
      }
      let result = await http.load('POST', 'rs/sql/saleSingleTable', {data: param},
        {resolveMsg: null, rejectMsg: '获取流程信息失败！！'})
      if (result.data.length > 0) {
        this.$showAlert('当前申请用户已有流程在进行中，请完成当前进行流程在进行申请！！！', 'warning', 3000)
        return
      }
      this.addTaskModel.f_task_name = `用户：${this.row.f_user_name}，编号：${this.row.f_userinfo_code} 申请掉气补气`
      this.addTaskModel.f_userinfo_code = this.row.f_userinfo_code
      this.addTaskModel.f_memorandum = this.model.f_othereason
      this.addTaskModalShow = true
    },
    close () {
      this.acceptprint = false
      // this.clean()
    },
    clear () {
      this.$dispatch('refresh')
    },
    accept () {
      // 打印受理单
      if (this.model.f_othereason || this.model.f_reason[0] === '其他') {
        this.printData.reason = `'${this.model.f_othereason}'`
      } else {
        this.printData.reason = this.model.f_comments ? `'${this.model.f_reason[0]}'` : '' + `'${this.model.f_reason}'`
      }
      this.printData.fillgas = `'${this.model.f_pregas}'`
      this.printData.fillamount = `'${this.model.f_fillamount}'`
      console.log('受累单中printData', this.printData)
      this.acceptUrl = 'rs/report/acceptOffGasAddGas_bill'
      this.acceptprint = true
    },
    closeAccept () {
      this.acceptprint = false
    },
    confirm () {
      this.buttonDisable = true
      this.$dispatch('no-button')
      this.row.cardInfo = this.cardData
      this.$OffGasAddGasService.offGasAddGas(this.model, this.row).then((res) => {
        if (this.config.approve) {
          console.log('存储补气业务信息')
          let obj = {
            data: {
              id: res
            }
          }
          this.$dispatch('futureapply', obj)
          // 向上级触发一个事件改变流程的操作状态
          this.$dispatch('changeFlowOperateState')
        }
        if (this.config.hasPrint) {
          if (this.config.hasBillManage) {
            this.row.id = res
            this.row.f_bill_type = '掉气补气'
            this.row.f_bill_style = ''
            this.print = true
          } else {
            this.row.id = res
            this.print = true
          }
        } else {
          this.$dispatch('success', '掉气补气', this.row, res)
        }
      }).catch((error) => {
        if (error.status === 603) {
          this.$error('重复提交')
          return
        }
        this.buttonDisable = false
        this.$dispatch('error', '掉气补气', this.row, error)
      })
    },
    printok () {
      this.$dispatch('success', '掉气补气')
    },
    clean () {
      this.print = false
      this.$dispatch('cancelclean', this.row)
    }
  }
}
</script>

<style>
</style>
