<!-- 班表查询 -->
<template>
  <div>
    <Row justify="space-between" type="flex">
      <Col>
        <Input placeholder="工号/姓名" class="setInput" v-model="searchForm.userName"/>
        <DatePicker
          :clearable="false"
          :disabled="!!exportLoading || searchLoading"
          :editable="false"
          placeholder="请选择月份"
          style="width: 200px"
          type="month"
          v-model="searchDateRange"
        ></DatePicker>
        <Button
          :disabled="!!exportLoading"
          :loading="searchLoading"
          @click="doInitSearch"
          style="margin-left: 8px;"
          type="primary"
        >查询</Button>
        <shift-advanced-search
          :clearable="isNoAgent"
          :disabled="!!exportLoading || searchLoading"
          @do-select-search="doInitSearch"
          @on-clear="onClear"
          @on-confirm="onConfirm"
          @on-get-org-err="onGetOrgErr"
          @on-select-admin-group="onSelectAdminGroup"
          @on-select-special-line="onSelectSpecialLIne"
          @on-select-sub-center="onSelectCenter"
          autoLoad
          autoSearch
        ></shift-advanced-search>
      </Col>
      <Col class-name="align-right" span="8">
        <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 v-permission:export @on-ok="exportExcel(1)" confirm title="确定导出班表？" transfer>
          <Button
            :disabled="searchLoading || this.exportLoading === 2"
            :loading="this.exportLoading === 1"
            style="margin-right: 4px;"
          >导出班表</Button>
        </Poptip>
      </Col>


      <!-- <Col>
        <Poptip v-permission:import @on-ok="exportExcel(1)" confirm title="确定导入班表？" transfer>
          <Button
            :disabled="searchLoading || this.exportLoading === 2"
            :loading="this.exportLoading === 1"
            style="margin-right: 4px;"
          >导入班表</Button>
        </Poptip> -->
        <!--<Poptip @on-ok="exportExcel(2)" confirm title="确定导出工时？" transfer>
          <Button
            :disabled="searchLoading || this.exportLoading === 1"
            :loading="this.exportLoading === 2"
          >导出工时</Button>
        </Poptip>
      </Col> -->
    </Row>
    <br />
    <Table :columns="columns" :data="dataList" :loading="searchLoading" border></Table>
    <br />
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      show-total
    />
    <Modal
      :mask-closable="false"
      @on-visible-change="onVisibleChange"
      title="班表编辑"
      v-model="showModal"
      width="800"
    >
      <el-calendar v-model="crtSelectDate">
        <template slot="dateCell" slot-scope="{date, data}">
          <div
            v-if="isSameMonth(date, calendarMonth)"
            style="width:100%;height:100%;"
            :class="data.isSelected ? 'is-selected p_comm' : 'p_comm'">
            <p>{{ data.day.split('-').slice(1).join('-') }}</p>
             <p>
              <Select
                :name="data.day + '-' + selectId"
                :placeholder="placeholderArc(data.day)"
                @on-change="selectChange(data.day)"
                v-model="model1[data.day]"
                clearable>
                <Option
                  :key="index"
                  :value="item.wmShiftId"
                  v-for="(item ,index) in SHIFT_TYPE"
                  @click.native="getMoreParams(item.wmShiftId,data.day)"
                >{{item.wmName}}</Option>
              </Select>
            </p>
          </div>
          <div v-else class="p_comm">
            <p>{{ data.day.split('-').slice(1).join('-') }}</p>            
          </div>
        </template>
      </el-calendar>
      <div slot="footer">
        <div>
        <Button @click="showModal = false">取消</Button>
        <Button :loading="confirmLoading" @click="confirmComplaint" type="primary">保存</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import commonListWidthAS from '@/mixin/commonListWidthAS'
import shiftEffectMonthLimit from '@/mixin/shiftEffectMonthLimit'
import ShiftAdvancedSearch from '@@c/shift-advanced-search'
import FileDownloadAPI from '@api/common/fileDownload'
import ScheduleAPI from '@api/common/schedule'
import ScheduleDaysAPI from '@api/common/scheduleDays'
import ExcelAPI from '@api/sys/excel'
import { parse,format, startOfMonth, endOfMonth,isSameMonth } from 'date-fns'
import shiftType from '@/mixin/shiftType'
import shiftMixin from './shift-mixin'
import { getWeekByDate } from '@lib/tools'
import { downloadExcel } from '@lib/download'
import configValue from '@conf/index'
const cellPrefix = 'calendar-cell'
export default {
  name: 'schedule-search',
  mixins: [shiftMixin,shiftType,commonListWidthAS, shiftEffectMonthLimit],
  components: { ShiftAdvancedSearch },
  data () {
    return {
      model1: [],
      rowList: {},
      selectId: '',
      selectIdList: [],
      advancedSearch: false,
      isSameMonth: isSameMonth,
      selectList: {},
      columns: [],
      selectForm: {
          agentId:'',
          schedule:[]
      },
      defaultColumns: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '中心',
          key: 'siteName',
          minWidth: 100,
          tooltip: true,
          fixed: 'left'
        },
        {
          title: '专线',
          key: 'activityName',
          minWidth: 100,
          tooltip: true,
          fixed: 'left'
        },
        {
          title: '业务小组',
          key: 'teamName',
          minWidth: 120,
          // tooltip: true,
          fixed: 'left'
        },
        {
          title: '姓名',
          key: 'firstName',
          minWidth: 100,
          tooltip: true,
          fixed: 'left'
        },
        {
          title: '操作',
          key: 'action',
          width: 70,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.InfoEdit(params.row)
                    }
                  }
                },
                '编辑'
              ),
            ])
          }
        }   
      ],
      modalIndex2: false,
      loading: true,
      dateType2: 1,
      spinShow: false,
      searchForm: {
        teamId: null,
        siteId: null,
        activityId: null,
        userName: ''
      },
      dataList: [],
      exportLoading: 0,
      UploadParams: {}
    }
  },
  created () {
    this.columns = this.defaultColumns
    this.searchLoading = true
  },
  watch: {
    searchDateRange () {
      this.searchForm.startTime = format(
        startOfMonth(this.searchDateRange),
        this.$config.DATE_FORMAT
      )
      this.searchForm.endTime = format(
        endOfMonth(this.searchDateRange),
        this.$config.DATE_FORMAT
      )
    }
  },
  computed: {
    isNoAgent () {
      let type = this.$store.state.user.userType
      if (
        type === configValue.LEADER_TYPE.ITEAM_AGENT ||
        type === configValue.LEADER_TYPE.ITEAM_LEADER
      ) {
        return false
      } else {
        return true
      }
    },
    placeholderArc(){
      //console.log('2',this.rowList);
      //return this.rowList[dataDay]
      return function(value){
        //console.log(this.rowList);
        return this.rowList[value]
      }
    },
  },
  methods: {
    InfoEdit(row){
      this.doSearch()
      this.showModal = true
      //console.log('row',row);
      // this.model1 = []
      this.rowList = row
      this.selectId = row.map.agentId
      console.log('123',this.rowList);
      // this.$nextTick(() => {
        
      //  
      // }) 
      
    },
    confirmComplaint(){
      this.selectForm.agentId = this.rowList.map.agentId
      if(this.selectForm.schedule.length>0){
         ScheduleAPI.edit(this.selectForm)
        .then(({ data }) => {
          //console.log(this.$refs.resetSelect)
          //this.$refs.resetSelect.clearSingleSelect();
          this.rowList = {}//清空数据
          this.selectForm.agentId = ''//清空数据
          this.selectForm.schedule = []//清空数据
          
          if (data.status === 'success') {
            this.$Message.destroy()
            this.$Message.success('保存成功!')
            this.showModal = false;
            this.doInitSearch()//回显
          }
        })
        .catch(err => {
          console.error(err)
        }) 
      }else{
        this.showModal = false
      }
      // console.log(this.selectForm);
    },
    onVisibleChange (visible) {
      // console.log('visible', visible)
      if(visible == false) {
        this.model1 = []
        this.selectForm.schedule = []
      }
    },
    selectChange(day){
      if(this.model1[day] == undefined && this.selectForm.schedule.length>0) {
        this.selectForm.schedule.splice(this.selectForm.schedule.findIndex(item => item.date == day),1)
      }
      console.log(this.selectForm.schedule)
    },
    getMoreParams(val,day){
      let obj = {}
      obj.date = day
      obj.shiftId = val
      console.log(obj)
      
      if(this.selectForm.schedule.length>0){
      this.selectForm.schedule.forEach(item =>{
        if(item.date == obj.date) {
          item.shiftId = obj.shiftId
        } else {
          this.selectForm.schedule.push(obj)
        }
      })} else {
        this.selectForm.schedule.push(obj)
      }
      
      const map = {}
      this.selectForm.schedule.forEach(item => map[JSON.stringify(item)] = item)
      this.selectForm.schedule = Object.keys(map).map(key => map[key])

      console.log(this.selectForm.schedule)
    },
    doSearch () {
      console.log(456);
      this.searchLoading = true
      this.$nextTick(() => {
        let {
          pageNum,
          pageSize,
          startTime,
          siteId,
          teamId,
          activityId,
          userName
        } = this.searchForm
        this.crtSelectDate = new Date(startTime)
        const currMonthTime = `${format(
          new Date(startTime),
          this.$config.MONTH_FORMAT
        )}`
        if (siteId) {
          siteId = siteId.split('_')[1]
        }
        if (teamId) {
          teamId = teamId.split('_')[1]
        }
        if (activityId) {
          activityId = activityId.split('_')[1]
        }
        ScheduleAPI.week({
          pageNum,
          pageSize,
          currMonthTime,
          siteId,
          teamId,
          activityId,
          userName
        })
          .then(({ data }) => {
            this.searchLoading = false
            this.dataList = []
            if (data.code === 200) {
              this.calendarMonth = new Date(startTime)

              this.total = data.total
              const wrapperList = data.data.agentScheduleVoList
              console.log(wrapperList);
              if (wrapperList && wrapperList.length > 0) {
                const obj = wrapperList.find(o => o.dayScheduleVoList)
                if (
                  obj &&
                  obj.dayScheduleVoList &&
                  obj.dayScheduleVoList.length > 0
                ) {
                  const dayList = obj.dayScheduleVoList
                  this.columns = [
                    ...this.defaultColumns,
                    ...dayList.map(item => {
                      return {
                        renderHeader: (h, params) =>
                          h('div', {}, [
                            h('p', item.date),
                            h('p', getWeekByDate(item.date))
                          ]),
                        align: 'center',
                        minWidth: 110,
                        key: item.date
                      }
                    })
                  ]
                }
                wrapperList.forEach(obj => {
                  const o = {
                    siteName: obj.siteName,
                    activityName: obj.activityName,
                    teamName: obj.teamName,
                    firstName: obj.firstName,
                    map: {
                      "agentId": obj.agentId,
                      //"shiftId": ''
                    }
                  }
                  const p = {}
                  if (
                    obj.dayScheduleVoList &&
                    obj.dayScheduleVoList.length > 0
                  ) {
                    const dayList = obj.dayScheduleVoList
                    dayList.forEach(day => {
                      o[day.date] = day.event
                      p[day.date] = day.shiftId
                      // o.map.agentId = day.agentId
                      //o.map.shiftId = day.shiftId
                    })
                  }
                  this.dataList.push(o)
                  this.selectIdList.push(p)
                })
                console.log(this.dataList);
              }
            }
          })
          .catch(err => {
            console.error('err', err)
            this.searchLoading = false
          })
      })
    },
    onSelectCenter (id, obj, isAuto) {
      this.searchForm.siteId = id
      this.searchForm.teamId = null
      this.searchForm.activityId = null
    },
    onGetOrgErr () {
      this.searchLoading = false
    },
    onSelectSpecialLIne (id, obj, isAuto) {
      this.searchForm.activityId = id
      this.searchForm.teamId = null
    },
    onSelectAdminGroup (id, obj, isAuto) {
      this.searchForm.teamId = id
    },
    onClear () {
      this.searchForm.teamId = null
    },
    onConfirm (obj) {
      console.log('confirm obj:', obj)
      this.searchForm.pageNum = 1
      this.searchForm.siteId = obj.sc.id
      this.searchForm.activityId = obj.sl.id
      this.searchForm.teamId = obj.ag.id
    },
    // 导入班表
    showImportData () {
      this.modalIndex2 = true
    },
    // 导入班表 - 确定
    handleImportData () {
      // setTimeout(() => {
      //     this.modalIndex2 = false;
      // }, 2000);
      //console.log(this.UploadParams);
      //debugger;
      let formData2 = new FormData()
      formData2.append('filename', this.UploadParams.filetest)
      formData2.append('type', this.UploadParams.type)
      //console.log(formData2);
      ScheduleDaysAPI.importScheduleExcel(formData2)
        .then(({ data }) => {
          this.spinShow = false
          if (data.status === 'success') {
            this.$Message.destroy()
            this.$Message.success('导入成功!')
            this.modalIndex2 = false;
            //if (this.spinShow) return false
          }else{
            this.loading = false
            // this.spinShow = false
            // this.$Message.destroy()
          }
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 关闭导入班表
    handleCloseIndex () {
      this.dateType2 = 1
      this.$refs.upload.fileList = []
    },
    // 下载模板
    modelDownload () {
      FileDownloadAPI.dowloadSchedule()
        .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.filetest = file
          this.UploadParams.type = this.dateType2
          // let formData2 = new FormData()
          // formData2.append('filetest', file)
          // formData2.append('type', this.dateType2)
          //console.log(formData2);
          this.spinShow = false
          this.$Message.success('选择文件成功!')
          this.$refs.upload.fileList.push(file)
          // ScheduleDaysAPI.importScheduleExcel(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
    },
    /**
     * @type 导出类型 1:班表，2:工时
     */
    exportExcel (type = 1) {
      const currMonthTime = `${format(
        new Date(this.searchForm.startTime),
        this.$config.MONTH_FORMAT
      )}`
      let siteId
      if (this.searchForm.siteId) {
        siteId = this.searchForm.siteId.split('_')[1]
      } else {
        siteId = null
      }
      let activityId
      if (this.searchForm.activityId) {
        activityId = this.searchForm.activityId.split('_')[1]
      } else {
        activityId = null
      }
      let teamId
      if (this.searchForm.teamId) {
        teamId = this.searchForm.teamId.split('_')[1]
      } else {
        teamId = null
      }
      const param = {
        siteId,
        teamId,
        activityId,
        currMonthTime
      }
      this.exportLoading = type
      const exportName = `${type === 1 ? '班表' : '工时'}_${currMonthTime}.xls`
      console.log(param)
      ExcelAPI.exportExcel({ type, param })
        .then(({ data }) => {
          console.log(data,'654')
          this.exportLoading = 0
          downloadExcel(data, exportName)
        })
        .catch(err => {
          this.exportLoading = 0
          console.error('export err', err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
 .is-selected {
    color: #1989FA;
  }
 .p_comm{
   text-align: center;
   font-size: 14px;
   line-height: 30px;
 }
 /deep/.el-calendar__button-group {
    display: none;
  }
 /deep/.ivu-select-single .ivu-select-selection .ivu-select-placeholder {
    color: #333;
}
/deep/.ivu-select-selection {
  border: none;
}

.setInput{
  width: 200px;
  margin-right: 10px;
}
</style>
