<template>
  <!-- 施工通知单 -->
  <div class="flex-row">
    <div class="basic-main">
      <criteria-paged :model="model" v-ref:cp>
        <criteria partial='criteria' @condition-changed='$parent.searchCondition' v-ref:cri>
          <div class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">
              <div class="form-group col-sm-3">
                <label class="font_normal_body"><strong>工程编号：</strong></label>
                <input type="text" style="width: 60%" class="input_search" placeholder='工程编号' v-model="model.f_apply_num"
                       v-on:keyup.enter="$parent.$parent.search()"
                       condition="f_apply_num like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body"><strong>用户名称：</strong></label>
                <input type="text" style="width: 60%" class="input_search" placeholder='用户名称' v-model="model.f_user_name"
                       v-on:keyup.enter="$parent.$parent.search()"
                       condition="f_user_name like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body"><strong>电&emsp;&emsp;话：</strong></label>
                <input type="text" style="width: 60%" class="input_search" placeholder='电话' v-model="model.f_phone"
                       v-on:keyup.enter="$parent.$parent.search()"
                       condition="f_phone = '{}'">
              </div>
              <div class="form-group col-sm-3 button-range">
                <button class="button_export button_spacing" @click="$parent.$parent.batchPrint()">批量打印</button>
                <button class="button_search button_spacing" @click="$parent.$parent.search()" v-el:cx>查询</button>
                <button class="button_clear button_spacing"  @click="$parent.$parent.clear()">清空</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-3">
                <label class="font_normal_body"><strong>报建类型：</strong></label>
                <v-select
                  v-model="model.f_apply_type"
                  placeholder='报建类型'
                  condition="f_apply_type = '{}'"
                  :value.sync="model.f_apply_type"
                  :options='$parent.$parent.applytype'
                  class="select select_list"
                  :value-single="true"
                  close-on-select ></v-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body"><strong>地&emsp;&emsp;址：</strong></label>
                <input type="text" style="width: 60%" class="input_search" placeholder='地址' v-model="model.f_address"
                       v-on:keyup.enter="$parent.$parent.search()"
                       condition="f_address like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body"><strong>安装单位：</strong></label>
                <input type="text" style="width: 60%" class="input_search" placeholder='安装单位' v-model="model.f_construction_name"
                       v-on:keyup.enter="$parent.$parent.search()"
                       condition="f_construction_name like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label  for="startDate" class="font_normal_body"><strong>开始时间：</strong></label>
                <datepicker id="startDate" placeholder="开始日期"
                            style="width: 60%!important;"
                            v-model="model.startDate"
                            :value.sync="model.startDate"
                            :format="'yyyy-MM-dd 00:00:00'"
                            :show-reset-button="true"
                            condition="a.f_release_date >= '{}'">
                </datepicker>
              </div>
              <div class="form-group col-sm-3">
                <label for="endDate" class="font_normal_body"><strong>结束时间：</strong></label>
                <datepicker id="endDate" placeholder="结束日期"
                            style="width: 60%!important;"
                            v-model="model.endDate"
                            :value.sync="model.endDate"
                            :format="'yyyy-MM-dd 23:59:59'"
                            :show-reset-button="true"
                            condition="a.f_release_date <= '{}'">
                </datepicker>
              </div>
            </div>
          </div>
        </criteria>
        <data-grid :model="model" optional partial='list' v-ref:grid style="overflow: auto" class="list_area table_sy">
          <template partial='head'>
            <tr>
              <th>序号</th>
              <th>工程编号</th>
              <th>用户名称</th>
              <th>电话</th>
              <th>地址</th>
              <th>安装单位</th>
              <th>派单时间</th>
            </tr>
          </template>
          <template partial='body'>
            <tr >
              <td style="text-align: center;">
                <nobr><font>{{$index+1}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_apply_num}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_user_name}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_phone}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_address}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_construction_name}}</font></nobr>
              </td>
              <td style="text-align: center;" @click="$parent.$parent.$parent.click(row)">
                <nobr><font>{{row.f_release_date}}</font></nobr>
              </td>
            </tr>
          </template>
        </data-grid>
      </criteria-paged>

      <modal :show.sync="showPrint" title="打印预览" v-ref:modal :backdrop="false">
        <header slot="modal-header" class="modal-header">
          <button type="button" class="close" @click="colseModal()"><span>&times;</span></button>
          <h4 class="modal-title">打印预览</h4>
        </header>
        <article slot="modal-body" class="modal-body" v-show="printShow">
          <print-build-order :selectdata="selectdata" :type="type" v-ref:print></print-build-order>
        </article>
        <article slot="modal-body" class="modal-body" v-show="printShow1">
          <print-gai-order :selectdata="selectdata" :type="type" v-ref:print1></print-gai-order>
        </article>
        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-primary" @click="print()">打印</button>
        </footer>
      </modal>

      <modal :show.sync="showProgress" v-ref:progress :backdrop="false">
        <header slot="modal-header" class="modal-header">
          <button type="button" class="close" @click="colseModal()"><span>&times;</span></button>
          <h4 class="modal-title">发送打印指令中,请耐心等待...</h4>
        </header>
        <article slot="modal-body" class="modal-body">
          <div class="progress" style="margin: 20px">
            <div class="progress-bar progress-bar-success progress-bar-striped active" :style="{width: percent}">
              {{ percent }}
            </div>
          </div>
        </article>
        <footer slot="modal-footer" class="modal-footer">
        </footer>
      </modal>
    </div>
  </div>
</template>

<script>
import {PagedList} from 'vue-client'
import {HttpResetClass} from 'vue-client'
export default {
  title: '施工通知单',
  data () {
    return {
      model: new PagedList('rs/sql/buildOrderList', 30, null),
      criteriaShow: false,
      selectdata: null,
      showPrint: false,
      showProgress: false,
      applytype: [{label: '全部', value: ''}, ...this.$appdata.getParam('报建类型')?this.$appdata.getParam('报建类型'):[]],
      percent: 0,
      userfile: '',
      device: '',
      f_construct_operator: '',
      f_build_operator: '',
      type: 'PREVIEW',
      printShow: false,
      printShow1: false
    }
  },
  ready () {
    // 调用查询
    this.search()
  },
  methods: {
    async batchPrint () {
      this.type = 'PRINT'
      let selectPrint = this.$refs.cp.$refs.grid.getRowData()
      let res = await this.getUserfiles(selectPrint)
      for (let i = 0; i < selectPrint.length; i++) {
        if (selectPrint[i].f_apply_type !== '改线业务'){
          for (let j = 0; j < res.length; j++) {
            if (selectPrint[i].f_process_id === res[j].f_process_id){
              selectPrint[i].userfile = res[j].f_meter
              selectPrint[i].device = res[j].f_devices
            }
          }
        }
      }
      setTimeout( async () => {
        if (selectPrint.length > 0) {
          let res = await this.$showMessage(`当前数据条数: ${selectPrint.length}, 条数过大时打印时间可能会过长, 是否确认打印?`)
          if (res == 'confirm') {
            this.showProgress = true
            for (let i = 0; i < selectPrint.length; i++) {
              setTimeout( async () => {
                this.selectdata = selectPrint[i]
                console.log("当前数据", selectPrint[i])
                if (selectPrint[i].f_due_money >= 0) {
                  selectPrint[i].f_amount_words = this.smalltoBIG(selectPrint[i].f_due_money)
                }
                this.print(selectPrint[i])
                this.percent = this.getPercent(i, selectPrint.length)
                this.selectdata = null
              },3000)
            }
            this.showProgress = false
            this.percent = 0
            this.$refs.cp.$refs.grid.selectInit()
          }
        } else {
          this.$showMessage('请选择要打印的单子')
        }
      }, 600)
    },
    getPercent (num, total){
      num = parseFloat(num);
      total = parseFloat(total);
      if (isNaN(num) || isNaN(total)) {
        return "-";
      }
      return total <= 0? "0%" : Math.round((num / total) * 10000) / 100.0 + "%";
    },
    print (index) {
      console.log("当前数据",index)
      if (index !== null && index !== '' && index !== undefined){
        this.selectdata = index
      }
      if (this.getShowPrint(this.selectdata.f_apply_type)){
        this.$refs.print.print(index)
      }else {
        this.$refs.print1.print(index)
      }
    },
    colseModal () {
      this.showPrint = false
      this.showProgress = false
      this.printShow = false
      this.printShow1 = false
      this.selectdata = null
    },
    getShowPrint (index) {
      console.log('2222',index)
      if (index !== '改线业务'){
        this.printShow = true
        return true
      }
      this.printShow1 = true
      return false
    },
    async click (row) {
      this.type = 'PREVIEW'
      if (row.f_apply_type !== '改线业务') {
        await this.getUserfile(row.f_process_id)
      }
      this.getShowPrint(row.f_apply_type)
      setTimeout(() => {
        row.userfile = this.userfile
        row.device = this.device
        this.selectdata = row
        if (this.selectdata.f_due_money >= 0 ) {
          this.selectdata.f_amount_words = this.smalltoBIG(this.selectdata.f_due_money)
        }
        this.showPrint = true
        }, 600)
    },
    async getMeter(f_process_id) {
      let data = {
        f_process_id: f_process_id
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `rs/sql/getMeters`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      let userfile = ''
      for (let i = 0; i < res.data.length ; i++){
        console.log("表具信77息",res.data[i].f_meter_type)
        if (res.data[i].f_meter_type === null){
          res.data[i].f_meter_type = '表具'
        }
        userfile = userfile + res.data[i].f_meter_count + '块' + res.data[i].f_meter_type + ','
      }
      if (userfile === ''){
        userfile = '无表具,'
      }
      console.log("表具信息",userfile)
      this.userfile = userfile
      return userfile
    },
    async getDevice(f_process_id) {
      let data = {
        f_process_id: f_process_id
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `rs/sql/getUserDevices`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      let device = ''
      for (let i = 0; i < res.data.length ; i++){
        if (res.data[i].f_devices_type === null){
          res.data[i].f_devices_type = '设备'
        }
        console.log("设备信77息",res.data[i].f_devices_type)
        device = device + res.data[i].f_devices_count + '个' + res.data[i].f_devices_type + ','
      }
      if (device === ''){
        device = '无设备,'
      }
      console.log("设备信息",device)
      this.device = device
      return device
    },
    async getUserfile(f_process_id) {
      let data = {
        condition: `met.f_process_id = '${f_process_id}'`
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `rs/sql/getUserfiles`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      if (res.data.length > 0){
        this.userfile = res.data[0].f_meter
        this.device = res.data[0].f_devices
        return res.data[0]
      }
      return {f_meter:'无',f_devices:'无'}
    },
    async getUserfiles(selectPrint) {
      let porcessid = `(`
      if (selectPrint.length > 0){
        for (let i=0; i < selectPrint.length-1; i++){
          porcessid = porcessid + `'` + selectPrint[i].f_process_id + `',`
        }
        porcessid = porcessid + `'` + selectPrint[selectPrint.length-1].f_process_id + `')`
      }
      console.log("当前porcessid",porcessid)

      let data = {
        condition: `met.f_process_id in ${porcessid}`
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `rs/sql/getUserfiles`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      console.log("当前res.data",res.data)
      return res.data
    },
    async getUser(str) {
      if (str) {
        let data = {
          items: 'us.name username,de.name departmentname',
          tablename: 't_user us left join t_department de on us.parentid = de.id',
          condition: `us.id = '${str}'`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          'rs/sql/applySingleTable',
          {data: data}, {
            resolveMsg: null,
            rejectMsg: '操作人查询失败！！！'
          })
        if (res.data.length > 0){
          let result = res.data[0]
          console.log('当前人员信息', result)
          return result
        }else {
          return {username:'',departmentname:''}
        }
      }
    },
    smalltoBIG (n) {
      let fraction = ['角', '分']
      let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      let unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']]
      let head = n < 0 ? '欠' : ''
      n = Math.abs(n)

      let s = ''

      for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
      }
      s = s || '整'
      n = Math.floor(n)

      for (var i = 0; i < unit[0].length && n > 0; i++) {
        let p = ''
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p
          n = Math.floor(n / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }
      let result = head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
      console.log('当前大写', result)
      return result
    },
    clear () {
      Object.keys(this.$refs.cp.$refs.cri.model).forEach((key) => {
        this.$refs.cp.$refs.cri.model[key] = ''
      })
    },
    searchCondition (args) {
      this.model.search(args.condition, args.model)
    },
    // 查询
    search () {
      this.$refs.cp.$refs.cri.search()
    }
  },
  computed: {
  }
}
</script>

<style scoped>
</style>
