<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: auto;min-height: 500px;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <!--          <div class="row" style="margin-top:10px;">-->
          <!--            -->
          <!--          </div>-->
          <div style="margin-top:10px;" v-for="(index, row) in model.otherdetail">
            <div class="row">
              <div class="col-sm-4" :class="{'has-success':row.f_brand_spec,'select-error':!row.f_brand_spec}">
                <label for="f_brand_spec" class="font_normal_body " title="参数名称：品名及规格">收费项目</label>
                <v-select id="f_brand_spec"
                          placeholder='请选择'
                          v-model="row.f_brand_spec"
                          :value.sync="row.f_brand_spec"
                          :options='brandspec'
                          @change="setTypename(row,index)"
                          close-on-select clear-button>
                </v-select>
              </div>
              <div class="col-sm-4" :class="{'has-success':row.f_typename,'has-error':!row.f_typename}">
                <label for="f_typename" class=" font_normal_body">&nbsp;品名规格</label>
                <v-select
                  style="width: 100px"
                  v-model="row.f_typename"
                  placeholder='请选择'
                  :value.sync="row.f_typename"
                  :options='row.typeNameList'
                  @change="setTypenumber(row,index)"
                  close-on-select clear-button>
                </v-select>
              </div>
              <div class="col-sm-4" :class="{'has-success':row.f_typenumber,'has-error':!row.f_typenumber}">
                <label for="f_typenumber" class=" font_normal_body">&nbsp;型&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号</label>
                <v-select
                  style="width: 100px"
                  v-model="row.f_typenumber"
                  placeholder='请选择'
                  :value.sync="row.f_typenumber"
                  :options='row.typenumberList'
                  @change="setTypeprice(index)"
                  close-on-select clear-button>
                </v-select>
              </div>
            </div>
            <div class="row">
              <div class="col-sm-4" :class="{'has-success':row.f_unitprice,'has-error':!row.f_unitprice}">
                <label style="" for="f_unitprice" class=" font_normal_body">*单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价</label>
                <input class="input_search" style="width:60%" type="number" min="1" @input.prevent="getcollection()"
                       v-model="row.f_unitprice"
                       v-validate:f_unitprice='{required: true}'
                       :value.sync="row.f_unitprice"
                       :disabled="false"
                       placeholder="单价" v-next-el='sl'>
              </div>
              <div class="col-sm-4" :class="{'has-success':row.f_number,'has-error':!row.f_number}">
                <label style="" for="f_number" class="font_normal_body">*数&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;量</label>
                <input class="input_search" style="width:60%" type="number" min='1' @input.prevent="getcollection()"
                       v-validate:f_number='{required: true, dctest: [0, ">" ] }'
                       v-model="row.f_number"
                       :value.sync="row.f_number"
                       placeholder="数量" v-next-el='sk' v-el:sl>
              </div>
              <div style="padding-top:10px">
                <button type="button" class="glyphicon glyphicon-minus btn-danger"
                        @click.stop="delthisdetail($index)"></button>&nbsp;&nbsp;&nbsp;
                <button type="button" class="glyphicon glyphicon-plus btn-success" @click.stop="addadetail()"></button>
              </div>
            </div>
            <!--            <div class="row" style="margin-top:10px;" v-if="row.f_brand_spec[0]=='其他费用'">-->
            <!--              <div class="col-sm-4" :class="[$v.f_fee_type.required ? 'has-error' : 'has-success']">-->
            <!--                <input v-validate:f_fee_type='{required: true}' v-model="row.f_fee_type" v-show="false"/>-->
            <!--                <label for="f_fee_type" class="font_normal_body ">其他收费类型</label>-->
            <!--                <v-select id="f_fee_type"-->
            <!--                          v-model="row.f_fee_type"-->
            <!--                          placeholder='请选择'-->
            <!--                          :value.sync="row.f_fee_type"-->
            <!--                          :options='feetype'-->
            <!--                          close-on-select clear-button>-->
            <!--                </v-select>-->
            <!--              </div>-->

            <!--              <div class="col-sm-4">-->
            <!--                <label for="f_fee_time" class="font_normal_body">本次购买时间</label>-->
            <!--                <v-select id="f_fee_time"-->
            <!--                          v-model="row.f_fee_time"-->
            <!--                          placeholder='请选择'-->
            <!--                          :value.sync="row.f_fee_time"-->
            <!--                          :options='feetime'-->
            <!--                          close-on-select clear-button>-->
            <!--                </v-select>-->
            <!--              </div>-->
            <!--            </div>-->

          </div>


          <div class="row" style="margin-top:10px;">
            <div class="col-sm-4 form-group" :class="[$v.payment.required ? 'select-error' : '']">
              <label class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
              <input type="text" v-show="false" v-model="$refs.payment.selectedItems"
                     v-validate:payment='{required: true }'>
              <v-select v-model="model.f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        close-on-select
                        :options='paytype' clear-button v-ref:payment></v-select>
            </div>
            <div class="col-sm-4">
              <label for="f_print" class="font_normal_body">&nbsp;打印格式</label>
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button>
              </v-select>
            </div>
            <div class="col-sm-4">
              <label for="f_collection" class="font_normal_body">&nbsp;收&emsp;&emsp;款</label>
              <label for="f_collection" class="font_normal_body">{{ model.f_collection }}</label>
            </div>
          </div>
          <div class="row" style="margin-top:10px;" v-if="model.f_payment[0].includes('POS')">
            <div class="col-sm-4">
              <label for="f_voucher_number" class="font_normal_body">&nbsp;&nbsp;&nbsp;凭证号</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_voucher_number"
                     placeholder="凭证号">
            </div>
          </div>
          <div class="row" style="margin-top:10px;">
            <div class="col-sm-4" v-show="false">
              <label for="f_voucher_number" class="font_normal_body">服务人员</label>
              <v-select v-model="model.f_service_person"
                        placeholder='请选择'
                        :value.sync="model.f_service_person"
                        :options='services'
                        close-on-select clear-button>
              </v-select>
            </div>
            <div class="col-sm-8">
              <label for="f_comments" class=" font_normal_body">&nbsp;备&emsp;&emsp;注</label>
              <input type="text" class="input_search" style="width:80%" v-model="model.f_comments" rows="1"
                     placeholder="备注">
            </div>
          </div>
        </form>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <print-bill :show="print" :data='row' :bill-config='config' :bill-data='billData' v-on:toggle="close"
                    @printok="printok" v-ref:printbill></print-bill>
        <ticket-print :show="eticket_show" @toggle="eticket_toggle" v-ref:eticketbill></ticket-print>
        <eticket-modal :show="eticket_msg" @closemodalshow="eticket_msg = false" :row="row" @confirm="confirm"></eticket-modal>
        <!-- <print-other-charge-bill :show="print" v-ref:printbill :row='row' :logic='model' v-on:success="close" v-on:toggle="close"></print-other-charge-bill> -->
        <!-- <tax-other-bill :show="taxprint"  v-ref:taxprintbill :row='row' :logic='model' v-on:success="close" v-on:toggle="close"></tax-other-bill> -->
        <div style="text-align:right;height: 25%;">
          <button v-if="config.modificationList" class="button_search" @click="confirm(true)"
                  :disabled=' validflag || validateOk'>确认并转单
          </button>
          <payment-code-button :clickable=" validflag || validateOk"
                               :payment.sync="model.f_payment" :payment-data="paytype"
                               @confirm-payment="confirm()">
          </payment-code-button>
          <button class="button_search btn-gn" v-if="authArr.includes('其它欠费生成')" @click="createQianfei()"
                  :disabled=' validflag || validateOk || !model.f_collection'>生成欠费
          </button>
          <button class="button_search btn-gn" @click="checkInvoiceMsg()" :disabled='validflag || validateOk || !model.f_collection'>确认
          </button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
      <upload :blodid="blodid" v-if="config.showupload"  isremark="true" fusetype="其他收费"></upload>
    </div>
    <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_collection"></payment-code>
  </div>
</template>
<script>
let otherChargeGen = async function (self, parameter) {
  try {
    // 加入扫码盒付款码支付流水号
    self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
    console.log('11111', self.model)
    let resid = await self.$LogicService.otherCharge(self.model, self.row)
    console.log('其他收费返回id', resid, self.config.hasPrint, self.$login.r.includes('不打印发票'))
    if (self.config.dispatch) {
      await self.$showMessage(`是否添加派工单`, ['confirm', 'cancel']).then((res) => {
        if (res === 'confirm') {
          console.log('其他收费xinxi', self.model)
          console.log('其他收费xinxi', self.row)
          let batch = {
            sf_id: resid.data,
            f_userinfo_code: self.row.f_userinfo_code,
            f_dispathch_name: self.row.f_user_name,
            f_phone: self.row.f_user_phone,
            f_dispathch_address: self.row.f_address,
            f_meternumber: self.row.f_meternumber,
            f_dispathch_type: '安装',
            f_source: '其他收费',
            f_money: self.model.f_collection,
            f_remarks: self.model.f_comments,
            f_operator_date: self.$login.toStandardTimeString(),
            f_orgid: self.$login.f.orgid,
            f_dispathch_state: '待分配'
          }
          console.log('111:', batch)
          self.$resetpost('rs/logic/savePatch', batch).then((res1) => {
            // this.params.rows.splice(index, 1)
            console.log('更新成功！', res1.data.id)
          })
        }
      })
    }
    let localeSustainMoney = window.localStorage.getItem('sustainMoney')
    if (localeSustainMoney != null) {
      localeSustainMoney = (localeSustainMoney - 0) + (self.model.f_collection - 0)
      window.localStorage.setItem('sustainMoney', localeSustainMoney)
    }
    // // 转燃气改装工程单
    // if (self.config.modificationList && parameter) {
    //   let printSheet = {
    //     f_userinfo_id: self.row.f_userinfo_id,
    //     f_charge_id: resid.data,
    //     f_state: '有效',
    //     f_print_state: '未打印',
    //     f_type: '改装单',
    //     f_orgid: self.$login.f.orgid ? self.$login.f.orgid : '',
    //     f_orgname: self.$login.f.orgs ? self.$login.f.orgs : '',
    //     f_depid: self.$login.f.depids ? self.$login.f.depids : '',
    //     f_depname: self.$login.f.deps ? self.$login.f.deps : '',
    //     f_operator: self.$login.f.name,
    //     f_operatorid: self.$login.f.id
    //   }
    //   await self.$resetpost('rs/logic/savePrintSheet', {data: {printData: printSheet}}, {
    //     resolveMsg: '',
    //     rejectMsg: '转单失败, 请重试'
    //   })
    // }
    if (self.config.hasPrint && !self.$login.r.includes('不打印发票')) {
      if (self.model.f_print[0] != '电子发票') {
        if (self.config.hasBillManage) {
          self.row.id = resid.data
          self.row.f_bill_type = '其他收费'
          self.row.f_bill_style = self.model.f_print[0]
          self.print = true
        } else {
          self.row.id = resid.data
          self.print = true
        }
      } else if (self.model.f_print[0] === '国税发票') {
        // TODO
        self.$dispatch('success')
      } else if (self.model.f_print[0] === '电子发票') {
        self.eticket_show = true
        await self.$refs.eticketbill.openETicket([resid.data], self.row, '是', self.invoice_is_pax, '其他收费')
        // self.$CommonService.openEticket(resid.data, '其他收费')
        // self.$dispatch('success')
      }
    } else {
      self.$dispatch('success')
    }
  } catch (error) {
    console.log(error)
    self.$showAlert(error, 'danger', 0)
    self.$dispatch('refresh')
  }
}

let asyncOtherCharge = async function (self) {
  await self.$getConfig(self, 'OtherCharge')
  self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
  self.model.f_payment = [self.config.payment]
  self.model.otherdetail[0].f_brand_spec = [self.config.brandspec]
  self.model.f_service_person = [self.config.services]

  self.model.f_use_type = self.config.billType
  self.model.f_bill_type = self.model.f_print
  self.hasValidateBill = self.config.hasBillManage
  // self.setTypename(self.model.f_brand_spec[0])
}
export default {
  title: '其他收费',
  data () {
    return {
      config: {
        showupload: true,
        checkFlag: false,
        modificationList: false,
        dispatch: false,
        hasPrint: true,  // 默认打票
        hasBillManage: false,  // 默认不启用发票管理
        billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费',  // 付款方式
        brandspec: '材料费', // 收费类型
        services: this.$login.f.name // 服务人员
      },
      model: {
        f_print: [],
        f_payment: '现金缴费',
        f_number: 0,
        f_unitprice: 0,
        f_collection: 0,
        f_comments: '',
        f_voucher_number: '',
        f_service_person: '',
        // 用户其他费用信息
        t_userfees: '',
        f_fee_type: ['其他费用'],
        f_fee_time: ['12'],
        otherdetail: [{f_brand_spec: [''], typeNameList: [], f_typenumber: '', typenumberList: [], f_unitprice: '', f_number: 1}]
      },
      eticket_msg: false,
      eticket_show: false,
      invoice_is_pax: '征税',
      is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
      print: false,
      taxprint: false,
      billData: {
        url: 'rs/report/otherCharge_bill',
        bill: ''
      },

      // 启用发票管理需要对票号进行验证
      hasValidateBill: false,
      validateOk: false,
      f_typenumber: '',
      typeNameList: [],
      typenumberList: [],
      brandspec: this.$appdata.getParam('品名及规格'),
      printstyle: this.$appdata.getParam('打印格式'),
      paytype: this.$appdata.getParam('付款方式'),
      feetype: this.$appdata.getParam('其他费用'),
      services: this.$appdata.getParam('服务人员'),
      isflag: false
    }
  },
  props: ['row'],
  ready () {
    // this.model.f_unitprice = this.$appdata.getSingleValue('置换气费')
    asyncOtherCharge(this)
  },
  watch: {
    'model.f_fee_type' (val) {
      if (val[0]) {
        this.userfees(this.row.f_userinfo_id, val[0])
      }
    }
  },
  methods: {
    setTypeprice (val) {
      console.log('单价变化：', val)
      if (this.model.otherdetail[val] && this.model.otherdetail[val].f_typenumber[0]) {
        let unitprice = this.$appdata.getSingleValue(this.model.otherdetail[val].f_typenumber[0])
        if (unitprice !== undefined) {
          this.model.otherdetail[val].f_unitprice = unitprice
        }
      }
      // if (this.model.otherdetail[val].f_typename.includes('壁挂炉之前安装材料费') ||
      //   this.model.otherdetail[val].f_typename.includes('热水器之前安装材料费')) {
      //   if (this.model.otherdetail[val].f_typenumber.includes('4米')) {
      //     this.model.otherdetail[val].f_unitprice = 192
      //   } else {
      //     this.model.otherdetail[val].f_unitprice = ''
      //   }
      // } else {
      //   this.model.otherdetail[val].f_unitprice = ''
      // }
    },
    async createQianfei () {
      let data = {
        f_serial_id: this.model.f_serial_id,
        record_userinfo: this.row.f_userinfo_id,
        f_serial_number: this.model.f_serial_number,
        f_userfiles_id: this.row.f_userfiles_id,
        f_user_id: this.row.f_user_id,
        f_user_name: this.row.f_user_name,
        f_address: this.row.f_address,
        f_user_type: this.row.f_user_type,
        f_gasproperties: this.row.f_gasproperties,
        // f_number: model.f_number,
        // f_unitprice: model.f_unitprice,
        f_collection: this.model.f_collection,
        f_comments: this.model.f_comments,
        f_payment: this.model.f_payment[0],
        f_voucher_number: this.model.f_voucher_number,
        f_bill_style: this.model.f_print[0],
        // f_brand_spec: model.f_brand_spec[0],
        f_userinfo_id: this.row.f_userinfo_id,
        f_service_person: this.model.f_service_person[0],
        f_operat_type: '其他收费欠费登记',
        f_describe: `${this.$login.f.name}对客户${this.row.f_user_name}进行其他收费欠费登记操作`,
        f_state: '有效',
        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,
        f_zoneid: this.$login.f.zoneid,
        f_zones: this.$login.f.zones,
        f_is_pay: '否',
        // 其他费用信息
        t_userfees: this.model.t_userfees,
        f_fee_type: this.model.f_fee_type[0],
        f_fee_time: this.model.f_fee_time[0],
        otherdetail: this.model.otherdetail
      }
      await this.$resetpost('rs/logic/sale_othercharge_logic_nopay', data, {
        resolveMsg: '生成其他欠费成功',
        rejectMsg: '生成其他欠费失败'
      })
      this.$dispatch('success')
    },
    // 校验发票信息
    checkInvoiceMsg () {
      if (this.model.f_print[0] === '电子发票') {
        if (!this.row.f_taxpayer_id) {
          this.row.f_taxpayer_id = this.row.f_idnumber
        }
        if (!this.row.f_paper_name) {
          this.row.f_paper_name = this.row.f_user_name
        }
        if (!this.row.f_address_phone) {
          this.row.f_address_phone = this.row.f_address + ' ' + this.row.f_user_phone
        }
        if (!this.row.f_email) {
          this.row.f_email = this.row.f_email
        }
        this.eticket_msg = true
      } else {
        this.confirm()
      }
    },
    eticket_toggle () {
      this.eticket_show = false
      this.$dispatch('success')
    },
    async setTypename (val, index) {
      this.model.otherdetail[index].f_typenumber = ''
      this.model.otherdetail[index].typeNameList = this.$appdata.getParam(val.f_brand_spec[0])
      this.model.otherdetail[index].typenumberList = []
      this.model.otherdetail[index].f_unitprice = ''
      let self = this
      if (val == '开卡费') {
        if (this.$appdata.getSingleValue('开卡费')) {
          let money = this.$appdata.getSingleValue('开卡费')
          await this.model.otherdetail.forEach(function (item) {
            self.isflag = false
            if (item.f_brand_spec[0] == '开卡费') {
              item.f_unitprice = money
              item.f_number = 1
              self.isflag = true
            }
          })
          this.getcollection()
        }
      }
    },
    setTypenumber (val, index) {
      this.model.otherdetail[index].f_typenumber = ''
      this.model.otherdetail[index].typenumberList = this.$appdata.getParam(val.f_typename[0 ])
      this.model.otherdetail[index].f_unitprice = ''
    },
    async confirm (parameter) {
      let res = await this.$showMessage(`确定对客户${this.row.f_user_name}进行其他收费吗？`, ['confirm', 'cancel'])
      if (res != 'confirm') return
      this.eticket_msg = false
      // 先调用付款码支付组件流程
      let ss = await this.$refs.paymentcode.flowPath()
      this.$refs.paymentcode.paymentCodeShow = false
      console.log('付款码操作返回', ss)
      if (!ss.result) return
      otherChargeGen(this, parameter)
    },
    clean () {
      this.$dispatch('refresh', this.row)
    },
    close () {
      this.taxprint = false
      this.print = false
      this.clean()
    },
    printok () {
      this.$dispatch('success')
    },
    validateBill (val) {
      this.validateOk = !val.isOk
      this.billData.bill = val.bill
    },
    getcollection () {
      let money = 0
      let flag = true
      this.model.otherdetail.forEach((item) => {
        if (!item.f_number || item.f_number == '0') flag = false
        if (!item.f_unitprice || item.f_unitprice == '0') flag = false
        if (item.f_unitprice && item.f_number) {
          money += ((item.f_unitprice - 0) * (item.f_number - 0)) - 0
        } else {
          flag = false
          this.model.f_collection = 0
        }
      })
      if (money != 0) {
        this.model.f_collection = money.toFixed(2)
      }
      if (!flag) this.model.f_collection = ''
    },
    addadetail () {
      this.$set(`model.otherdetail[${this.model.otherdetail.length}]`, {f_brand_spec: [''], f_typenumber: '', typeNameList: [], typenumberList: [], f_unitprice: '', f_number: ''})
      console.log(JSON.stringify(this.model.otherdetail))
    },
    delthisdetail (index) {
      if (this.model.otherdetail.length > 1) {
        this.model.otherdetail.splice(index, 1)
        this.getcollection()
      }
    },
    async userfees (userinfoid, feetype) {
      this.model.t_userfees = await this.$resetpost('rs/sql/saleSingleTable', {
        data: {
          tablename: 't_userfees',
          condition: `f_userinfo_id=${userinfoid} and f_fee_type='${feetype}'`
        }
      }, {resolveMsg: null, rejectMsg: '查询客户其他费用失败!'})
    }
  },
  computed: {
    validflag () {
      console.log(this.isflag)
      console.log(this.$v.valid)
      if (this.isflag) {
        if (this.model.f_collection && this.model.f_collection != '') {
          let collection = (parseFloat(this.model.f_collection - 0)).toFixed(2)
          if (collection > 0) return !this.isflag
          else return !this.$v.valid
        } else {
          return !this.$v.valid
        }
      } else {
        return !this.$v.valid
      }
    },
    feetime () {
      return [{label: '一个月', value: '1'}, {label: '三个月', value: '3'}, {label: '六个月', value: '6'}, {
        label: '一年',
        value: '12'
      }]
    },

    authArr () {
      console.log('this.$login.r:', this.$login.r)
      console.log('this.$login.r.includes:', this.$login.r.includes('收费综合导出权限'))
      return this.$login.r ? this.$login.r : []
    },
    gettypename () {
      return this.typeNameList
    },
    gettypenumber () {
      return this.typenumberList
    }
  }
}
</script>

<style>
</style>
