<!-- 非指定换班 -->
<template>
  <div class="non-designation-shift">
    <Row justify="space-between" type="flex">
      <Col>
        <DatePicker
          :clearable="false"
          :disabled="!!this.exportLoading || this.searchLoading"
          :editable="false"
          :options="monthLimit"
          placeholder="请选择月份"
          style="width: 200px"
          type="month"
          v-model="selectMonth"
        ></DatePicker>
        <Button
          :disabled="!!this.exportLoading"
          :loading="searchLoading"
          @click="doSearch"
          style="margin-left: 8px;"
          type="primary"
        >查询</Button>
      </Col>
      <Col v-permission:export="'self-schedule'">
        <Poptip @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>
    <Row>
      <el-calendar v-model="crtSelectDate">
        <template slot="dateCell" slot-scope="{date, data}">
          <calendar-day
            :calendarMonth="calendarMonth"
            :crtDate="crtDate"
            :data="data"
            :date="date"
            :dayObj="matchDay(data.day)"
            @on-select-date="selectDate(date, data.day)"
          ></calendar-day>
        </template>
      </el-calendar>
      <Spin fix size="large" v-if="searchLoading"></Spin>
    </Row>
    <Modal
      :mask-closable="false"
      @on-visible-change="onVisibleChange"
      title="非指定换班 - 发布换班信息"
      v-model="showModal"
      width="400"
    >
      <Form :label-width="100" :model="validateForm" :rules="ruleValidate" ref="formValidate">
        <FormItem label="已选定日期">
          <strong style="font-size: 16px;">{{validateForm.shiftDate}}</strong>
        </FormItem>
        <FormItem label="选择换班意向" prop="eventType">
          <Select
            :disabled="confirmLoading"
            clearable
            style="width: 200px;"
            v-model="validateForm.eventType"
          >
            <Option
              :key="index"
              :value="item.wmShiftId"
              v-for="(item ,index) in SHIFT_TYPE"
            >{{item.wmName}}</Option>
          </Select>
        </FormItem>
      </Form>
      <Alert show-icon type="warning">
        说明：
        <Icon slot="icon" type="ios-bulb-outline"></Icon>
        <template slot="desc">
          <p
            style="text-justify: distribute !important;"
          >1.若选择换班意向，换班请求发出后，如果系统自动匹配成功，会出现在【换班消息列表-被请求的】中，如果没有匹配成功，则会出现在【换班消息列表-我发出的】中；</p>
          <p style="text-justify: distribute !important;">2. 若不选择换班意向，则换班请求会出现在【换班消息列表-公告栏】中，本人不可见；</p>
        </template>
      </Alert>
      <div slot="footer">
        <Button :disabled="confirmLoading" @click="resetForm">重置</Button>
        <Button :loading="confirmLoading" @click="confirmShift" type="primary">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import TradeProposalAPI from '@api/common/tradeProposal'
import ExcelAPI from '@api/sys/excel'
import shiftMixin from '../shift-mixin'
import shiftType from '@/mixin/shiftType'
import { format, isSameMonth } from 'date-fns'
import calendarDay from '../../comp/calendar-day'
import { downloadExcel } from '@lib/download'
export default {
  name: 'non-designation-shift',
  components: { calendarDay },
  mixins: [shiftMixin, shiftType],
  data () {
    return {
      validateForm: {
        shiftDate: null,
        eventType: null
      },
      ruleValidate: {
        eventType: [
          {
            required: false,
            type: 'number',
            trigger: 'change',
            message: '请选择'
          }
        ]
      },
      exportLoading: 0
    }
  },
  props: {
    monthLimit: {
      type: Object,
      required: true
    }
  },
  watch: {
    crtSelectDate (newValue, oldValue) {
      this.validateForm.shiftDate = format(
        this.crtSelectDate,
        this.$config.DATE_FORMAT
      )
      this.crtStateType = this.matchDay(this.validateForm.shiftDate).stateType
      this.crtShiftId = this.matchDay(this.validateForm.shiftDate).shiftId
    }
  },
  methods: {
    selectDate (date, approvalDate) {
      if (
        date.getTime() > this.crtDate.getTime() &&
        isSameMonth(date, this.calendarMonth) &&
        date.getTime() <= this.limitMonthEnd
      ) {
        this.$Message.destroy()
        this.$Message.loading({
          content: '请稍候...',
          duration: 0
        })
        TradeProposalAPI.checkIsShift({ approvalDate }).then(({ data }) => {
          if (data.code === 200) {
            this.$Message.destroy()
            this.showModal = true
          }
        })
      }
    },
    resetForm () {
      this.$refs['formValidate'].resetFields()
    },
    confirmShift () {
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          // const agentId = this.$store.state.user.userCode || ''
          const changeType = 2 // 换班方式 1:指定换班， 2:非指定换班
          // TODO: 接口获取
          const eventType = this.crtShiftId
          const intention = this.validateForm.eventType
          const shiftChangeDate = this.validateForm.shiftDate
          const shiftSchType = this.crtStateType
          TradeProposalAPI.changeShifts({
            // agentId,
            changeType,
            eventType,
            intention,
            shiftChangeDate,
            shiftSchType
          })
            .then(({ data }) => {
              this.confirmLoading = false
              if (data.code === 200) {
                if (data.message) {
                  this.showModal = false
                  this.$Modal.success({
                    title: '匹配提醒',
                    content: data.message
                  })
                } else {
                  this.$Message.success('提交成功')
                  this.shiftObjList = []
                  this.showModal = false
                }
              }
            })
            .catch(err => {
              console.error('err', err)
              this.confirmLoading = false
            })
        }
      })
    },
    onVisibleChange () {
      this.$refs['formValidate'].resetFields()
    },
    /**
     * @type 导出类型 1:班表，2:工时
     */
    exportExcel (type = 1) {
      const currMonthTime = format(
        this.calendarMonth,
        this.$config.MONTH_FORMAT
      )
      const employeeId = this.$store.state.user.userCode || ''
      const param = {
        employeeId,
        currMonthTime
      }
      this.exportLoading = type
      const exportName = `${
        type === 1 ? '班表' : '工时'
      }_${employeeId}_${currMonthTime}.xls`
      ExcelAPI.exportExcel({ type, param })
        .then(({ data }) => {
          this.exportLoading = 0
          downloadExcel(data, exportName)
        })
        .catch(err => {
          this.exportLoading = 0
          console.error('export err', err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
.non-designation-shift {
  /deep/.el-calendar-day {
    .ivu-poptip {
      width: 100%;

      .ivu-poptip-rel {
        width: 100%;
      }
    }
  }
  /deep/.el-calendar__button-group {
    display: none;
  }
}
</style>
