<template>
  <div class="auto">
    <modal :show.sync="show" v-ref:modal large backdrop="false">
      <header slot="modal-header" class="modal-header" style="text-align: center">
        <h4 class="modal-title">{{data.type}}撤销</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <validator name='v'>
          <form class="form-horizontal select-overspread">
            <div class="form-group" v-if="config.hasBillManage">
              <label class=" col-sm-2 control-label">发票撤销类型:</label>
              <div class="col-sm-2">
                <v-select v-model="f_cancel_type"
                          placeholder='请选择'
                          :value.sync="model.f_cancel_type"
                          :options='cancelTypes'
                          @change='cancelTypeChange'
                          :value-single="true"
                          close-on-select clear-button>
                </v-select>
              </div>
            </div>
            <div class="form-group" :class="[$v.f_cancel_reason.required ? 'has-error' : 'has-success']">
              <label for="f_cancel_reason" class=" col-sm-2 control-label">撤销原因:</label>
              <div class="col-sm-8">
                <textarea class="form-control" v-model="model.f_cancel_reason" rows="3"
                          placeholder="请填写原因" v-validate:f_cancel_reason='{required: true}'></textarea>
              </div>
            </div>
            <div class="form-group" :class="[$v.payment.required ? 'has-error' : '']"
                 v-if="data.type ==='物联网收费'|| data.type === '机表收费' || data.type === '卡表收费'|| data.type === '超用收费' || data.type === '发卡售气'|| data.type === '其他收费' ">
              <label class="col-sm-2 font_normal_body" title="参数名称：付款方式">收款方式:</label>
              <input type="text" v-show="false" v-model="$refs.payment.selectedItems"
                     v-validate:payment='{required: true }'>
                <div class="col-sm-4">
              <v-select v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype' clear-button v-ref:payment></v-select></div>
            </div>
            <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
          </form>
        </validator>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button class="btn btn-success" @click="confirm()" :disabled="!$v.valid">确认</button>
        <button class="btn btn-default" @click="clean()">取消</button>
      </footer>
    </modal>
    <correct-bill :show="print" :bill-config='config' :bill-data='billData'
                  @printok="printok" @toggle="printCancel" :data='printModel' v-ref:printbill ></correct-bill>
  </div>
</template>

<script>
  let postGen = async function (self, name) {
    let url = 'rs/logic/' + name

    // 获取冲正后的记录
    let returnfee = await self.$resetpost('rs/logic/returnFeeFromBank',self.model)
    let res = await self.$CancelService.cancel(url, self.model, self.data)
    console.log('冲正后的记录。。', res, self.model)

    // 判断需不需要判断冲正发票（发票管理）
    if (self.config.hasPrint) {
      if (self.model.f_cancel_type === 'newBill') {
        // 显示发票信息，
        self.printModel.id = res.data.record
        self.printModel.f_type = res.data.type
        self.printModel.f_use_type = self.model.f_use_type
        self.billData.url = self.getBillUrl(self.data.type)
        self.print = true
      } else if (self.model.f_cancel_type === 'abort') {
        await self.$CommonService.correctPaperBill(res.data.record, res.data.type, null, null, 'abort')
        self.$dispatch('cancel-success')
      }
    } else {
      self.$dispatch('cancel-success')
    }

    // 判断需不需要冲正电子票
    // if (self.isNeedEticket(getRecord.data, self.data.type)) {
    //   console.log('冲正打票，', getRecord.data.id, self.data.type)
    //   let getEticket = await self.$resetpost('rs/sql/singleTable', {
    //       data: {
    //         tablename: 't_eticket',
    //         condition: `f_sell_id = '${getRecord.data.id}' and f_type = '${self.data.type}'`
    //       }
    //     }, {resolveMsg: null, rejectMsg: '获取电子票明细失败!!'})
    //   console.log('获取电子票信息', getEticket)
    //   if (getEticket.data.length > 0) {
    //     await self.$CommonService.correctEticket(getRecord.data.id, self.data.type)
    //   }
    // }
  }

  let readyGen = async function (self) {
    await self.$getConfig(self, 'RecordCancel')
    console.log('冲正业务config', self.config)
    // 验证是否是卡表，如果是卡表提示卡表需要读卡撤销
    console.log('卡看看有没有是卡表的标识', self.data)

    // 查询获取表状态
    let res = await self.$resetpost('rs/sql/sale_getUserfilesDetail', {
      data: {
        condition: `f_userfiles_id = '${self.data.f_userfiles_id}'`
      }
    }, {resolveMsg: null, rejectMsg: '获取客户信息失败'})
    if (res.data[0].f_meter_type) {
      if (res.data[0].f_meter_type.includes('卡表') && self.data.type === '换表补气') {
        self.$showAlert(`您这是${res.data[0].f_meter_type}客户,撤销需要进行读卡撤销。`, 'warning', 5000)
        self.$dispatch('cancel')
      }
      if (res.data[0].f_meter_type.includes('机表') && self.data.type === '换表补气') {
        self.$showAlert(`您这是${res.data[0].f_meter_type}客户,暂不支持撤销。`, 'warning', 5000)
        self.$dispatch('cancel')
      }

      if (res.data[0].f_meter_type.includes('物联网表') && (self.data.type === '' || self.data.type === '气表清零')) {
        self.$showAlert(`您这是${res.data[0].f_meter_type}客户,暂不支持撤销。`, 'warning', 5000)
        self.$dispatch('cancel')
      }
    }
    // 获取原来收费记录使用的发票类型
    let param = {
      id: self.data.id,
      type: self.data.type
    }
    let oldUseType = await self.$resetpost('rs/logic/sale_getOldUseType', {data: param}, {resolveMsg: null, rejectMsg: '获取原始票据信息出错！！'})
    console.log('获取原始票据信息。。。', oldUseType)
    if (self.config.hasBillManage && self.config.cancelType === 'newBill' && oldUseType.data.billtype) {
      self.model.f_use_type = oldUseType.data.f_use_type
      self.model.f_bill_type = [oldUseType.data.billtype]
      self.hasValidateBill = self.config.hasBillManage
    }
    self.model.f_cancel_type = self.config.cancelType
    if (self.data.type === '物联网收费' || self.data.type === '机表收费' || self.data.type === '卡表收费' || self.data.type === '超用收费' || self.data.type === '发卡售气') {
      let getWebHand = await self.$SqlService.singleTable('t_sellinggas', `id = '${self.data.id}'`)
      console.log('-----a--a-a-a-a-a-', getWebHand)
      self.model.f_payment = [getWebHand.data[0].f_payment]
    }
    if (self.data.type === '其他收费') {
      let getWebHand = await self.$SqlService.singleTable('t_othercharge', `id = '${self.data.id}'`)
      console.log('-----a--a-a-a-a-a-', getWebHand)
      self.model.f_payment = [getWebHand.data[0].f_payment]
    }
  }

  export default {
    props: ['show', 'data'],
    title: '操作撤销',
    data () {
      return {
        config: {
          hasPrint: true,
          hasBillManage: true,  // 默认不启用发票管理
          cancelType: 'newBill'
        },
        model: {
          f_cancel_type: '',
          f_cancel_reason: '',
          f_cancel_name: this.$login.f.name,
          f_operator: this.$login.f.name,
          f_operatorid: this.$login.f.id,
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          f_depid: this.$login.f.depids,
          f_depname: this.$login.f.deps,
          record_id: ''
        },

        // 发票信息
        printModel: {},
        print: false,
        paytype: this.$appdata.getParam('付款方式'),
        billData: {
          url: '',
          bill: ''
        },
        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false
      }
    },
    ready () {
      readyGen(this)
    },
    methods: {
      confirm () {
        // 整理数据
        let name = this.sortdata()
        // 撤销操作请求
        postGen(this, name)
      },
      clean () {
        this.$dispatch('cancel', this.model)
      },
      // 判断type类型  整理数据
      sortdata () {
        this.model.record_id = this.data.id
        let type = this.data.type
        let name
        // 根据type数据 选择调用的Logic
        if (type === '过户') {
          name = 'transferCancel'
        } else if (type === '换新表' || type === '气表清零') {
          name = 'changemeterCancel'
        } else if (type === '机表收费') {
          name = 'machineChargeCancelPay'
        } else if (type === '物联网收费' || type === '物联网开户' || type === '卡表赠气' || type === '物联网赠费' || type === '卡表赠费' || type === '物联网赠气') {
          name = 'iotMeterChargeCancel'
        } else if (type === '开通') {
          name = 'iotOpenCancel'
        } else if (type === '卡表超用') {
          name = 'cardOverCancel'
        } else if (type === '超用收费') {
          name = 'overuseCancel'
        } else if (type === '其他收费') {
          name = 'otherFeeRollback'
        } else if (type === '维修收费') {
          name = 'otherFeeRollback'
        } else if (type === '补卡') {
          name = 'replaceCardCancel'
        } else if (type === '卡表收费') {
          name = 'noWriteCardCancel'
        } else if (type === '换表补气') {
          name = 'iotChangeAddGasCancel'
        } else if (type === '调价补费' || type === '调价退费') {
          name = 'compensationCancel'
        } else if (type === '预存缴费') {
          name = 'depositChargeCancel'
        } else if (type === '拆表') {
          name = 'cancelCB'
        } else if (type === '迁表') {
          name = 'cancelmovemeter'
        } else if (type === '气费减免') {
          name = 'machineChargeCancelPay'
        } else {
          return
        }
        return name
      },
      getBillUrl (type) {
        let name = ''
        // 根据type数据 选择调用的Logic
        if (type === '过户') {
          name = 'rs/report/transfer_bill'
        } else if (type === '换表') {
          console.log('看看row..', this.row)
          name = 'rs/report/change_meter'
        } else if (type === '机表收费') {
          name = 'rs/report/machine_bill'
        } else if (type === '物联网收费') {
          name = 'rs/report/pre_sell'
        } else if (type === '超用收费') {
          name = 'rs/report/overuse_bill'
        } else if (type === '其他收费') {
          name = 'rs/report/otherCharge_bill'
        } else if (type === '补卡') {
          name = 'rs/report/replace_sell'
        }
        return name
      },
      isNeedEticket (record, type) {
        // TODO 需要其他类型再继续加
        if (type === '补卡') {
          // 判断卡费是否大于零
          if (record.f_cardfees > 0) {
            return true
          }
        } else if (type === '其他收费') {
          if (record.f_collection > 0) {
            return true
          }
        } else if (type === '超用收费') {
          if (record.f_collection > 0) {
            return true
          }
        } else if (type === '物联网表收费') {
          if (record.f_collection > 0) {
            return true
          }
        }
        return false
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      printok () {
        this.$dispatch('cancel-success')
      },
      printCancel () {
        this.$dispatch('cancel')
      },
      cancelTypeChange () {
        console.log('撤销类型。。', this.model)
        if (this.model.f_cancel_type) {
          this.hasValidateBill = this.model.f_cancel_type === 'newBill'
        }
      }
    },
    computed: {
      cancelTypes () {
        return [{label: '使用新票号', value: 'newBill'}, {label: '旧发票作废', value: 'abort'}]
      }
    }
  }
</script>
