<!-- 班表统计 -->
<template>
  <div>
    <Row justify="space-between" type="flex">
      <Col>
        <Input placeholder="工号/姓名" v-model="searchForm.condition" class="setInput"/>
        <DatePicker
          :clearable="false"
          :disabled="loading || exportLoading"
          :editable="false"
          placeholder="查询日期"
          placement="bottom-start"
          type="month"
          v-model="date"
        ></DatePicker>
        <Select class="setInput" placeholder="小组" v-model="searchForm.teamId" clearable>
          <Option v-for="(item,index) in selectList" :value="item.wmTeamId" :key="index">{{item.wmName}}</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="确定导出表格信息？" v-permission:export="'schedule-statistics'">
          <Button :disabled="loading" :loading="exportLoading"
          >导出班表统计</Button>
        </Poptip>
      </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 ScheduleAPI from '@api/common/schedule'
import WmTeamsAPI from '@api/common/wmTeams'
import ExcelAPI from '@api/sys/excel'
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'
export default {
  name: 'monthly-statistics',
  mixins: [commonadvSearch, advanceSearchClear],
  components: {
    advancedSearch
  },
  data () {
    return {
      loading: false,
      exportLoading: false,
      date: '',
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 20,
        teamId: ''
      },
      exportInfo: {
        type: 3,//班表统计导出
        param: {}
      },
      columnsDaily: [
        {
          title: '日期',
          key: 'date',
          //width: 155
        },
        {
          title: '工号',
          key: 'userCode',
          //width: 155
        },
        {
          title: '座席姓名',
          key: 'name',
          //width: 155
        },
        {
          title: '中心',
          key: 'siteName',
          //width: 155
        },
        {
          title: '渠道',
          key: 'activityName',
          //width: 155
        },
        {
          title: '组别',
          key: 'teamName',
          //width: 155
        },
        {
          title: '白班数',
          key: 'dayShiftCount',
          //width: 155
        },
        {
          title: '小夜班数',
          key: 'smallNightShiftCount',
          //width: 155
        },
        {
          title: '夜班数',
          key: 'nightShiftCount',
          //width: 155
        },
        
      ],
      dataMonth: [],
      // 小组列表
      selectList: []
    }
  },
  watch: {
    date () {
      if (this.date) {
        this.searchForm.date = format(
          new Date(this.date),
          this.$config.MONTH_FORMAT
        )
      } else {
        this.searchForm.date = ''
      }
    },
    // loginenddate () {
    //   if (this.loginenddate) {
    //     this.searchForm.loginenddate = format(
    //       new Date(this.loginenddate),
    //       this.$config.MONTH_FORMAT
    //     )
    //   } else {
    //     this.searchForm.loginenddate = ''
    //   }
    // }
  },
  mounted () {
    this.date = subMonths(new Date(store.state.app.systemTime), 0)
    //console.log(this.date);
    //this.loginenddate = subMonths(new Date(store.state.app.systemTime), 1)
  },
  created(){
    this.doInitSearch()
    this.searchGroup()
    console.log(this.$store.state.user.permission,'178')
  },
  methods: {
    // 查询小组列表
    searchGroup () {
      WmTeamsAPI.list().then(({data}) => {
        if(data.status === 'success') {
          console.log(data.data)
          this.selectList = data.data.list
        }
      }).catch(err => {
        console.error('err:', err)
      })
    },
    // 分页
    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
        const exportName = `${'班表统计'}_${this.searchForm.date}.xls`
        console.log(this.exportInfo)
        ExcelAPI.exportExcel({ ...this.exportInfo })
          .then(({ data }) => {
            this.exportLoading = false
            // let fileName = decodeURIComponent(
            //   headers['content-disposition'].split(';')[1].split('filename=')[1]
            // )
            downloadExcel(data, exportName)
          })
          .catch(err => {
            console.error('err: ', err)
            this.exportLoading = false
          })
      }
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      // if (this.stopSearch()) {
      //   this.dataMonth = []
      //   return
      // }
      console.log(this.searchForm);
      this.loading = true
      this.$nextTick(() => {
        
          ScheduleAPI.statistics({ ...this.searchForm })
            .then(({ data }) => {
              this.loading = false
              if (data.status === 'success') {
                this.exportInfo.param.date = format(
                  new Date(this.date),
                  this.$config.MONTH_FORMAT
                )
                this.exportInfo.param.condition = this.searchForm.condition
                // 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].date = formData[i].date
                  formData[i].userCode = formData[i].userCode
                  formData[i].name = formData[i].name
                  formData[i].siteName = formData[i].siteName
                  formData[i].activityName = formData[i].activityName
                  formData[i].teamName = formData[i].teamName
                  formData[i].dayShiftCount = formData[i].dayShiftCount
                  formData[i].nightShiftCount = formData[i].nightShiftCount
                  formData[i].smallNightShiftCount = formData[i].smallNightShiftCount
                }
                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: 0 10px;
}
</style>
