<!-- 考勤统计 -->
<template>
  <div>
    <Row justify="space-between" type="flex">
      <Col>
        <Input placeholder="工号/姓名" class="setInput" v-model="searchForm.userName"/>
        <DatePicker
          :clearable="false"
          :disabled="loading || exportLoading"
          :editable="false"
          :options="startControl"
          placeholder="起始日期"
          placement="bottom-start"
          type="date"
          v-model="loginstartdate"
        ></DatePicker>
        <span style="padding: 0 6px;">-</span>
        <DatePicker
          :clearable="false"
          :disabled="loading || exportLoading"
          :editable="false"
          :options="endControl"
          placeholder="截止日期"
          placement="bottom-start"
          type="date"
          v-model="loginenddate"
          style="margin-right: 10px;"
        ></DatePicker>
        <Select v-model="searchForm.dateType" class="setInput" placeholder="日报">
          <Option name='0' value="3" selected="selected">日报</Option>
          <Option name='0' value="2">月报</Option>
          <Option name='0' value="1">年报</Option>
        </Select>
        <Button
          :disabled="exportLoading"
          :loading="loading"
          @click="doInitSearch"
          style="margin-left: 6px;"
          type="primary"
        >查询</Button>
        <!-- <advancedSearch
          :autoLoad="isAdvanLoad"
          :clearable="isNoAgent"
          :disabled="loading || exportLoading"
          :orgType="otype"
          @invokeDoSearch="exeDosearch"
          @on-confirm="handleAdvanSearch"
          @on-select-admin-group="AdvanSearchGroup"
          @on-select-special-line="AdvanSearchCenter"
          @on-select-sub-center="AdvanSearchCenter"
        ></advancedSearch> -->
      </Col>
      <Col>
        <Poptip @on-ok="handleExport" confirm title="确定导出表格信息？">
          <Button :disabled="loading" :loading="exportLoading" v-permission:export>导出</Button>
        </Poptip>
      </Col>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataMonth" :loading="loading" border></Table>
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      class="mt-set16"
      show-total
    />
  </div>
</template>

<script>
//import advancedSearch from '@/views/components/advanced-search'
import TimeSheetMonthAPI from '@api/common/timeSheetMonth'
import TimeSheetDayAPI from '@api/common/timeSheetDay'
import { format, differenceInMonths, subMonths } from 'date-fns'
// import commonadvSearch from '@/mixin/commonadvSearch'
// import advanceSearchClear from '@/mixin/advanceSearchClear'
import { downloadExcel } from '@lib/download'
import cloneDeep from 'lodash/cloneDeep'
import store from '@/store'
import { timeout } from 'q'
export default {
  name: 'monthly-statistics',
  //mixins: [commonadvSearch, advanceSearchClear],
  // components: {
  //   advancedSearch
  // },
  data () {
    return {
      loading: false,
      exportLoading: false,
      loginstartdate: '',
      loginenddate: '',
      total: 0,
      searchForm: {
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10,
        dateType: 3,
        userName: ''
      },
      exportInfo: {},
      startControl: {
        disabledDate: date => {
          if (typeof this.loginenddate.valueOf() === 'number') {
            return date && date.valueOf() > this.loginenddate.valueOf()
          }
        }
      },
      endControl: {
        disabledDate: date => {
          return date && date.valueOf() <= this.loginstartdate - 2592000000
        }
      },
      columnsDaily: [
        {
          title: '周期',
          key: 'userline',
          //width: 100,
          tooltip: true,
          //fixed: 'left'
        },
        {
          title: '工号',
          key: 'userCode',
          //minWidth: 120,
          tooltip: true,
          //fixed: 'left'
        },
        {
          title: '座席姓名',
          key: 'userName',
          //width: 100,
          //fixed: 'left'
        },
        {
          title: '上班异常次数',
          key: 'userref',
          tooltip: true,
          //width: 100
        },
        {
          title: '上班正常次数',
          key: 'agentId',
          tooltip: true,
          //width: 100
        },
        {
          title: '迟到次数',
          key: 'docnumber',
          //width: 155
        },
        {
          title: '早退次数',
          key: 'userLevel',
          //width: 100
        },
        {
          title: '下班正常次数',
          key: 'fullAttendance',
          //width: 100,
          render: (h, params) => {
            return h(
              'span',
              params.row.fullAttendance ? params.row.fullAttendance : '0'
            )
          }
        },
        {
          title: '下班异常次数',
          key: 'sicklevelTimein30',
          //width: 90,
          render: (h, params) => {
            return h(
              'span',
              params.row.sicklevelTimein30 ? params.row.sicklevelTimein30 : '0'
            )
          }
        }
      ],
      dataMonth: []
    }
  },
  watch: {
    loginstartdate () {
      if (this.loginstartdate) {
        this.searchForm.startTime = format(
          new Date(this.loginstartdate),
          this.$config.DATE_FORMAT
        )
      } else {
        this.searchForm.startTime = ''
      }
    },
    loginenddate () {
      if (this.loginenddate) {
        this.searchForm.endTime = format(
          new Date(this.loginenddate),
          this.$config.DATE_FORMAT
        )
      } else {
        this.searchForm.endTime = ''
      }
    }
  },
  mounted () {
    this.loginstartdate = subMonths(new Date(store.state.app.systemTime), 1)
    this.loginenddate = subMonths(new Date(store.state.app.systemTime), 0)
  },
  created () {
    this.doInitSearch()
  },
  methods: {
    // 分页
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.doSearch()
    },
    // 导出
    handleExport () {
      if (this.dataMonth.length === 0) {
        this.exportLoading = false
        this.$Message.destroy()
        this.$Message.warning('请先查询数据')
      } else {
        this.exportLoading = true
        TimeSheetMonthAPI.exportexcel({ ...this.exportInfo })
          .then(({ data, headers }) => {
            this.exportLoading = false
            let fileName = decodeURIComponent(
              headers['content-disposition'].split(';')[1].split('filename=')[1]
            )
            downloadExcel(data, fileName)
          })
          .catch(err => {
            console.error('err: ', err)
            this.exportLoading = false
          })
      }
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      // if (this.stopSearch()) {
      //   this.dataMonth = []
      //   return
      // }
      this.loading = true
      this.$nextTick(() => {
        const dateRange = differenceInMonths(
          new Date(this.searchForm.endTime),
          new Date(this.searchForm.startTime)
        )
        if (dateRange > this.$config.DATE_RANGE_SIX_MONTH) {
          // this.loading = false
          // this.$Message.destroy()
          // this.$Message.warning(
          //   `日期范围不能超过${this.$config.DATE_RANGE_SIX_MONTH}个月`
          // )
          // this.dataMonth = []
        } else {
          let _this = this
          setTimeout(function(){ _this.loading = false }, 1000);
          console.log(this.searchForm)
          TimeSheetDayAPI.statistics({...this.searchForm}).then(({data}) => {
            this.loading = false
            if(data.status === 'success'){
              console.log(data.data)
              const formData = cloneDeep(data.data.list)
              console.log('formdata',formData)
              for(let i = 0, len = formData.length; i<len; i++) {
                formData[i].userline = formData[i].date
                formData[i].userCode = formData[i].userCode
                formData[i].userName = formData[i].userName
                formData[i].userref = formData[i].sbyc
                formData[i].agentId = formData[i].sbzc
                formData[i].docnumber = formData[i].cd
                formData[i].userLevel = formData[i].zt
                formData[i].fullAttendance = formData[i].xbzc
                formData[i].sicklevelTimein30 = formData[i].xbyc
              }
              this.total = data.data.total
              this.dataMonth = formData
            }
          }).catch(err => {
            console.error('err: ', err)
            this.loading = false
          })     
          // TimeSheetMonthAPI.viewList({ ...this.searchForm })
          //   .then(({ data }) => {
          //     this.loading = false
          //     if (data.status === 'success') {
          //       this.exportInfo.loginstartdate = format(
          //         new Date(this.loginstartdate),
          //         this.$config.MONTH_FORMAT
          //       )
          //       this.exportInfo.loginenddate = format(
          //         new Date(this.loginenddate),
          //         this.$config.MONTH_FORMAT
          //       )
          //       if (this.paramsAdvance) {
          //         this.exportInfo.usercenter = this.removeAnnotation(
          //           this.paramsAdvance.sc.id
          //         )
          //         if (this.paramsAdvance.sl) {
          //           this.exportInfo.userline = this.removeAnnotation(
          //             this.paramsAdvance.sl.id
          //           )
          //         }
          //         if (this.paramsAdvance.ag) {
          //           this.exportInfo.usergroupname = this.removeAnnotation(
          //             this.paramsAdvance.ag.id
          //           )
          //         }
          //       }
          //       const formData = cloneDeep(data.data.list)
          //       for (let i = 0, len = formData.length; i < len; i++) {
          //         formData[i].usercenter = formData[i].map.usercenter
          //         formData[i].userline = formData[i].map.userline
          //         formData[i].usergroupname = formData[i].map.userteam
          //       }
          //       this.total = data.data.total
          //       this.dataMonth = formData
          //     }
          //   })
          //   .catch(err => {
          //     console.error('err:', err)
          //     this.loading = false
          //   })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.align-left {
  text-align: left;
}
.setInput{
  width: 200px;
  margin-right: 10px;
}
</style>
