<!-- 指定换班 -->
<template>
  <div class="designation-shift">
    <Row justify="space-between" type="flex">
      <Col>
        <DatePicker
          :clearable="false"
          :disabled="!!this.exportLoading || this.searchLoading"
          :editable="false"
          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="1200"
    >
      <Form :label-width="100" :model="searchForm">
        <Row>
          <Col span="6">
            <FormItem label="已选定日期">
              <strong style="font-size: 16px;">{{searchForm.shiftDate}}</strong>
            </FormItem>
          </Col>
          <!-- <Col offset="6" span="6">
            <FormItem label="是否为还班：">
              <i-switch
                :disabled="shiftSearchLoading || this.crtStateType !== 1"
                v-model="isBackShift"
              >
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
              <span class="back-shift-tip" v-if="this.crtStateType !== 1">非休息日班次无法还班</span>
            </FormItem>
          </Col> -->
        </Row>
        <Row v-if="!isBackShift">
          <Col span="5">
            <FormItem label="姓名">
              <Input
                :disabled="shiftSearchLoading"
                :maxlength="20"
                clearable
                v-model="searchForm.searchCondition"
              ></Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="工号">
              <Input
                :disabled="shiftSearchLoading"
                :maxlength="20"
                clearable
                v-model="searchForm.code"
              ></Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="业务小组">
              <!-- <span slot="label">
                <span style="color: #ed4014;">*&nbsp;</span>业务小组
              </span> -->
              <Select clearable :disabled="shiftSearchLoading" v-model="searchForm.teamId">
                <Option
                  :key="index"
                  :value="item.id"
                  v-for="(item ,index) in TEAM_LIST"
                >{{item.name}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="班次信息">
              <Select :disabled="shiftSearchLoading" clearable v-model="searchForm.shiftId">
                <Option
                  :key="index"
                  :value="item.wmShiftId"
                  v-for="(item ,index) in SHIFT_TYPE"
                >{{item.wmName}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="4" style="text-align: center;">
            <Button :loading="shiftSearchLoading" @click="doInitShiftSearch" type="primary">查询</Button>
            <Button :disabled="shiftSearchLoading" @click="resetForm" style="margin-left: 8px;">重置</Button>
          </Col>
        </Row>
      </Form>
      <Table
        :columns="columns"
        :data="datas"
        :loading="shiftSearchLoading"
        @on-select="onSelect"
        @on-select-cancel="onSelectCancel"
        border
        ref="selection"
      ></Table>
      <br />
      <Page
        :current.sync="searchForm.pageNum"
        :page-size="searchForm.pageSize"
        :total="total"
        @on-change="pageChange"
        show-total
      />
      <div slot="footer">
        <Button
          :disabled="shiftSearchLoading"
          :loading="confirmLoading"
          @click="confirmShift"
          type="primary"
        >提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ScheduleAPI from '@api/common/schedule'
import WfmOrgAPI from '@api/common/wfmOrg'
import TradeProposalAPI from '@api/common/tradeProposal'
import ExcelAPI from '@api/sys/excel'
import shiftMixin from '../shift-mixin'
import shiftType from '@/mixin/shiftType'
import wmTeams from '@/mixin/wmTeams'
import { format, isSameMonth } from 'date-fns'
import cloneDeep from 'lodash/cloneDeep'
import calendarDay from '../../comp/calendar-day'
import { downloadExcel } from '@lib/download'
export default {
  name: 'designation-shift',
  components: { calendarDay },
  mixins: [shiftMixin, shiftType, wmTeams],
  data () {
    return {
      shiftSearchLoading: false,
      isBackShift: false,
      searchForm: {
        shiftDate: null,
        searchCondition: '', // 姓名
        code: '', // 员工编号
        teamId: null, // 业务小组id
        shiftId: null, // 班次id
        pageNum: 1,
        pageSize: 5
      },
      columnsSeatPool: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '业务小组',
          minWidth: 120,
          key: 'teamName'
        },
        {
          title: '组长',
          key: 'teamLeader'
        },
        {
          title: '姓名',
          key: 'lastName'
        },
        {
          title: '工号',
          key: 'employeeId'
        },
        {
          title: '当日班次',
          key: 'event'
        }
      ],
      dataSeatPool: [],
      columnsBackShift: [
        {
          title: '选择',
          key: 'chose',
          width: 70,
          align: 'center',
          render: (h, params) => {
            let obj = params.row
            let flag = false
            if (this.backShiftObj === obj) {
              flag = true
            } else {
              flag = false
            }
            let _this = this
            return h('div', [
              h('Radio', {
                props: {
                  value: flag
                },
                on: {
                  'on-change': () => {
                    _this.backShiftObj = obj
                  }
                }
              })
            ])
          }
        },
        {
          title: '发布日期',
          key: 'createtime',
          width: 140
        },
        {
          title: '班次类型',
          key: 'eventType'
        },
        {
          title: '换班方式',
          key: 'shiftWay'
        },
        {
          title: '换班请求日期',
          key: 'shiftDate'
        },
        {
          title: '换班意向',
          key: 'shiftIntent'
        },
        {
          title: '换班对象业务小组',
          key: 'shiftObjGroup'
        },
        {
          title: '换班对象',
          key: 'shiftObj'
        },
        {
          title: '对象员工编号',
          key: 'objJobNo'
        },
        {
          title: '对象班次',
          key: 'objShiftType'
        },
        {
          title: '状态',
          key: 'shiftState'
        }
      ],
      dataBackShift: [],
      shiftObjList: [], // 非还班，目标列表
      backShiftObj: null,
      total: 0,
      exportLoading: 0
    }
  },
  props: {
    monthLimit: {
      type: Object,
      required: true
    }
  },
  watch: {
    crtSelectDate (newValue, oldValue) {
      this.searchForm.shiftDate = format(
        this.crtSelectDate,
        this.$config.DATE_FORMAT
      )
      this.crtStateType = this.matchDay(this.searchForm.shiftDate).stateType
      this.crtShiftId = this.matchDay(this.searchForm.shiftDate).shiftId
    },
    isBackShift () {
      this.doInitShiftSearch()
    }
  },
  computed: {
    columns () {
      return this.isBackShift ? this.columnsBackShift : this.columnsSeatPool
    },
    datas () {
      return this.isBackShift ? this.dataBackShift : this.dataSeatPool
    }
  },
  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
            this.doInitShiftSearch()
          }
        })
      }
    },
    doInitShiftSearch () {
      this.searchForm.pageNum = 1
      this.clearDatas()
      this.doShiftSearch()
    },
    doShiftSearch () {
      this.$nextTick(() => {
        const agentId = 1
        const employeeId = this.$store.state.user.userCode || ''
        this.shiftSearchLoading = true
        if (!this.isBackShift) {
          const activityId = this.ACID // useless
          //console.log(activityId);
          ScheduleAPI.condition({
            agentId,
            activityId,
            employeeId,
            ...this.searchForm
          })
            .then(({ data }) => {
              this.shiftSearchLoading = false
              if (data.code === 200) {
                this.dataSeatPool = data.data
                // this.dataSeatPool = data.list
                this.$nextTick(() => {
                  if (
                    this.dataSeatPool.length > 0 &&
                    this.shiftObjList.length > 0
                  ) {
                    this.dataSeatPool.forEach(row => {
                      const agentId = row.agentId
                      this.shiftObjList.forEach(obj => {
                        if (obj.targetNo === agentId) {
                          this.$set(row, '_checked', true)
                        }
                      })
                    })
                  }
                })
                this.total = data.total
              }
            })
            .catch(err => {
              console.error('err', err)
              this.shiftSearchLoading = false
            })
        } else {
          TradeProposalAPI.getReturnWorkList({
            agentId,
            employeeId,
            ...this.searchForm
          })
            .then(({ data }) => {
              this.shiftSearchLoading = false
              if (data.code === 200) {
                this.dataBackShift = data.data.list
                this.total = data.data.total
              }
            })
            .catch(err => {
              console.error('err', err)
              this.shiftSearchLoading = false
            })
        }
      })
    },
    resetForm () {
      this.searchForm.searchCondition = ''
      this.searchForm.code = ''
      //this.searchForm.teamId = this.TEAM_LIST[0] ? this.TEAM_LIST[0].id : null
      this.searchForm.teamId = null
      this.searchForm.shiftId = null
    },
    onSelect (selection, row) {
      console.log('selections: ', selection)
      console.log('selected row: ', row)
      if (!this.isBackShift) {
        if (this.shiftObjList.length >= 5) {
          this.$Message.destroy()
          this.$Message.warning('最多选择5个换班对象！')
          this.dataSeatPool.forEach((obj, index) => {
            const agentId = obj.agentId
            if (obj.agentId === row.agentId) {
              this.$set(this.dataSeatPool[index], '_checked', true)
              this.$set(this.dataSeatPool[index], '_checked', false)
            } else {
              this.shiftObjList.forEach(o => {
                if (o.targetNo === agentId) {
                  console.log('double')
                  this.$set(obj, '_checked', false)
                  this.$set(obj, '_checked', true)
                }
              })
            }
          })
        } else {
          this.shiftObjList.push({
            targetEventtype: row.shiftId,
            targetNo: row.agentId,
            targetNumber: row.employeeId,
            targetTeam: row.teamId
          })
          this.dataSeatPool.forEach((item, index) => {
            if (item.agentId === row.agentId) {
              this.$set(this.dataSeatPool[index], '_checked', false)
              this.$set(this.dataSeatPool[index], '_checked', true)
            }
          })
        }
      }
    },
    onSelectCancel (selection, row) {
      console.log('selections: ', selection)
      console.log('canceled row: ', row)
      const canceledAgentId = row.agentId
      if (!this.isBackShift) {
        this.shiftObjList.forEach((obj, index) => {
          if (obj.targetNo === canceledAgentId) {
            this.shiftObjList.splice(index, 1)
          }
        })
        this.dataSeatPool.forEach((item, index) => {
          if (item.agentId === row.agentId) {
            this.$set(this.dataSeatPool[index], '_checked', true)
            this.$set(this.dataSeatPool[index], '_checked', false)
          }
        })
      }
    },
    confirmShift () {
      // 非还班提交
      this.confirmLoading = true
      // const agentId = this.$store.state.user.userCode || ''
      const changeType = 1 // 换班方式 1:指定换班， 2:非指定换班
      // TODO: 接口获取
      const eventType = this.crtShiftId
      const shiftChangeDate = this.searchForm.shiftDate
      const shiftSchType = this.crtStateType
      if (!this.isBackShift) {
        if (this.shiftObjList.length === 0) {
          this.$Message.warning('请选择换班对象')
          this.confirmLoading = false
          return
        }
        const list = cloneDeep(this.shiftObjList)
        TradeProposalAPI.changeShifts({
          // agentId,
          changeType,
          eventType,
          list,
          shiftChangeDate,
          shiftSchType
        })
          .then(({ data }) => {
            this.confirmLoading = false
            if (data.code === 200) {
              this.$Message.success('提交成功')
              this.showModal = false
            }
          })
          .catch(err => {
            console.error('err', err)
            this.confirmLoading = false
          })
      } else {
        if (!this.backShiftObj) {
          this.$Message.warning('请选择还班对象')
          this.confirmLoading = false
          return
        }
        // 还班提交
        const isNeedShift = 2
        const returnId = this.backShiftObj.uuid
        const list = []
        list.push({
          targetNo: this.backShiftObj.targetAgentId,
          targetNumber: this.backShiftObj.objJobNo
        })
        TradeProposalAPI.changeShifts({
          changeType,
          eventType,
          isNeedShift,
          shiftChangeDate,
          returnId,
          list,
          shiftSchType
        })
          .then(({ data }) => {
            this.confirmLoading = false
            if (data.code === 200) {
              this.$Message.success('提交成功')
              this.showModal = false
            }
          })
          .catch(err => {
            console.error('err', err)
            this.confirmLoading = false
          })
      }
    },
    onVisibleChange (visible) {
      console.log('visible', visible)
      if (!visible) {
        this.isBackShift = false
        this.clearDatas()
        this.resetForm()
      } else {
        // 隐藏换班对象列表全选 checkbox
        const selection = this.$refs.selection
        if (selection.$el && selection.$el.querySelector('.ivu-checkbox')) {
          selection.$el.querySelector('.ivu-checkbox').style.display = 'none'
        }
      }
    },
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.clearDatasKeepShiftObjList()
      this.doShiftSearch()
    },
    clearDatas () {
      this.dataSeatPool = []
      this.shiftObjList = []
      this.dataBackShift = []
      this.backShiftObj = null
    },
    // WARN：指定换班（非换班）支持多选，翻页时不清除已选择换班对象列表
    clearDatasKeepShiftObjList () {
      this.dataSeatPool = []
      this.dataBackShift = []
      this.backShiftObj = null
    },
    /**
     * @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>
.designation-shift {
  /deep/.el-calendar-day {
    .ivu-poptip {
      width: 100%;

      .ivu-poptip-rel {
        width: 100%;
      }
    }
  }
  /deep/.el-calendar__button-group {
    display: none;
  }
}
.back-shift-tip {
  display: inline-block;
  margin-left: 8px;
  color: #666;
  &::before {
    content: '*';
    display: inline-block;
    margin-right: 4px;
    line-height: 1;
    font-size: 12px;
    color: #ed4014;
  }
}
</style>
