<!-- 偏好申请 -->
<template>
  <div>
    <Row>
      <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="400"
    >
      <Form
        :label-width="100"
        :model="validateForm"
        :rules="ruleValidate"
        class="prefer-apply-form"
        ref="formValidate"
      >
        <FormItem label="偏好排班日期" prop="eventDate">
          <DatePicker
            :options="dateLimit"
            format="yyyy-MM-dd"
            placeholder="请选择偏好日期"
            type="date"
            v-model="validateForm.eventDate"
          ></DatePicker>
        </FormItem>
        <FormItem label="偏好内容" prop="eventType">
          <Select style="width: 166px;" v-model="validateForm.eventType">
            <Option
              :key="index"
              :value="item.wmShiftId"
              v-for="(item ,index) in SHIFT_TYPE"
            >{{item.wmName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input
            :autosize="{minRows: 4,maxRows: 6}"
            :maxlength="200"
            placeholder="请输入备注"
            type="textarea"
            v-model="validateForm.remark"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="resetForm">重置</Button>
        <Button :loading="confirmLoading" @click="confirmPrefer" 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>
  </div>
</template>

<script>
import commonList from '@/mixin/commonList'
import dateLimit from '@/mixin/dateLimit'
import timeline from '@/mixin/timeline'
import shiftType from '@/mixin/shiftType'
import PreferAPI from '@api/common/prefer'
import cloneDeep from 'lodash/cloneDeep'
import { format, differenceInDays, getTime } from 'date-fns'
export default {
  name: 'perfer-apply',
  mixins: [commonList, timeline, dateLimit, shiftType],
  data () {
    return {
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '发起日期',
          width: 150,
          key: 'createTime',
          tooltip: true
        },
        {
          title: '发起人',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userName : '')
          }
        },
        {
          title: '员工编号',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userCode : '')
          }
        },
        {
          title: '偏好内容',
          render: (h, params) => {
            return h('div', params.row.map ? params.row.map.shiftName : '')
          }
        },
        {
          title: '偏好排班日期',
          render: (h, params) => {
            return h(
              'div',
              format(new Date(params.row.eventDate), this.$config.DATE_FORMAT)
            )
          }
        },
        {
          title: '备注',
          key: 'remark',
          tooltip: true
        },
        {
          title: '状态',
          align: 'center',
          width: 120,
          render: (h, params) => {
            const row = params.row
            return h(
              'Button',
              {
                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, 2)
                  }
                }
              },
              row.map ? row.map.status : ''
            )
          }
        }
      ],
      dataList: [],
      // form
      showModal: false,
      confirmLoading: false,
      validateForm: {
        eventType: null,
        eventDate: null,
        remark: null
      },
      ruleValidate: {
        eventDate: {
          required: true,
          type: 'date',
          message: '请选择',
          trigger: 'change'
        },
        eventType: [
          {
            type: 'number',
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },
  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 {
          PreferAPI.viewList({ ...this.searchForm })
            .then(({ data }) => {
              console.log('data: ', data)
              this.searchLoading = false
              if (data.status === 'success') {
                this.dataList = data.data.list.map(item => {
                  item.createTime = item.map.createTime
                  return item
                })
                this.total = data.data.total
              }
            })
            .catch(err => {
              console.error('err:', err)
              this.searchLoading = false
            })
        }
      })
    },
    onVisibleChange () {
      this.resetForm()
    },
    confirmPrefer () {
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const formData = cloneDeep(this.validateForm)
          formData.eventDate = getTime(formData.eventDate)
          console.log('formData', formData)
          PreferAPI.create({ ...formData })
            .then(({ data }) => {
              this.confirmLoading = false
              if (data.status === 'success') {
                this.showModal = false
                this.$refs['formValidate'].resetFields()
                this.$Message.success('提交偏好申请成功')
                this.doInitSearch()
              }
            })
            .catch(err => {
              console.error('prefer err', err)
              this.confirmLoading = false
            })
        }
      })
    },
    resetForm () {
      this.$refs['formValidate'].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
