<!-- 绩效计件数据 -->
<template>
  <div>
    <Row align="middle" justify="space-between" type="flex">
      <Col span="18">
        <Row align="middle" type="flex">
          <DatePicker
            :clearable="false"
            :disabled="loading || exportLoading"
            :editable="false"
            :options="startControl"
            placeholder="起始日期"
            placement="bottom-start"
            style
            type="month"
            v-model="startdate"
          ></DatePicker>
          <span style="padding: 0 6px;">-</span>
          <DatePicker
            :clearable="false"
            :disabled="loading || exportLoading"
            :editable="false"
            :options="endControl"
            placeholder="截止日期"
            placement="bottom-start"
            style
            type="month"
            v-model="enddate"
          ></DatePicker>
          <Button
            :disabled="loading || 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>
        </Row>
      </Col>
      <Col class-name="align-right" span="6">
        <Poptip @on-ok="handleExport" class="align-left" confirm title="确定导出表格信息？">
          <Button :disabled="loading" :loading="exportLoading" v-permission:export>导出</Button>
        </Poptip>
      </Col>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataPiece" :loading="loading" border ref="table"></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 AchievePieceDataAPI from '@api/common/achievePieceData'
import { format, differenceInMonths, subMonths } from 'date-fns'
import commonadvSearch from '@/mixin/commonadvSearch'
import advanceSearchClear from '@/mixin/advanceSearchClear'
import cloneDeep from 'lodash/cloneDeep'
import { downloadExcel } from '@lib/download'
// import { dragTable } from '@/lib/dragTable'
import store from '@/store'
export default {
  name: 'piecework-data',
  mixins: [commonadvSearch, advanceSearchClear],
  components: {
    advancedSearch
  },
  data () {
    return {
      modalIndex: false,
      searchForm: {
        pageNum: 1,
        pageSize: 10
      },
      exportInfo: {},
      total: 0,
      loading: false,
      exportLoading: false,
      startdate: '',
      enddate: '',
      startControl: {
        disabledDate: date => {
          if (typeof this.enddate.valueOf() === 'number') {
            return date && date.valueOf() > this.enddate.valueOf()
          }
        }
      },
      endControl: {
        disabledDate: date => {
          return date && date.valueOf() <= this.startdate - 2592000000
        }
      },
      columnsDaily: [
        {
          title: '月份',
          key: 'dataMonth',
          maxWidth: 80
        },
        {
          title: '中心',
          key: 'usercenter',
          maxWidth: 120
        },
        {
          title: '专线',
          key: 'userline',
          maxWidth: 120
        },
        {
          title: '业务小组',
          minWidth: 120,
          key: 'usergroupname'
        },
        {
          title: '座席',
          key: 'username'
          // maxWidth: 80
        },
        {
          title: '员工编号',
          key: 'usercode',
          width: 120
          // tooltip: true
        },
        {
          title: '绩效模板名称',
          key: 'achieveModelName',
          tooltip: true
        },
        {
          title: '计件模板名称',
          key: 'pieceModelName',
          tooltip: true
        },
        {
          title: '绩效考核排名',
          key: 'achieveRange'
        },
        {
          title: '绩效考核得分',
          key: 'achieveScore'
        },
        {
          title: '计件工资',
          key: 'pieceScore'
        }
      ],
      dataPiece: []
    }
  },
  watch: {
    startdate () {
      if (this.startdate) {
        this.searchForm.startdate = format(
          new Date(this.startdate),
          this.$config.MONTH_FORMAT
        )
      } else {
        this.searchForm.startdate = ''
      }
    },
    enddate () {
      if (this.enddate) {
        this.searchForm.enddate = format(
          new Date(this.enddate),
          this.$config.MONTH_FORMAT
        )
      } else {
        this.searchForm.enddate = ''
      }
    }
  },
  created () {
    this.startdate = subMonths(new Date(store.state.app.systemTime), 1)
    this.enddate = subMonths(new Date(store.state.app.systemTime), 1)
  },
  mounted () {
    // let $this = this
    // this.$nextTick(() => {
    //   let dom = $this.$refs.table.$refs.header.getElementsByTagName('th')
    //   dragTable($this, dom)
    // })
  },
  methods: {
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      if (this.stopSearch()) {
        this.dataPiece = []
        return
      }
      this.loading = true
      this.$nextTick(() => {
        const dateRange = differenceInMonths(
          new Date(this.searchForm.enddate),
          new Date(this.searchForm.startdate)
        )
        if (dateRange > this.$config.DATE_RANGE_SIX_MONTH) {
          this.loading = false
          this.$Message.destroy()
          this.$Message.warning(
            `日期范围不能超过${this.$config.DATE_RANGE_SIX_MONTH}个月`
          )
          this.dataPiece = []
        } else {
          AchievePieceDataAPI.viewList({ ...this.searchForm })
            .then(({ data }) => {
              this.loading = false
              if (data.status === 'success') {
                this.exportInfo.startdate = format(
                  new Date(this.startdate),
                  this.$config.MONTH_FORMAT
                )
                this.exportInfo.enddate = format(
                  new Date(this.enddate),
                  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.usergroupname
                }
                this.total = data.data.total
                this.dataPiece = formData
              }
            })
            .catch(err => {
              console.error('err: ', err)
              this.loading = false
            })
        }
      })
    },
    // 导出
    handleExport () {
      if (this.dataPiece.length === 0) {
        this.exportLoading = false
        this.$Message.destroy()
        this.$Message.warning('请先查询数据')
      } else {
        this.exportLoading = true
        AchievePieceDataAPI.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
          })
      }
    },
    // 分页
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.doSearch()
    }
  }
}
</script>

<style lang="less" scoped>
.align-left {
  text-align: left;
}
</style>
