<template>
  <div class="basic-main" style="height: 100%">
    <criteria-paged :model="model" :pager='false' v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:criteria>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row">
            <div class="col-sm-2 form-group">
              <label class="font_normal_body" for="startDate">开始日期:</label>
              <datepicker id="startDate" placeholder="开始日期" style="width: 60%"
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-2 form-group">
              <label class="font_normal_body" for="endDate">结束日期:</label>
              <datepicker id="endDate" placeholder="结束日期" style="width: 60%"
                          v-model="model.endDate"
                          :value.sync="model.endDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <res-select-group :show-component="$parent.$parent.resshow" :selectin="true"
                              :initres="$parent.$parent.initres" :cascade=true @re-res="$parent.$parent.getRes"
                              v-ref:sel></res-select-group>
          </div>
          <div class="span" style="float:right;">
            <button class="button_search" @click="$parent.$parent.pushAudit()" v-if="$parent.$parent.config.hasAudit">审核</button>
            <button class="button_search" @click="$parent.$parent.searchData()">查询</button>
            <report-print id='gasprice' top='3cm' left='0' width='100%' height='100%' :preview="true"></report-print>
            <report-excel id='gasprice'></report-excel>
            <div style="float: right" class="button_spacing" :class="{'button_shrink_top':$parent.$parent.criteriaShow,
                  'button_shrink_bottom':!$parent.$parent.criteriaShow}" @click="$parent.$parent.hidden()"></div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <div class="col-sm-2 form-group">
              <label class="font_normal_body">用户类型</label>
              <v-select :value.sync="$parent.$parent.f_user_type"
                        v-model="$parent.$parent.f_user_type"
                        :options='$parent.$parent.user_type' placeholder='请选择'
                        condition="f_user_type = '{}'"
                        close-on-select></v-select>
            </div>
            <!--<div class="col-sm-2 form-group">-->
            <!--<label class="font_normal_body">收费状态</label>-->
            <!--<v-select :value.sync="$parent.$parent.f_state" multiple-->
            <!--v-model="$parent.$parent.f_state"-->
            <!--:options='$parent.$parent.charge_state' placeholder='请选择'-->
            <!--condition="f_state in {}"-->
            <!--close-on-select></v-select>-->
            <!--</div>-->
          </div>
        </div>
      </criteria>
      <div partial='list' v-el:handcollect id='gasprice' style="overflow-y: scroll">
        <table class='tableprint' style="margin: 0px auto">
          <thead>
          <tr>
            <th :colspan='$parent.spans' style="font-weight: normal; text-align: left;">
              <h3 style="text-align: center">收费结账报表</h3>
            </th>
          </tr>
          <tr>
            <th :colspan='$parent.spans' style="font-weight: normal; text-align: center;">
              开始时间：{{ model.model.startDate }}&nbsp;&nbsp;&nbsp;
              结束时间：{{ model.model.endDate }}&nbsp;&nbsp;<br/>
              <!--打印时间：{{{$parent.printTime}}}-->
              打印时间：{{ $parent.printTime }}
              <!--收费员：{{// $parent.operatorname}}-->
            </th>
          </tr>
          <tr>
            <th :colspan='$parent.spans' style="font-weight: normal; text-align: center;">
              <div>
                <span style="font-weight: normal;text-align: center;margin:5px 15px" v-show="$parent.orgname">公司：{{$parent.orgname}}</span>
                <span v-show="$parent.depname"> 部门：{{$parent.depname}}</span>
                <span style="font-weight: normal;text-align: center;margin:5px 15px" v-show="$parent.operatorname">人员：{{$parent.operatorname}}</span>
              </div>
            </th>
          </tr>
          </thead>
          <tr>
            <td :colspan='$parent.spans' class="noborder">
              {{{ model.data.substring(26,model.data.length-8) }}}
            </td>
          </tr>
          <tfoot>
          <tr style="text-align: left">
            <th :colspan='Math.floor($parent.spans/3)'>财务审核：</th>
            <th :colspan='Math.floor($parent.spans/3)'>收款审核：</th>
            <th :colspan='Math.floor($parent.spans/3)'>收款员：</th>
          </tr>
          </tfoot>
        </table>
        {{{ $parent.reportStr}}}
      </div>
    </criteria-paged>
    <modal :show.sync="show" v-ref:modal small backdrop="false">
    </modal>
    <modal :show.sync="pushAuditShow" large backdrop="false" width="40%">
      <header slot="modal-header" class="modal-header" style="text-align: center">
        <h4 class="modal-title">审核推送</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <validator name='v'>
          <form class="form-horizontal select-overspread">
            <div class="form-group" :class="[$v.f_audit_person.required ? 'has-error' : '']">
              <label class="col-sm-4 font_normal_body">审核人:</label>
              <input type="text" v-show="false" v-model="$refs.f_audit_person.selectedItems"
                     v-validate:f_audit_person='{required: true }'>
              <div class="col-sm-8">
                <v-select v-model="pushAuditData.f_audit_person"
                          placeholder='请选择'
                          :value.sync="pushAuditData.f_audit_person"
                          :options='auditor'
                          :value-single="true"
                          close-on-select
                          clear-button
                          v-ref:f_audit_person>
                </v-select>
              </div>
            </div>
          </form>
        </validator>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button class="button_search" @click="auditConfirm()" :disabled="!$v.valid">提交审核</button>
        <button class="button_clear" @click="cancel()">取消</button>
      </footer>
    </modal>
    <modal :show.sync="signatureModalShow" large backdrop="false" width="50%">
      <header slot="modal-header" class="modal-header" style="text-align: center">
        <h4 class="modal-title">业务员签名</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div style="text-align:center">
          <canvas v-ref:signCanvas data-sign-canvas="true"
                  style="border:1px solid #ccc; background:#fff; width:600px; height:300px; touch-action:none;">
          </canvas>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="button_clear" @click="clearSignatureCanvas()">清除</button>
        <button type="button" class="button_search" @click="saveSignatureAndSubmit()" :disabled="signatureUploadInProgress">保存并提交</button>
        <button type="button" class="button_clear" @click="signatureModalShow=false">取消</button>
      </footer>
    </modal>
  </div>
</template>

<script>
import Vue from 'vue'
import {DataModel} from 'vue-client'
import co from 'co'

export default {
  title: '收费结账报表',
  props: ['data'],
  data () {
    return {
      printTime: this.$login.toStandardTimeString(),
      depresid: [],
      userresid: [],
      f_orgid: this.$login.f.orgid,
      f_depid: this.$login.f.depids,
      // f_operatorid: this.$login.f.id,
      operatorid: [],
      depid: [],
      orgname: '',
      depname: '',
      criteriaShow: false,
      operatorname: '',
      orgCondtionStr: '1=1',
      f_user_type: '',
      f_state: ['有效'],
      auditor: [],
      model: new DataModel('api/af-revenue/report/getmoneyall', {
        startDate: 'this.model.startDate', endDate: 'this.model.endDate',
        f_orgid: 'this.model.f_orgid'
      }),
      reportStr: null,
      resshow: ['company', 'department', 'operator'],
      spans: 0,
      initres: {
        org: [this.$login.f.orgid],
        dep: [],
        user: []
      },
      pushAuditData: {},
      pushAuditShow: false,
      signatureModalShow: false,
      signatureData: '',
      signatureDrawn: false,
      signatureUploadInProgress: false,
      signing: false,
      signLastX: 0,
      signLastY: 0,
      signDPR: 1,
      signCanvasContext: null,
      signatureCanvas: null,
      config: {
        hasAudit: false
      }
    }
  },
  async ready () {
    this.$refs.paged.$refs.criteria.model.startDate = this.$login.toStandardDateString() + ' 00:00:00'
    this.$refs.paged.$refs.criteria.model.endDate = this.$login.toStandardDateString() + ' 23:59:59'
    this.getAuditor()
    await this.$getConfig(this, 'reportAuditConfig')
    console.log('this.config.hasAudit', this.config.hasAudit)
    console.log('config对象结构:', JSON.stringify(this.config))
  },
  methods: {
    auditConfirm () {
      // If no signature yet, require the reviewer to sign first
      if (!this.pushAuditData.f_audit_person) {
        this.$showMessage('请选择审核人')
        return
      }
      if (!this.pushAuditData.signature) {
        this.signatureModalShow = true
        return
      }

      const param = {
        f_type: '收费结账报表',
        f_requestparam: this.model.data,
        f_audit_person: this.pushAuditData.f_audit_person,
        f_signature: this.pushAuditData.signature,
        f_otherparam: this.pushAuditData,
        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_describe: `${this.$login.f.name}发起收费结账报表审核操作`,
        f_is_report_audit: '是'
      }
      this.$resetpost('api/af-revenue/logic/saveReportAuditLogic', param, {
        warnMsg: `确定要对当前查询的报表数据进行推送审核吗？`,
        resolveMsg: `提交审核完成！！`,
        rejectMsg: `提交审核失败！！请重试！！`
      }).then((res) => {
        this.pushAuditShow = false
        this.pushAuditData.f_audit_person = ''
        this.pushAuditData.signature = ''
      })
    },
    initSignCanvas () {
      this.$nextTick(() => {
        let canvas = this.$refs.signCanvas
        if (!canvas) {
          canvas = this.$el.querySelector('canvas[data-sign-canvas]') || document.querySelector('canvas[data-sign-canvas]')

        }
        const desiredW = 600
        const desiredH = 300
        canvas.width = desiredW
        canvas.height = desiredH
        canvas.style.width = desiredW + 'px'
        canvas.style.height = desiredH + 'px'
        const ctx = canvas.getContext('2d')
        ctx.setTransform(1, 0, 0, 1, 0, 0)
        ctx.fillStyle = '#fff'
        ctx.fillRect(0, 0, desiredW, desiredH)
        ctx.strokeStyle = '#000'
        ctx.lineWidth = 2
        ctx.lineCap = 'round'
        ctx.lineJoin = 'round'
        this.signCanvasContext = ctx
        this.signing = false
        this.signatureDrawn = false
        this.destroySignCanvasListeners()
        const getPoint = (event) => {
          const rect = canvas.getBoundingClientRect()
          let clientX = event.clientX
          let clientY = event.clientY
          if (event.touches && event.touches.length) {
            clientX = event.touches[0].clientX
            clientY = event.touches[0].clientY
          } else if (event.changedTouches && event.changedTouches.length) {
            clientX = event.changedTouches[0].clientX
            clientY = event.changedTouches[0].clientY
          }
          if (clientX == null || clientY == null) return null
          const x = (clientX - rect.left) * (canvas.width / rect.width)
          const y = (clientY - rect.top) * (canvas.height / rect.height)
          return { x, y }
        }

        const onStart = (event) => {
          event.preventDefault()
          const point = getPoint(event)
          if (!point) return
          this.signing = true
          this.signatureDrawn = true
          this.signLastX = point.x
          this.signLastY = point.y
        }
        const onMove = (event) => {
          if (!this.signing) return
          event.preventDefault()
          const point = getPoint(event)
          if (!point) return
          const ctx2 = this.signCanvasContext
          ctx2.beginPath()
          ctx2.moveTo(this.signLastX, this.signLastY)
          ctx2.lineTo(point.x, point.y)
          ctx2.stroke()
          this.signLastX = point.x
          this.signLastY = point.y
        }
        const onEnd = (event) => {
          if (this.signing) {
            event.preventDefault()
          }
          this.signing = false
        }
        canvas.addEventListener('mousedown', onStart)
        canvas.addEventListener('mousemove', onMove)
        canvas.addEventListener('mouseup', onEnd)
        canvas.addEventListener('mouseleave', onEnd)
        canvas.addEventListener('touchstart', onStart, {passive:false})
        canvas.addEventListener('touchmove', onMove, {passive:false})
        canvas.addEventListener('touchend', onEnd)
        canvas.addEventListener('touchcancel', onEnd)

        this._signCanvasListeners = { canvas, onStart, onMove, onEnd }
        this.signatureCanvas = canvas
      })
    },
    destroySignCanvasListeners () {
      if (!this._signCanvasListeners) return
      const { canvas, onStart, onMove, onEnd } = this._signCanvasListeners
      canvas.removeEventListener('mousedown', onStart)
      canvas.removeEventListener('mousemove', onMove)
      canvas.removeEventListener('mouseup', onEnd)
      canvas.removeEventListener('mouseleave', onEnd)
      canvas.removeEventListener('touchstart', onStart)
      canvas.removeEventListener('touchmove', onMove)
      canvas.removeEventListener('touchend', onEnd)
      canvas.removeEventListener('touchcancel', onEnd)
      this._signCanvasListeners = null
      this.signatureCanvas = null
    },
    getSignCanvasElement () {
      return this.$refs.signCanvas || this.signatureCanvas || this.$el.querySelector('canvas[data-sign-canvas]') || document.querySelector('canvas[data-sign-canvas]')
    },
    getSignPoint (event) {
      const canvas = this.getSignCanvasElement()
      if (!canvas) return null
      const rect = canvas.getBoundingClientRect()
      let clientX = event.clientX
      let clientY = event.clientY

      if (event.touches && event.touches.length) {
        clientX = event.touches[0].clientX
        clientY = event.touches[0].clientY
      } else if (event.changedTouches && event.changedTouches.length) {
        clientX = event.changedTouches[0].clientX
        clientY = event.changedTouches[0].clientY
      }

      if (clientX == null || clientY == null) return null

      // Use offset within canvas bounding box
      const x = (clientX - rect.left) * (canvas.width / rect.width)
      const y = (clientY - rect.top) * (canvas.height / rect.height)
      return { x, y }
    },
    signStart (event) {
      // legacy support: keep method but not used by native listeners
      if (!this.signCanvasContext) return
      const point = this.getSignPoint(event)
      if (!point) return
      this.signing = true
      this.signatureDrawn = true
      this.signLastX = point.x
      this.signLastY = point.y
    },
    signMove (event) {
      if (!this.signing || !this.signCanvasContext) return
      const point = this.getSignPoint(event)
      if (!point) return
      const ctx = this.signCanvasContext
      ctx.beginPath()
      ctx.moveTo(this.signLastX, this.signLastY)
      ctx.lineTo(point.x, point.y)
      ctx.stroke()
      this.signLastX = point.x
      this.signLastY = point.y
    },
    signEnd () {
      this.signing = false
    },
    clearSignatureCanvas () {
      const canvas = this.getSignCanvasElement()
      const ctx = this.signCanvasContext || (canvas ? canvas.getContext('2d') : null)
      if (!canvas || !ctx) {
        return
      }

      const desiredW = 600
      const desiredH = 300
      ctx.setTransform(1, 0, 0, 1, 0, 0)
      ctx.clearRect(0, 0, desiredW, desiredH)
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, desiredW, desiredH)
      this.signatureDrawn = false
      this.pushAuditData.signature = ''
    },
    getUploadPathFromResponse (res) {
      return res && (res.id)
    },
    canvasToBlob (canvas) {
      return new Promise((resolve, reject) => {
        if (canvas.toBlob) {
          canvas.toBlob((blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('canvas toBlob returned null'))
            }
          }, 'image/png')
        } else {
          try {
            const dataURL = canvas.toDataURL('image/png')
            const byteString = atob(dataURL.split(',')[1])
            const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0]
            const ab = new ArrayBuffer(byteString.length)
            const ia = new Uint8Array(ab)
            for (let i = 0; i < byteString.length; i++) {
              ia[i] = byteString.charCodeAt(i)
            }
            resolve(new Blob([ab], { type: mimeString }))
          } catch (err) {
            reject(err)
          }
        }
      })
    },
    uploadSignatureFile () {
      return new Promise(async (resolve, reject) => {
        const canvas = this.getSignCanvasElement()
        if (!canvas) {
          reject(new Error('签名画布未找到'))
          return
        }
        let blob
        try {
          blob = await this.canvasToBlob(canvas)
        } catch (err) {
          reject(err)
          return
        }

        const form = new FormData()
        form.append('file', blob, 'signature.png')

        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'api/af-revenue/file/uploadFile', true)
        if (Vue.$login && Vue.$login.jwt) {
          xhr.setRequestHeader('Authorization', 'Bearer ' + Vue.$login.jwtNew)
          xhr.setRequestHeader('Token', Vue.$login.jwt)
        }

        xhr.onreadystatechange = function () {
          if (xhr.readyState < 4) return
          if (xhr.status < 400) {
            try {
              const res = JSON.parse(xhr.responseText)
              const uploadPath = this.getUploadPathFromResponse(res)
              if (!uploadPath) {
                reject(new Error('上传成功但未返回有效路径'))
                return
              }
              resolve(uploadPath)
            } catch (err) {
              reject(err)
            }
          } else {
            let err
            try {
              err = JSON.parse(xhr.responseText)
            } catch (parseErr) {
              err = new Error(xhr.statusText || '签名上传失败')
            }
            reject(err)
          }
        }.bind(this)

        xhr.onerror = function () {
          reject(new Error('签名文件上传网络错误'))
        }

        xhr.send(form)
      })
    },
    async saveSignatureAndSubmit () {
      if (!this.signatureDrawn) {
        if (this.$showMessage) this.$showMessage('请先签名')
        return
      }

      const canvas = this.getSignCanvasElement()
      if (!canvas) {
        if (this.$showMessage) this.$showMessage('签名画布未找到，请重新打开签名弹窗')
        return
      }

      if (this.signatureUploadInProgress) {
        return
      }
      this.signatureUploadInProgress = true
      try {
        const uploadPath = await this.uploadSignatureFile()
        this.pushAuditData.signature = uploadPath
        this.signatureModalShow = false
        this.auditConfirm()
      } catch (err) {
        if (this.$showMessage) this.$showMessage('签名上传失败，请重试')
      } finally {
        this.signatureUploadInProgress = false
      }
    },
    async getAuditor () {
      await this.$MagGetSaleParam.initinputtor()
      console.log('查询到的人员：', await this.$MagGetSaleParam.initinputtor())
      this.auditor = this.$MagGetSaleParam.getAudit(this.$login.f.orgid)
      this.auditor.push({label: '管理员', value: '管理员'})
      console.log('查询到的审核员：', this.auditor)
    },
    cancel () {
      this.pushAuditShow = false
      this.pushAuditData.signature = ''
    },
    pushAudit () {
      if (this.model.data === null || this.model.data === ' ') {
        this.$showMessage('请先查询报表再发起审核')
        return
      }
      this.pushAuditShow = true
    },
    searchData () {
      this.$refs.paged.$refs.criteria.search()
    },
    selfSearch (args) {
      this.printTime = this.$login.toStandardTimeString()
      let orgcondition = '1=1'
      let orgstr = this.orgCondtionStr
      orgcondition = orgcondition + orgstr
      if (this.f_user_type && this.f_user_type[0]) {
        orgcondition += ` and f_user_type = '${this.f_user_type}  '`
      }
      this.$refs.paged.$refs.criteria.model.f_orgid = orgcondition
      this.$refs.paged.search(args)
      this.pushAuditData.startDate = this.model.params.startDate
      this.pushAuditData.endDate = this.model.params.endDate
      this.pushAuditData.condition = orgcondition.replace(/'/g, "''")
    },

    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    getRes (condition, obj) {
      this.orgCondtionStr = condition
      this.orgname = obj.orgnames[0]
      this.depname = obj.depnames[0]
      console.log(obj, '========')
      this.operatorname = obj.operatornames[0]
    },
    getdep (obj, val) {
      this.depname = val[0]
      this.userresid = obj
      this.f_depid = obj
    },
    getuser (obj, val) {
      this.operatorname = val[0]
      this.f_operatorid = obj
    }
  },
  watch: {
    'model.data' (val) {
      let len = 0
      let a = val.split('</tr>')
      for (let i = 0; i < a.length; i++) {
        if (a[i].split('</td>').length - 1 > len) {
          len = a[i].split('</td>').length - 1
        }
      }
      this.spans = len
    }
    ,
    signatureModalShow (val) {
      console.log('[ManageBusSummary] signatureModalShow watcher', val)
      if (val) {
        this.initSignCanvas()
      } else {
        this.destroySignCanvasListeners()
      }
    }
  },
  computed: {
    charge_state () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('收费状态')]
    },
    user_type () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')]
    },
    showAudit () {
      return this.config.hasAudit
    }
  }
}
</script>
<style scoped>
.noborder {
  border: none;
}
</style>
