<template>
  <div>
    <Row>
      <!-- <Alert
        class="warnInfo"
        show-icon
        style="width: 200px;margin-right:10px;display: inline-block;"
        type="warning"
      >
        总年假时长(小时)：
        <strong>{{totalTimeForLeave}}</strong>
      </Alert> -->
      <DatePicker
        :clearable="false"
        :editable="false"
        placeholder="请选择月份"
        style="width: 200px"
        type="month"
        v-model="searchDateRange"
      ></DatePicker>
      <Button
        :loading="searchLoading"
        @click="doInitSearch"
        style="margin-left: 8px;"
        type="primary"
      >查询</Button>
      <Button
        :disabled="searchLoading"
        @click="showModal = true"
        ghost
        icon="md-add"
        style="margin-left: 8px;"
        type="primary"
        v-permission:add
      >新建</Button>
    </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="600"
    >
      <Form
        :label-width="80"
        :model="validateForm"
        :rules="ruleValidate"
        class="ask-leave-form"
        ref="formValidate"
      >
        <FormItem label="请假类型" prop="type">
          <Select style="width: 200px;" v-model="validateForm.type">
            <Option
              :key="index"
              :value="item.wmTimeoffTypeId"
              v-for="(item ,index) in LEAVE_TYPE"
            >{{item.wmName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="请假日期" prop="applyDateValidate">
          <Row>
            <FormItem prop="applyDateRange" style="display: inline-block;">
              <DatePicker
                :options="dateLimitToday"
                format="yyyy-MM-dd"
                placeholder="请选择请假日期"
                style="width: 200px"
                type="daterange"
                v-model="validateForm.applyDateRange"
              ></DatePicker>
            </FormItem>
            <Alert
              class="warnInfo"
              show-icon
              style="width: 200px;margin-left:10px;display: inline-block;"
              type="warning"
              v-if="validateForm.type ===YEAR_LEAVE_ID"
            >
              剩余年假时长(小时)：
              <strong>{{leftTimeForLeave}}</strong>
            </Alert>
          </Row>
        </FormItem>
        <FormItem prop="applyTimeValidate">
          <div slot="label">
            <span
              style="color: #ed4014;"
              v-if="!this.disabledTimePickerByDate && !this.isFullDay"
            >*&nbsp;</span>请假时间
          </div>
          <InputNumber
            :disabled="disabledTimePickerByDate || isFullDay"
            :editable="false"
            :max="23"
            :min="0"
            style="width: 60px;"
            v-model="startTimeHour"
          ></InputNumber>&nbsp;时&nbsp;
          <InputNumber
            :disabled="disabledTimePickerByDate || isFullDay"
            :editable="false"
            :max="30"
            :min="0"
            :step="30"
            style="width: 60px;"
            v-model="startTimeMinute"
          ></InputNumber>&nbsp;分&nbsp;
          <span>&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;</span>
          <InputNumber
            :disabled="disabledTimePickerByDate || isFullDay"
            :editable="false"
            :max="24"
            :min="endTimeHourMin"
            :value="0"
            style="width: 60px;"
            v-model="endTimeHour"
          ></InputNumber>&nbsp;时&nbsp;
          <InputNumber
            :disabled="disabledTimePickerByDate || isFullDay"
            :editable="false"
            :max="endTimeMinuteMax"
            :min="0"
            :step="30"
            style="width: 60px;"
            v-model="endTimeMinute"
          ></InputNumber>&nbsp;分&nbsp;
          <span>&nbsp;&nbsp;</span>
          <Checkbox :disabled="disabledTimePickerByDate" v-model="isFullDay">全天</Checkbox>
        </FormItem>
        <!-- <FormItem label="附件">
          <div :key="index" class="upload-list" v-for="(item, index) in uploadList">
            <template v-if="item.status === 'finished'">
            <img :src="item.url" />
            <div class="upload-list-cover">
              <Icon @click.native="handleView(item.url)" type="ios-eye-outline"></Icon>
              <Icon @click.native="handleRemove(item)" type="ios-trash-outline"></Icon>
            </div>
            </template>
            <template v-else>
              <Progress :percent="item.percentage" hide-info v-if="item.showProgress"></Progress>
            </template>
          </div>
          <Upload
            :before-upload="handleBeforeUpload"
            :format="['jpg','jpeg','png','JPG','JPEG','PNG']"
            :max-size="1024"
            :show-upload-list="false"
            action
            ref="upload"
            style="display: inline-block;width:58px;"
            type="drag"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon size="20" type="ios-camera"></Icon>
            </div>
          </Upload>
        </FormItem> -->
        <FormItem label="请假原因" prop="reason">
          <Input
            :autosize="{minRows: 4,maxRows: 6}"
            :maxlength="200"
            placeholder="请输入请假原因"
            type="textarea"
            v-model="validateForm.reason"
          ></Input>
        </FormItem>
      </Form>
      <Alert show-icon type="warning">
        说明：
        <Icon slot="icon" type="ios-bulb-outline"></Icon>
        <template slot="desc">
          <p>1. 座席申请半天假，日期选择同一天，再选择请假时间段；</p>
          <p>2. 座席申请全天假，日期选择同一天，并勾选全天；</p>
          <p>3. 座席申请多天假，日期选择为多天，时间选择框置灰，默认为申请连续的全天假。</p>
        </template>
      </Alert>
      <div slot="footer">
        <Button @click="resetForm">重置</Button>
        <Button :loading="confirmLoading" @click="confirmLeave" type="primary">提交</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" :title="`请假申请状态 - ${timelineStateDesc}`" v-model="showTimeline">
      <Timeline>
        <custom-timeline-item
          :date="formatDate(item.approvalTime)"
          :key="index"
          :passed="index !== timelineList.length - 1 || timelineState !== 1"
          :roleName="item.map.linkType"
          :state="item.map.status"
          :username="item.map.linkOperateName"
          v-for="(item, index) in timelineList"
        />
      </Timeline>
      <div slot="footer">
        <Button @click="showTimeline=false" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" title="查看附件" v-model="visible">
      <img :src="imgSrc" style="width: 100%" v-if="visible" />
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import commonList from '@/mixin/commonList'
import dateLimit from '@/mixin/dateLimit'
import timeline from '@/mixin/timeline'
import LeaveAPI from '@api/common/leave'
import TimeoffTypeAPI from '@api/common/timeoffType'
import FileAPI from '@api/sys/file'
import { addHours, addMinutes, differenceInDays, getTime } from 'date-fns'
export default {
  name: 'ask-leave',
  mixins: [commonList, timeline, dateLimit],
  data () {
    return {
      LEAVE_TYPE: [],
      YEAR_LEAVE_ID: -1,
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '发起日期',
          width: 150,
          key: 'createTime'
        },
        {
          title: '发起人',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userName : '')
          }
        },
        {
          title: '工号',
          key: 'userCode',
          tooltip: true
        },
        {
          title: '请假时间',
          key: 'requestTime',
          width: 140
          // tooltip: true
        },
        {
          title: '请假类型',
          render: (h, params) => {
            return h('div', params.row.map ? params.row.map.timeoffType : '')
          }
        },
        {
          title: '请假时数',
          key: 'times'
        },
        {
          title: '请假天数',
          key: 'days'
        },
        // {
        //   title: '附件',
        //   key: 'files',
        //   width: 150,
        //   render: (h, params) => {
        //     if (params.row.map) {
        //       const files = params.row.map.fileList
        //       if (files) {
        //         return h(
        //           'div',
        //           {},
        //           files.map(img =>
        //             h('img', {
        //               style: {
        //                 width: '36px',
        //                 height: '36px',
        //                 cursor: 'pointer',
        //                 padding: '2px'
        //               },
        //               attrs: {
        //                 src: FileAPI.show(img.uuid)
        //               },
        //               props: {
        //                 shape: 'square'
        //               },
        //               on: {
        //                 click: () => {
        //                   this.handleView(FileAPI.show(img.uuid))
        //                 }
        //               }
        //             })
        //           )
        //         )
        //       }
        //     }
        //   }
        // },
        {
          title: '请假原因',
          key: 'reason',
          tooltip: true
        },
        {
          title: '状态',
          align: 'center',
          width: 120,
          render: (h, params) => {
            const row = params.row
            return h(
              'Button',
              {
                directives: [
                  {
                    name: 'show',
                    value: row.map && row.map.status
                  }
                ],
                props: {
                  type: 'primary',
                  ghost: true,
                  size: 'small'
                },
                on: {
                  click: () => {
                    const relatedId = row.uuid
                    this.timelineState = row.status
                    this.timelineStateDesc = row.map ? row.map.status : ''
                    this.showTimelineList(relatedId, 3)
                  }
                }
              },
              row.map ? row.map.status : ''
            )
          }
        }
      ],
      dataList: [],
      // form
      showModal: false,
      confirmLoading: false,
      validateForm: {
        type: '',
        reason: '',
        applyDateValidate: [],
        applyDateRange: []
      },
      ruleValidate: {
        type: [
          {
            type: 'number',
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        applyDateValidate: [
          {
            type: 'array',
            required: true,
            message: ' '
          }
        ],
        applyDateRange: [
          {
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!value[0] || !value[1]) {
                callback(new Error('请选择'))
              } else {
                callback()
              }
            }
          }
        ],
        applyTimeValidate: [
          {
            trigger: 'change',
            validator: (rule, value, callback) => {
              this.$nextTick(() => {
                if (this.requirePickTime) {
                  callback(new Error('请选择'))
                } else {
                  callback()
                }
              })
            }
          }
        ],
        reason: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ]
      },
      // form upload
      imgSrc: '',
      visible: false,
      uploadList: [],
      isFullDay: true,
      // time limit
      startTimeHour: 0,
      startTimeMinute: 0,
      endTimeHour: 0,
      endTimeHourMin: 0,
      endTimeMinute: 0,
      endTimeMinuteMax: 30,
      leftTimeForLeave: 0,
      totalTimeForLeave: 0
    }
  },
  created () {
    // 获取请假类型字典
    TimeoffTypeAPI.viewList().then(({ data }) => {
      console.log('data', data)
      if (data.code === 200) {
        this.LEAVE_TYPE = data.data
        if (data.data && data.data.length > 0) {
          for (let key in data.data) {
            let tmp = data.data[key]
            if (tmp.wmName === '年假') {
              this.YEAR_LEAVE_ID = tmp.wmTimeoffTypeId
              break
            }
          }
        }
      }
    })
  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
  },
  computed: {
    requirePickTime () {
      return (
        !this.disabledTimePickerByDate &&
        !this.isFullDay &&
        this.startTimeHour === 0 &&
        this.startTimeMinute === 0 &&
        this.endTimeHour === 0 &&
        this.endTimeMinute === 0
      )
    },
    disabledTimePickerByDate: {
      get () {
        const startDate = this.validateForm.applyDateRange[0]
        const endDate = this.validateForm.applyDateRange[1]
        if (startDate && endDate) {
          if (differenceInDays(endDate, startDate) < 1) {
            return false
          }
        }
        return true
      },
      set (newValue, oldValue) {
        console.log(newValue)
      }
    }
  },
  watch: {
    'validateForm.applyDateRange' (newValue, oldValue) {
      this.validateForm.applyDateValidate = newValue
      const startDate = this.validateForm.applyDateRange[0]
      const endDate = this.validateForm.applyDateRange[1]
      if (startDate && endDate) {
        if (differenceInDays(endDate, startDate) < 1) {
          this.isFullDay = false
        } else {
          this.isFullDay = true
        }
      }
    },
    isFullDay (newValue, oldValue) {
      if (newValue) {
        this.resetTimeSelector()
      }
    },
    startTimeHour (newValue, oldValue) {
      if (oldValue === this.endTimeHour && newValue > oldValue) {
        this.endTimeHour = newValue
      }
      if (newValue === this.endTimeHour) {
        if (this.startTimeMinute === 0) {
          this.endTimeMinute = 30
        } else {
          this.endTimeHour = newValue + 1
        }
      }
      if (this.startTimeMinute === 30) {
        this.endTimeHourMin = newValue + 1
      } else {
        this.endTimeHourMin = newValue
      }
    },
    startTimeMinute (newValue, oldValue) {
      if (newValue === 30) {
        this.endTimeHourMin = this.startTimeHour + 1
        if (this.startTimeHour === this.endTimeHour) {
          this.endTimeHour = this.startTimeHour + 1
        }
        if (this.startTimeHour === 23) {
          this.endTimeMinute = 0
          this.endTimeMinuteMax = 0
        } else {
          this.endTimeMinuteMax = 30
        }
      } else {
        this.endTimeHourMin = this.startTimeHour
      }
    },
    endTimeHour (newValue) {
      if (newValue === this.startTimeHour) {
        this.endTimeMinute = 30
        this.startTimeMinute = 0
      }
      if (newValue === 24) {
        this.endTimeMinute = 0
        this.endTimeMinuteMax = 0
      } else {
        this.endTimeMinuteMax = 30
      }
    },
    endTimeMinute (newValue) {
      if (this.startTimeHour === this.endTimeHour) {
        if (newValue === 0 && this.startTimeHour > 0) {
          this.startTimeHour = this.endTimeHour - 1
          this.startTimeMinute = 30
        }
      }
    }
  },
  methods: {
    doSearch () {
      this.searchLoading = true
      this.$nextTick(() => {
        const dateRange = differenceInDays(
          new Date(this.searchForm.endTime),
          new Date(this.searchForm.startTime)
        )
        if (dateRange > this.$config.DATE_RANGE_QUARTER) {
          this.$Message.warning(
            `日期范围不能超过${this.$config.DATE_RANGE_QUARTER}天`
          )
        } else {
          LeaveAPI.viewList({ ...this.searchForm })
            .then(({ data }) => {
              this.searchLoading = false
              if (data.status === 'success') {
                if (data.data.totalYearHour !== undefined) {
                  this.totalTimeForLeave = data.data.totalYearHour
                }
                if (data.data.remainYearHour !== undefined) {
                  this.leftTimeForLeave = data.data.remainYearHour
                }

                this.dataList = data.data.pageInfo.list.map(item => {
                  item.createTime = item.map.createTime
                  item.requestTime = item.map.requestTime
                  item.userCode = item.map.userCode
                  return item
                })
                this.total = data.data.pageInfo.total
              }
            })
            .catch(err => {
              console.error('err:', err)
              this.searchLoading = false
            })
        }
      })
    },
    onVisibleChange () {
      this.resetForm()
    },
    confirmLeave () {
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          let formData = new FormData()
          formData.append('type', this.validateForm.type)
          if (this.disabledTimePickerByDate || this.isFullDay) {
            formData.append(
              'starttime',
              getTime(this.validateForm.applyDateRange[0])
            )
            formData.append(
              'endtime',
              getTime(this.validateForm.applyDateRange[1]) + 86400000
            )
          } else {
            formData.append(
              'starttime',
              getTime(
                addMinutes(
                  addHours(
                    this.validateForm.applyDateRange[0],
                    Number(this.startTimeHour)
                  ),
                  Number(this.startTimeMinute)
                )
              )
            )
            formData.append(
              'endtime',
              getTime(
                addMinutes(
                  addHours(
                    this.validateForm.applyDateRange[1],
                    Number(this.endTimeHour)
                  ),
                  Number(this.endTimeMinute)
                )
              )
            )
          }
          // formData.append('file_content_type', 'jpg,png')
          // this.uploadList.forEach((item, index) => {
          //   formData.append(`file${index}`, item)
          //   formData.append(`file${index}_file_max_size`, 5)
          // })
          formData.append('reason', this.validateForm.reason)
          this.submitLeave(formData)
        }
      })
    },
    submitLeave (formData) {
      this.confirmLoading = true
      LeaveAPI.create(formData)
        .then(({ data }) => {
          this.confirmLoading = false
          if (data.status === 'success') {
            if (data.message) {
              this.$Modal.confirm({
                title: '提示',
                content: '<p style="color:green">' + data.message + '</p>',
                onOk: () => {
                  formData.append('skipCheck', 1)
                  this.submitLeave(formData)
                },
                onCancel: () => {}
              })
            } else {
              this.showModal = false
              this.$Message.success('提交请假申请成功')
              this.doInitSearch()
            }
          }
        })
        .catch(err => {
          console.error('leave err', err)
          this.confirmLoading = false
        })
    },
    resetForm () {
      this.$refs['formValidate'].resetFields()
      this.$refs.upload.fileList.splice(0, this.$refs.upload.fileList.length)
      this.resetTimeSelector()
    },
    handleView (name) {
      this.imgSrc = name
      this.visible = true
    },
    handleRemove (file) {
      const fileList = this.$refs.upload.fileList
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1)
    },
    handleBeforeUpload (file) {
      console.log('file ', file)
      if (this.uploadList.length >= this.$config.LEAVE_ATTACHMENT_MAX_COUNT) {
        this.$Message.warning(
          `最多添加${this.$config.LEAVE_ATTACHMENT_MAX_COUNT}个附件`
        )
      } else {
        if (!new RegExp('.(jpg|jpeg|png)|JPG|JPEG|PNG$').test(file.name)) {
          this.$Message.warning('请上传jpg或png格式文件')
        } else if (
          file.size / 1024 / 1024 >
          this.$config.LEAVE_ATTACHMENT_MAX_SIZE
        ) {
          this.$Message.warning(
            `文件大小不要超过${this.$config.LEAVE_ATTACHMENT_MAX_SIZE}M`
          )
        } else {
          let reader = new FileReader()
          reader.onprogress = e => {
            console.log('progress', e)
          }
          reader.onerror = e => {
            // this.$refs.upload.fileList.pop()
          }
          reader.readAsDataURL(file)
          reader.onloadend = e => {
            console.log('file reader', reader)
            file.url = reader.result
            this.$refs.upload.fileList.push(file)
            this.$nextTick(() => {
              console.log(
                'uploadList ',
                Object.prototype.toString.call(this.uploadList[0])
              )
            })
          }
        }
      }
      return false
    },
    resetTimeSelector () {
      this.startTimeHour = 0
      this.startTimeMinute = 0
      this.endTimeHour = 0
      this.endTimeHourMin = 0
      this.$nextTick(() => {
        this.endTimeMinute = 0
      })
      this.endTimeMinuteMax = 0
    }
  }
}
</script>

<style lang="less" scoped>
.upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.upload-list img {
  width: 100%;
  height: 100%;
}
.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.upload-list:hover .upload-list-cover {
  display: block;
}
.upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.warnInfo {
  padding: 8px 5px 8px 38px;
}
</style>
