<template>
  <div class="auto basic-main" style="height:95%">
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row">
            <div class="form-group col-sm-2" >
              <label class="font_normal_body">组织机构</label>
              <res-select :initresid='$parent.$parent.curorgid'
                          @res-select="$parent.$parent.getorg"
                          class="select select_list"
                          restype='organization'
                          style="width: 60%">
              </res-select>
            </div>
          <div  class="form-group col-sm-2">
            <label class="font_normal_body">客户编号</label>
            <input  type="text" class="form-control" v-model="model.f_userinfo_code" style="width:60%"
                    condition="f_userinfo_code = '{}' "  placeholder="客户编号"
            >
          </div>
          <div  class="form-group col-sm-2">
            <label class="font_normal_body">用户姓名</label>
            <input  type="text" class="form-control" v-model="model.f_user_name" style="width:60%"
                    condition="f_user_name = '{}'" placeholder="用户姓名"
            >
          </div>
          <div  class="form-group col-sm-2" >
            <label class="font_normal_body">业务类型</label>
            <v-select id="f_charge_type"
                      style="width:60%"
                      v-model="model.f_type"
                      placeholder='业务类型'
                      condition="f_type ='{}'"
                      :value.sync="model.f_type"
                      :options='$parent.$parent.chargetypes'
                      close-on-select clear-button>
            </v-select>
          </div>

          <div style="float: right">
            <button class="btn button_search"  @click="search()">查 询</button>
            <button class="btn btn-success"  @click="$parent.$parent.open_eTicket()">开票</button>
            <button class="btn button_search" style="margin-left: 10px" @click="$parent.$parent.invoiceLogin('0')">登录 </button>
            <button class="btn button_search" @click="$parent.$parent.invoiceAuthShow=true">认证</button>
            <div
              :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
              @click="$parent.$parent.criteriaShow=!$parent.$parent.criteriaShow"
              class="button_spacing"
              style="float: right"></div>
            </div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <div class="form-group col-sm-2">
              <label class="font_normal_body">开票时间</label>
              <datepicker id="startDate" placeholder="开始时间"
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          style="width: 60%"
                          condition="f_operate_date >='{}'"
                          :format="'yyyy-MM-dd 00:00:00'"
              >
              </datepicker>
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
              <datepicker id="endDate" placeholder="结束时间"
                          style="width: 60%"
                          v-model="model.endDate"
                          :value.sync="model.endDate"
                          condition="f_operate_date <='{}'"
                          :format="'yyyy-MM-dd 23:59:59'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div  class="form-group col-sm-2">
              <label class="font_normal_body">是否开票</label>
              <v-select id="f_bill_null"
                        style="width:60%"
                        v-model="model.f_bill_null"
                        placeholder='是否开票'
                        condition="f_bill_null  in {}"
                        :value.sync="model.f_bill_null"
                        :options='$parent.$parent.billNull'
                        close-on-select
              >
              </v-select>
            </div>
          </div>
        </div>
      </criteria>
      <data-grid  :model="model" partial='list'  class="list_area table_sy" v-ref:grid>
        <template partial='head'>
          <tr>
            <th>
              <input type="checkbox"  @click="$parent.$parent.$parent.addOrRemove($parent.$parent.$parent.selectAll)" :checked="$parent.$parent.$parent.selectAll">
            </th>
            <th>序号</th>
            <th>客户编号</th>
            <th>用户姓名</th>
            <th>用户地址</th>
            <th>气量</th>
            <th>应交金额</th>
            <th>实收金额</th>
            <th>收费类型</th>
            <th>是否开票</th>
            <th>收费时间</th>
          </tr>
        </template>
        <template partial='body'  >
          <td style="text-align:center">
            <input type="checkbox" v-model="$parent.$parent.$parent.selecteds" :value="row">
          </td>
          <td style="text-align:center">{{$index+1}}</td>
          <td style="text-align:center">{{row.f_userinfo_code}}</td>
          <td style="text-align:center">{{row.f_user_name}}</td>
          <td style="text-align:center">{{row.f_address}}</td>
          <td style="text-align:center">{{row.f_pregas}}</td>
          <td style="text-align:center">{{row.f_preamount}}</td>
          <td style="text-align:center">{{row.f_collection}}</td>
          <td style="text-align:center">{{row.f_type}}</td>
          <td style="text-align:center">{{row.f_bill_null}}</td>
          <td style="text-align:center">{{row.f_operate_date}}</td>
        </template>
        <template partial='foot'></template>
      </data-grid>
    </criteria-paged>
  </div>

  <modal v-if="inputSmsCodeShow" :show.sync="inputSmsCodeShow" large="large" backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h3 style="color:black" class="modal-title">开票登录</h3>
    </header>
    <article slot="modal-body" class="modal-body qrcode-modal">
      <div style="height: 3.6rem; display: flex; justify-content: center;">
        <div class="form-group col-sm-6">
          <input  type="text" class="form-control" v-model="smsCode" placeholder="请输入验证码" />
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success"  @click="invoiceLogin('1')" >确定</button>
      <button type="button" class="btn btn-default"  @click='cancelAuth' >取消</button>
    </footer>
  </modal>
  <modal v-if="invoiceAuthShow" :show.sync="invoiceAuthShow" large="large" backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h3 style="color:black" class="modal-title">开票认证</h3>
    </header>
    <article slot="modal-body" class="modal-body qrcode-modal">
      <div>
        <button type="button" class="btn btn-default" :class="{ 'btn-success': authType === '0' }"  @click="invoiceAuth('0')" >蓝票认证</button>
        <button type="button" class="btn btn-default" :class="{ 'btn-success': authType === '1' }"  @click="invoiceAuth('1')" >红票认证</button>
      </div>
      <div>
        <div id="qrcode" class="qrcode"></div>
        <p v-if="qrCodeValidityPeriod > 0 && qrCodeValidityPeriod <= 300" style="margin-top: 16px;">二维码有效期剩余: {{ qrCodeValidityPeriod }} s</p>
        <p v-if="qrCodeValidityPeriod === 0" style="color: red; font-weight: bold; margin-top: 16px;">二维码已过期，请点击上方对应按钮重新获取</p>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button v-show="invoiceAuthQrCodeShow" type="button" class="btn btn-success"  @click="invoiceAuth(authType, '1')" >确定</button>
      <button type="button" class="btn btn-default" @click='cancelAuth' >取消</button>
    </footer>
  </modal>

  <eticket-modal :show="eticket_msg" :row="row" @closemodalshow="eticket_msg = false"  @confirm="confirm"></eticket-modal>
  <!--<eticket-print-async  :show="eticket_show" @toggle="eticket_toggle"  v-ref:asynceticket></eticket-print-async>-->
  <ticket-print :show="eticket_show" @toggle="eticket_toggle" v-ref:eticketbill></ticket-print>
</template>

<script>
  /**
   *发票冲红管理
   */
  import {HttpResetClass, PagedList} from 'vue-client'
  import QRCode from 'qrcodejs2'
  export default {
    title: '自定义开票',
    data () {
      return {
        curorgid: [this.$login.f.orgid],
        f_orgid: '',
        criteriaShow:false,
        disabled:false,
        model: new PagedList('rs/sql/openSellelent', 50, {},),
        selecteds: [],
        eticket_show:false,
        eticket_msg: false,
        invoice_show_gas: '否',
        billNull:[{label:'否',value:'否'},{label:'是',value:'是'}],
        show_gas: [{label: '是', value: '是'}, {label: '否', value: '否'}],
        row: {},
        mid: [{label: '全部', value: ''}, {label: '是', value: ' > 0 '}, {label: '否', value: ' is null'}],
        f_operator: '',
        smsCode: '',
        inputSmsCodeShow: false,
        invoiceAuthShow: false,
        invoiceAuthQrCodeShow: false,
        qrCodeValidityPeriod: -1,
        rzid: '',
        authType: '',
        charge_type: ''
      }
    },
    ready () {
      this.$refs.paged.$refs.cri.model.f_bill_null=['否']
      this.$refs.paged.$refs.cri.model.startDate = this.$login.toStandardDateString() + ' 00:00:00'
      this.$refs.paged.$refs.cri.model.endDate = this.$login.toStandardDateString() + ' 23:59:59'
    },
    methods: {
      async open_eTicket () {
        if(this.selecteds.length>1){
          this.$showAlert('选中条数大于一条，请重新修改！！', 'warning', 2000)
          return
        }
        let HttpReset = new HttpResetClass()
        let row = await HttpReset.load('POST', 'rs/sql/sale_getUser', {
          data: {
            orderitem: 'f_userinfo_code',
            condition: `i.f_userinfo_id = '${this.selecteds.map(item => item.f_userinfo_id).toString()}'`
          }
        }, {resolveMsg: null, rejectMsg: '获取地址失败!'})
        this.row = row.data[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
        }
        this.eticket_msg = true
      },
      async invoiceLogin (loginType) {
        this.$showAlert('请求数据中,请稍后...', 'info')
        console.log('>>> 开票登类型：' + (loginType === '0' ? '开票登录' : '确认登录'))
        let f_operator = this.$login.f.name
        const loginParams = {
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          f_operator: f_operator,
          loginState: loginType
        }
        // 类型是0则登录，1则确认登录，确认登录需要输入验证码
        if (loginType === '1') {
          loginParams.smsCode = this.smsCode
        }

        let HttpReset = new HttpResetClass()
        let res = await HttpReset.load('POST', 'invoice/logic/loginSys', loginParams, {resolveMsg: null, rejectMsg: '开票登录失败!'})
        let loginRes = res.data.data
        this.$closeAlert()
        // TODO 测试数据
        // let loginRes = {
        //   msg: '操作成功！',
        //   code: '1000',
        //   data: {
        //     mobile: '159****8771',
        //     status: 0
        //   }
        // }
        console.log('>>> 看看是啥' + JSON.stringify(loginRes))
        if (loginRes.code === '1000' || loginRes.code === '0000') {
          this.$showAlert(loginType === '0' ? '短信验证码发送成功' : '确认登录成功', 'success', 1000)
          console.log('>>> 登录模式：' + loginType + '，登录状态：' + loginRes.data.data.status)
          this.inputSmsCodeShow = loginType === '0' && loginRes.data && loginRes.data.data.status === 1
        } else {
          this.$showAlert(loginRes.msg || '登录失败', 'danger', 3000)
        }
      },
      async invoiceAuth (authType, authState = '0') {
        console.log('>>> 认证票据类型：' + (authType === '0' ? '蓝票' : '红票'))
        console.log('>>> 认证操作类型：' + (authState === '0' ? '请求二维码 ' : '确认认证'))
        this.authType = authType
        let f_operator = this.$login.f.name
        const gerQrCodeParams = {
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          authState: authState,
          czlx: authType,
          f_operator: f_operator
        }
        if (authState === '1') {
          gerQrCodeParams.rzid = this.rzid
        }
        this.$showAlert('正在请求数据，请稍后...', 'info')
        let HttpReset = new HttpResetClass()
        let res = await HttpReset.load('POST', 'invoice/logic/authSys', gerQrCodeParams, {resolveMsg: null, rejectMsg: '获取二维码失败!'})
        let authRes = res.data.data
        this.$closeAlert()
        // TODO 测试数据
        // authRes = {
        //   msg: '操作成功！',
        //   code: '0000',
        //   data: {
        //     rzid: 'c931b2bc421147938824d30885a4391e',
        //     ewm: 'qrcode_id=/RA/SCohpTf/DzPosp9R3rLrhuniNZmWbj+/xot9h4AFAdAvmDp7i7Yobk7zzkNM&areaPrefix=5200&interfaceCode=0004',
        //     nsrsbh: '91520324666984050J'
        //   }
        // }
        if (authRes.code === '0000') {
          // 如果是登录
          if (authState === '0') {
            // 将返回结果转换成二维码
            this.rzid = authRes.data.rzid
            this.creatQrCode(authRes.data.ewm, authType === '0' ? 'b' : 'r')
            this.invoiceAuthQrCodeShow = true
            clearInterval(this.timer)
            this.qrCodeValidityPeriod = 300
            this.timer = setInterval(this.countDown, 1000)
          } else {
            authState = authRes.data.slzt
            this.$showAlert(authState === '2' ? '认证成功' : authState === '1' ? '未扫码' : authState === '3' ? '二维码已过期' : '认证失败', authState === '2' ? 'success' : 'danger', 6000)
            if (authState === '2') {
              this.cancelAuth()
            }
          }
        } else {
          this.$showAlert(authRes.msg || '操作失败', 'danger', 3000)
        }
      },
      // 生成二维码
      creatQrCode (text) {
        const qrCodeDOM = document.querySelector('#qrcode')
        console.log('>>> HTML Element：', qrCodeDOM)
        console.log('>>> 二维码内容：', text)
        while (qrCodeDOM.firstChild) {
          qrCodeDOM.removeChild(qrCodeDOM.firstChild)
        }
        console.log('>>> 删掉子元素后：', qrCodeDOM)
        const qrCode = new QRCode(qrCodeDOM, {
          text: text,
          width: 200,
          height: 200,
          colorDark: '#000000',
          colorLight: '#ffffff'
        })
        // 根据条件更改类名
        if (this.authType === '0') {
          qrCodeDOM.classList.remove('qrcode_r')
          qrCodeDOM.classList.add('qrcode_b')
        } else {
          qrCodeDOM.classList.remove('qrcode_b')
          qrCodeDOM.classList.add('qrcode_r')
        }
      },
      cancelAuth () {
        clearInterval(this.timer)
        this.qrCodeValidityPeriod = -1
        this.smsCode = ''
        this.authType = ''
        this.invoiceAuthShow = false
        this.inputSmsCodeShow = false
      },
      countDown () {
        if (this.qrCodeValidityPeriod > 0) {
          this.qrCodeValidityPeriod--
          this.seconds = this.qrCodeValidityPeriod
        } else {
          clearInterval(this.timer)
        }
      },
      confirm () {
        this.eticket_msg = false
        this.eticket_show = true
        this.$refs.eticketbill.openETicket(this.selecteds[0].id.toString(), this.row, this.selecteds[0].f_type)
      },
      eticket_toggle () {
        this.eticket_show = false
        this.search()
      },
      getorg (val) {
        this.f_orgid = this.$login.convertToIn(val)
        this.$parent.f_orgid = this.f_orgid
      },
      async selfSearch (args) {
        this.selecteds=[]
        if (!this.f_orgid) {
          this.getorg([this.$login.f.orgid])
        }
        if (this.f_orgid) {
          args.condition = `f_orgid in ${this.f_orgid} and ${args.condition}`
        }
        await this.model.search(args.condition, this.model)
        console.log("res",this.model)
      },
      search () {
        this.$refs.paged.$refs.cri.search()
      },
      addOrRemove (is) {
        this.selecteds = []
        if (!is) { // 添加本页所有数据到ids中
          this.model.rows.forEach((row) => {
            this.selecteds.push(row)
          })
          this.selectAll = true
        } else { // 从ids中取消所有的数据
          this.selecteds = []
          this.selectAll = false
        }
        console.log("selectdde",this.selecteds)
      }
    },
    computed: {
      chargetypes(){
        return [{label: '全部', value: ''},...this.$appdata.getParam('收费类型')]
      },
    },
    watch:{
      selecteds(){
        console.log("框框的长度",this.selecteds.length)
      }
    },
    events:{
      'closeModalShow'(){
        this.eticket_msg= !this.eticket_msg
      },
    }
  }
</script>
<style>
  .qrcode-modal {
    text-align: center;

    #qrcode {
      display: inline-block;
      text-align: center;
      padding: 3px;
    }
    .qrcode_r {
      border: 6px solid #e74c3c;
      box-shadow: 6px 6px 3px 3px #dedede;
    }
    .qrcode_b {
      border: 6px solid #1e90ff;
      box-shadow: 6px 6px 6px 1px #dedede;
    }
    button {
      margin: 0 16px 26px;
    }
  }
</style>
