<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-3" >
              <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 00:00:00'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-3" >
              <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 23:59:59'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-3" >
              <label class="font_normal_body" for="yearStartDate">年开始日期:</label>
              <datepicker id="yearStartDate" placeholder="年开始日期" style="width: 60%"
                          v-model="model.yearStartDate"
                          :value.sync="model.yearStartDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd 00:00:00'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-3" >
              <label  class="font_normal_body" for="yearEndDate">年结束日期:</label>
              <datepicker id="yearEndDate" placeholder="年结束日期" style="width: 60%"
                          v-model="model.yearEndDate"
                          :value.sync="model.yearEndDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd 23:59:59'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-3 form-group" >
              <label class="font_normal_body" for="org">公&emsp;&emsp;司:</label>
              <manage-right-tree id="org" @re-res="$parent.$parent.getRes" style="width: 60%" v-ref:org></manage-right-tree>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body" for="dep" >部&emsp;&emsp;门:</label>
              <v-select id="dep" style="width: 60%"
                        :multiple="false"
                        @change="$parent.$parent.getDep"
                        :value.sync="model.f_depid"
                        v-model="model.f_depid"
                        :options='$parent.$parent.depresid' placeholder='请选择'
                        condition="f_depid in {}">
              </v-select>

            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body" for="oper">人&emsp;&emsp;员:</label>
              <v-select id="oper" style="width: 60%"
                        :multiple="false"
                        @change="$parent.$parent.getOpe"
                        :value.sync="model.f_operatorid"
                        v-model="model.f_operatorid"
                        :options='$parent.$parent.userresid' placeholder='请选择'
                        condition="f_operatorid in {}">
              </v-select>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body" for="oper1">格式一</label>
              <input type="radio" name="reportStyle" id="oper1" v-model="$parent.$parent.reportStyle" value="1">
              <label class="font_normal_body" for="oper2">格式二</label>
              <input type="radio" name="reportStyle" id="oper2"  v-model="$parent.$parent.reportStyle" value="2">
            </div>
          </div>
          <div class="span" style = "float:right;">
            <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>
        </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.tablen' style="font-weight: normal; text-align: left;">
              <h3 style="text-align: center">营业分类统计</h3>
            </th>
          </tr>
          <tr>
            <th :colspan='$parent.tablen' style="font-weight: normal; text-align: center;">
              时间区间：{{$refs.criteria.model.startDate}} - {{ $refs.criteria.model.endDate }}<br/>
              打印时间：{{$parent.printTime}}
            </th>
          </tr>
          <tr>
            <th :colspan='$parent.tablen' style="font-weight: normal; text-align: center;">
              <div>
                <span v-show="$parent.orgname[0]">公司：{{$parent.orgname}}</span>
                <span v-show="$parent.depname[0]"> 部门：{{$parent.depname}}</span>
                <span v-show="$parent.operatorname[0]">人员：{{$parent.operatorname}}</span>
              </div>
            </th>
          </tr>
          </thead>
          <tr>
            <td :colspan='$parent.tablen' class="noborder">
              {{{ model.data.substring(26,model.data.length-8) }}}
            </td>
          </tr>
          <tfoot>
          <tr style="text-align: left">
            <th :colspan='Math.floor($parent.tablen/3)'>财务审核：</th>
            <th :colspan='Math.round($parent.tablen/3)'>收款审核：</th>
            <th :colspan='Math.round($parent.tablen/3)'>收款员：</th>
          </tr>
          </tfoot>
        </table>
      </div>
    </criteria-paged>
  </div>
</template>

<script>
import {DataModel, HttpResetClass} from 'vue-client'
  import co from 'co'
let getorg = async function (self) {
  new HttpResetClass().load("POST",'api/af-revenue/sql/singleTableParam',
    {
      data: {
        items: 'name label,id value',
        tablename: 't_department',
        condition: `1=1`
      }
    },
    {resolveMsg: null, rejectMsg: null})
    .then((res) => {
      self.depresid = res.data
    })
  new HttpResetClass().load("POST",'api/af-revenue/sql/singleTableParam',
    {
      data: {
        items: 'name label,id value',
        tablename: 't_user',
        condition: `state = '在职' and f_department_name is not null`
      }
    },
    {resolveMsg: null, rejectMsg: null})
    .then((res) => {
      self.userresid = res.data
    })
}
  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: [],
        tablen:0,
        reportStyle: 1,
        orgname: '',
        depname: '',
        operatorname: '',
        orgCondtionStr: '1=1',
        model: new DataModel('api/af-revenue/report/BusinessClassify', {
          startDate: 'this.model.startDate',
          endDate: 'this.model.endDate',
          yearStartDate: 'this.model.yearStartDate',
          yearEndDate: 'this.model.yearEndDate',
          f_orgid: 'this.model.f_orgid'}),
        reportStr: null,
        show: false,
      }
    },
    ready () {
      getorg(this)
      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'
      console.log(this.$login.f)
    },
    methods: {
      adjustParams(startDateStr,endDateStr) {
        const now = new Date()
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)

        const startDate = new Date(startDateStr)
        const endDate = new Date(endDateStr)
        let result
        if (startDate < todayStart && endDate >= todayStart) {
          // startDate 在今天之前，endDate 在今天或之后
          let splitDates = 2
          let month = now.getMonth() + 1
          let date = now.getDate()
          const yesterday = new Date(now);
          yesterday.setDate(yesterday.getDate() - 1);
          let month2 = yesterday.getMonth() + 1
          let date2 = yesterday.getDate()
          result = {
            splitDates: splitDates,
            yesterdayEnd: (yesterday.getFullYear() + '-' + (month2 < 10 ? '0' + month2 : month2) + '-' + (date2 < 10 ? '0' + date2 : date2) + ' 23:59:59'),
            todayStart:  now.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date) + ' 00:00:00'
          }
        } else if (startDate >= todayStart && endDate >= todayStart) {
          // startDate 和 endDate 都在今天或之后
          let splitDates = 0
          result = {
            splitDates: splitDates
          }
        } else {
          // startDate 和 endDate 都在今天之前
          let splitDates = 1
          result = {
            splitDates: splitDates
          }
        }
        function padZero(num) {
          return num.toString().padStart(2, '0');
        }
        return result;
      },
      searchData () {
        this.$refs.paged.$refs.criteria.search()
      },
      getDep(val){
        this.depname = this.depresid.filter(x => x.value ==val).map(x=>x.label).toString()
        console.log('dep',this.depname )
      },
      getOpe(val){
        this.operatorname = this.userresid.filter(x => x.value ==val).map(x=>x.label).toString()
        console.log('dep',this.operatorname )
      },
      distinctJson(obj){
        let at = []
        for (let i = 0; i < obj.length; i++) {
          let flag = false
          if (i == 0 ) {
            at.push(obj[i])
          } else {
            for (let j = 0; j < at.length; j++) {
              if (JSON.stringify(obj[i]) == JSON.stringify(at[j])) {
                flag = true
              }
            }
            if (!flag) {
              at.push(obj[i])
            }
          }
        }
        return at
      },
      selfSearch (args) {
        console.log('---------------->', this.reportStyle)
        this.printTime = this.$login.toStandardTimeString()
        let orgcondition = '1=1'
        if (this.f_orgid) {
          orgcondition += ` and f_orgid in (${this.f_orgid})`
        }
        orgcondition += ' and ' + args.condition
        this.$refs.paged.$refs.criteria.model.f_orgid = orgcondition
        let monthObj = null
        let yearObj = null
        if (this.$refs.paged.$refs.criteria.model.startDate && this.$refs.paged.$refs.criteria.model.endDate ) {
          monthObj = this.adjustParams(this.$refs.paged.$refs.criteria.model.startDate, this.$refs.paged.$refs.criteria.model.endDate)
        }
        if (this.$refs.paged.$refs.criteria.model.yearStartDate && this.$refs.paged.$refs.criteria.model.yearEndDate) {
          yearObj = this.adjustParams(this.$refs.paged.$refs.criteria.model.yearStartDate, this.$refs.paged.$refs.criteria.model.yearEndDate)
        }
        console.log('========', monthObj)
        console.log('========', yearObj)
        if (this.reportStyle == '1') {
          let load = new HttpResetClass()
          let params = {
            startDate: args.model.startDate,
            endDate: args.model.endDate,
            monthRealTime: 0,
            yearRealTime: 0,
            monthRealStart: '',
            monthHistoryEnd: '',
            yearRealStart: '',
            yearHistoryEnd: '',
            yearStartDate: args.model.yearStartDate,
            yearEndDate: args.model.yearEndDate,
            f_orgid: orgcondition
          }
          if (monthObj && monthObj.splitDates === 2) {
            params.monthRealTime = monthObj.splitDates
            params.monthRealStart = monthObj.todayStart
            params.monthHistoryEnd = monthObj.yesterdayEnd
          } else if (monthObj) {
            params.monthRealTime = monthObj.splitDates
          }
          if (yearObj && yearObj.splitDates === 2) {
            params.yearRealTime = yearObj.splitDates
            params.yearRealStart = yearObj.todayStart
            params.yearHistoryEnd = yearObj.yesterdayEnd
          } else if (yearObj) {
            params.yearRealTime = yearObj.splitDates
          }
          load.load("POST", 'api/af-revenue/sql/UserCountNum',
            {data: params},
            {resolveMsg: null, rejectMsg: null})
            .then((res) => {
              let info = res.data
              let gasproperties = info.map(item => {return {f_gasproperties: item.f_gasproperties}})
              let district = info.map(item => {
                return { f_gasproperties: item.f_gasproperties, f_district: item.f_district }
              })
              let meter_type = info.map(item => {
                return { f_meter_type: item.f_meter_type }
              })
              this.model.url = 'api/af-revenue/report/BusinessClassify'
              this.$refs.paged.$refs.criteria.model.f_orgid = {
                left1: JSON.stringify(this.distinctJson(gasproperties)),
                left2: JSON.stringify(this.distinctJson(district)),
                left3: JSON.stringify(this.distinctJson(meter_type)),
                infoall: JSON.stringify(info)
              }
              this.$refs.paged.search(args)
            })
        } else {
          this.model.params.monthRealTime = 0
          this.model.params.yearRealTime = 0
          this.model.params.monthRealStart = ''
          this.model.params.monthHistoryEnd = ''
          this.model.params.yearRealStart = ''
          this.model.params.yearHistoryEnd = ''
          if (monthObj && monthObj.splitDates === 2) {
            this.model.params.monthRealTime = monthObj.splitDates
            this.model.params.monthRealStart = monthObj.todayStart
            this.model.params.monthHistoryEnd = monthObj.yesterdayEnd
          }else if (monthObj) {
            this.model.params.monthRealTime = monthObj.splitDates
          }
          if (yearObj && yearObj.splitDates === 2) {
            this.model.params.yearRealTime = yearObj.splitDates
            this.model.params.yearRealStart = yearObj.todayStart
            this.model.params.yearHistoryEnd = yearObj.yesterdayEnd
          }else if (yearObj) {
            this.model.params.yearRealTime = yearObj.splitDates
          }
          this.model.url = 'api/af-revenue/report/BusinessClassifyTwo'
          this.$refs.paged.search(args)
        }
      },
      getRes (obj) {
        this.orgname = obj.res[0]
        this.f_orgid = obj.resids
      }
    },
    watch: {
      'model.data' (val) {
        if (val) {
          this.tablen = val.split('</tr>').map(item => item.split('</td>').length-1).reduce((x, y) => x > y ? x : y)
        }
      },
      'reportStyle'(val) {
        this.$refs.paged.$refs.criteria.search()
      }
    },
    computed: {

    }
  }
</script>
<style scoped>
  .noborder{
    border: none;
  }
</style>
