<!-- 请假设置 -->
<template>
  <div>
    <Row justify="space-between" type="flex">
      <Col>
        <Input placeholder="工号/姓名" class="setInput" v-model="searchForm.userName"/>
        <Select class="setInput" placeholder="小组" v-model="searchForm.teamId" clearable>
          <Option v-for="(item,index) in teamList" :value="item.wmTeamId" :key="index">{{item.wmName}}</Option>
        </Select>
        <DatePicker
          :clearable="false"
          :disabled="loading || exportLoading"
          :editable="false"
          placement="bottom-start"
          class="setInput"
          type="year"
          v-model="searchDay"
        ></DatePicker>
        <!-- <Select class="setInput" placeholder="考情情况" v-model="searchForm.timeSheetState">
          <Option v-for="(item,index) in selectList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select> -->
        <Select class="setInput" placeholder="是否有效" v-model="searchForm.isEffective" clearable>
          <Option v-for="(item,index) in availableList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
        <Button
          :disabled="exportLoading"
          :loading="loading"
          @click="doInitSearch"
          style="margin-left: 6px;"
          type="primary"
        >查询</Button>
      </Col>
      <Col>
        <Button @click="showImportData" class="mr-set6" v-permission:import>导入</Button>
        <Modal
          :loading="loading"
          :mask-closable="false"
          :styles="{width: '450px'}"
          @on-ok="handleImportData"
          @on-visible-change="handleCloseIndex"
          class-name="cancle-hide"
          title="导入"
          v-model="modalIndex2"
        >
          <Upload
            :before-upload="handleBeforeUpload"
            :format="['xlsx', 'xls']"
            action
            ref="upload"
            style="margin-top:16px;width:300px;"
            type="drag"
          >
            <div style="padding: 20px 0">
              <Icon size="52" style="color: #3399ff" type="ios-cloud-upload"></Icon>
              <p>点击或者拖拽上传</p>
              <Spin fix size="large" v-if="spinShow"></Spin>
            </div>
          </Upload>
          <Button @click="modelDownload">下载模板</Button>
        </Modal>
        <!-- <Poptip @on-ok="handleExport" confirm title="确定导出表格信息？">
          <Button :disabled="loading" :loading="exportLoading" v-permission:export>导出</Button>
        </Poptip> -->
      </Col>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataDaily" :loading="loading" border @on-sort-change = "sort"></Table>
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      class="mt-set16"
      show-total
    />
    <Modal :mask-closable="false" title="修改考勤状态" v-model="modalIndex" @on-cancel="searchForm2={}">
      考勤状态：
      <Select class="setInput" placeholder="考情状态" v-model="searchForm2.timeSheetState">
        <Option v-for="(item,index) in selectList" :value="item.value" :key="index">{{item.label}}</Option>
      </Select>
      <div slot="footer">
        <Button @click="confirmEdit" type="primary">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import LeaveAPI from '@api/common/leave'
import WmTeamsAPI from '@api/common/wmTeams'
import { format } from 'date-fns'
import commonadvSearch from '@/mixin/commonadvSearch'
import { downloadExcel } from '@lib/download'
import cloneDeep from 'lodash/cloneDeep'
import store from '@/store'

export default {
  name: 'daily-details',
  mixins: [commonadvSearch],
  data () {
    return {
      selectList: [
          {
              value: '1',
              label: '迟到'
          },
          {
              value: '2',
              label: '早退'
          },
          {
              value: '3',
              label: '上班正常'
          },
          {
              value: '4',
              label: '上班异常'
          },
          {
              value: '5',
              label: '下班正常'
          },
          {
              value: '6',
              label: '下班异常'
          }
      ],
      availableList :[
          {
              value: '0',
              label: '无效'
          },
          {
              value: '1',
              label: '有效'
          },
      ],
      teamList: [],
      modalIndex: false,
      loading: false,
      exportLoading: false,
      searchDay: '',
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        orderBy: null,
        userName: null,
        teamId: null,
        year: '',
        isEffective: null
        // startTime: '',
        // endTime: '',
        //timeSheetState: ''
      },
      searchForm2: {
        uuid: '',
        timeSheetState: ''
      },
      exportInfo: {},
      columnsDaily: [
        {
          title: '组别',
          key: 'teamId',
          tooltip: true,
          sortable: 'custom',
          render: (h, params) => {
             return h('div',params.row.teamName)
          }
          // width: 100
        },
        {
          title: '座席姓名',
          key: 'name',
          // width: 100,
          //fixed: 'left'
        },
        {
          title: '工号',
          key: 'userName',
          // width: 100,
          //fixed: 'left'
        },
        {
          title: '假期类型',
          key: 'leaveName',
          // width: 100,
          //fixed: 'left'
        },
        {
          title: '年假总天数',
          key: 'major',
          // width: 100,
          //fixed: 'left'
        },
        {
          title: '剩余天数',
          key: 'remianAnnualLeave',
          sortable: 'custom',
          // width: 100,
          //fixed: 'left'
        },
         {
          title: '年份',
          key: 'year',
          // width: 100,
          //fixed: 'left'
        },
        {
          title: '是否有效',
          key: 'isEffective',
          sortable: 'custom',
          render: (h, params) => {
           if (params.row.isEffective == 0) {
             return h('div','无效')
           } else if(params.row.isEffective == 1) {
              return h('div','有效')
           }
          }
        } 
      ],
      dataDaily: [],
      modalIndex2: false,
      spinShow: false,
      UploadParams: {},
      loading: false
    }
  },
  created(){
    this.doInitSearch()
    this.searchGroup()
  },
  mounted () {
    this.searchDay = format(
      new Date(store.state.app.systemTime),
      this.$config.DATE_FORMAT
    )
    // this.searchDay[0] = format(
    //   new Date(store.state.app.systemTime),
    //   this.$config.DATE_FORMAT
    // )
    // this.searchDay[1] = format(
    //   new Date(store.state.app.systemTime),
    //   this.$config.DATE_FORMAT
    // )
  },
  watch: {
    // searchDay () {
    //   if (this.searchDay) {
    //     this.searchDay = format(
    //       new Date(this.searchDay),
    //       this.$config.DATE_FORMAT
    //     )
    //   } else {
    //     this.searchDay = []
    //   }
    // }
  },
  methods: {
    //排序
    sort (id) {
      if(id.order == 'normal') {
        this.searchForm.orderBy = null
      }else {
        // if(this.searchForm.orderBy !== null) {
        //   this.searchForm.orderBy =this.searchForm.orderBy +','+ id.key+' '+id.order
        // } else {
          this.searchForm.orderBy = id.key+' '+id.order
        // }
      }
      this.doSearch()
    },
    // 查询小组列表
    searchGroup () {
      WmTeamsAPI.list().then(({data}) => {
        if(data.status === 'success') {
          console.log(data.data)
          this.teamList = data.data.list
        }
      }).catch(err => {
        console.error('err:', err)
      })
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      this.loading = true
      //console.log(123);
      this.$nextTick(() => {
        //debugger;
        // this.searchForm.startTime =  format(
        //   this.searchDay[0],
        //   this.$config.DATE_FORMAT
        // )
        // this.searchForm.endTime = format(
        //   this.searchDay[1],
        //   this.$config.DATE_FORMAT
        // )
        // this.searchForm.startTime = new Date(this.searchDay[0]).valueOf()
        // this.searchForm.endTime = new Date(this.searchDay[1]).valueOf()
        this.searchForm.year = format(
          this.searchDay,
          this.$config.YEAR_FORMAT
        )
        console.log(this.searchForm)
        LeaveAPI.annualLeave({ ...this.searchForm })
          .then(({ data }) => {
            console.log(data,'233')
            this.loading = false
            if (data.status === 'success') {
              this.total = data.data.total
              this.dataDaily = data.data.list
            }
          })
          .catch(err => {
            console.error('err: ', err)
            this.loading = false
          })
      })
    },
    // 导入班表
    showImportData () {
      this.modalIndex2 = true
    },
    // 导入班表 - 确定
    handleImportData () {
      let formData2 = new FormData()
      formData2.append('filename', this.UploadParams.filename)
      formData2.append('type', this.UploadParams.type)
      //console.log(formData2);
      LeaveAPI.importAnnualLeave(formData2)
        .then(({ data }) => {
          this.spinShow = false
          if (data.status === 'success') {
            this.$Message.destroy()
            this.$Message.success('导入成功!')
            this.modalIndex2 = false;
            this.doInitSearch()
            //if (this.spinShow) return false
          }
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 关闭导入班表
    handleCloseIndex () {
      this.dateType2 = 1
      this.$refs.upload.fileList = []
    },
    // 下载模板
    modelDownload () {
      LeaveAPI.downloadAnnualLeave()
        .then(({ data, headers }) => {
          let fileName = decodeURIComponent(
            headers['content-disposition'].split(';')[1].split('filename=')[1]
          )
          downloadExcel(data, fileName)
        })
        .catch(err => {
          console.error('err: ', err)
        })
    },
    // 导入文件
    handleBeforeUpload (file) {
      this.$refs.upload.fileList.pop()
      console.log('file ', file)
      //debugger;
      if (!new RegExp('.(xlsx|xls)$').test(file.name)) {
        this.$Message.destroy()
        this.$Message.warning('请上传xlsx或xls格式文件')
      } else {
        let reader = new FileReader()
        reader.onprogress = e => {
          this.spinShow = true
          console.log('progress', e)
        }
        reader.onerror = e => {
          // this.$refs.upload.fileList.pop()
        }
        reader.readAsDataURL(file)
        reader.onloadend = e => {
          console.log('file reader', reader)
          this.fileName = file.name
          file.url = reader.result

          this.UploadParams.filename = file
          this.UploadParams.type = this.dateType2
          this.spinShow = false
          this.$Message.success('选择文件成功!')
          this.$refs.upload.fileList.push(file)
          // let formData2 = new FormData()
          // formData2.append('filename', file)
          // formData2.append('type', this.dateType2)
          // TimeSheetDayAPI.importexcel(formData2)
          //   .then(({ data }) => {
          //     this.spinShow = false
          //     if (data.status === 'success') {
          //       this.$Message.destroy()
          //       this.$Message.success('导入成功!')
          //       this.$refs.upload.fileList.push(file)
          //     }
          //   })
          //   .catch(err => {
          //     console.error(err)
          //   })
        }
      }
      return false
    },
    // 导出
    handleExport () {
      if (this.dataDaily.length === 0) {
        this.exportLoading = false
        this.$Message.destroy()
        this.$Message.warning('请先查询数据')
      } else {
        this.exportLoading = true
        TimeSheetDayAPI.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()
    },
    //修改
    infoEdit(row){
      //console.log(row);
      this.searchForm2.uuid = row.uuid
      this.modalIndex = true
    },
    //修改提交
    confirmEdit(){
      //console.log(this.searchForm2);
      if(!this.searchForm2.timeSheetState){
        this.$Message.destroy()
        this.$Message.warning('请选择考勤情况')
      }else{
        this.$nextTick(() => {
        //debugger;
        TimeSheetDayAPI.edit({ ...this.searchForm2 })
          .then(({ data }) => {
            //this.loading = false
            if (data.status === 'success') {
              //console.log(data);
              this.$Message.destroy()
              this.$Message.success('修改成功!')
              this.searchForm2 = {}
              this.modalIndex = false
              this.doInitSearch()
            }
          })
          .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>
