<template>
  <div>
    <Row>
      <Input placeholder="班次名称" v-model="searchForm.wmName" style="width: 200px"/>
      <Button
        :loading="searchLoading"
        @click="doInitSearch"
        style="margin-left: 8px;"
        type="primary"
      >查询</Button>
      <Button
        :disabled="searchLoading"
        @click="addModal"
        ghost
        icon="md-add"
        style="margin-left: 8px;"
        type="primary"
        v-permission:add
      >新建</Button>
    </Row>
    <br />
    <Table :columns="columns" :data="list" :loading="searchLoading" @on-sort-change="sortChange" 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="modalTitle"
      v-model="showModal"
      width="600"
    >
      <Form
        :label-width="80"
        :model="validateForm"
        :rules="ruleValidate"
        class="ask-leave-form"
        ref="formValidate"
      >
        <FormItem label="所属中心" prop="wmSiteId">
          <Select style="width: 200px;" v-model="validateForm.wmSiteId" :disabled="isDisabled">
            <Option
              :key="index"
              :value="item.wmSiteId"
              v-for="(item ,index) in SITE_ITEM"
            >{{item.wmName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="班次种类" prop="wmTypeId">
          <Select style="width: 200px;" v-model="validateForm.wmTypeId" :disabled="isDisabled">
            <Option
              :key="index"
              :value="item.wmTypeId"
              v-for="(item ,index) in TYPE_ITEM"
            >{{item.wmName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="班次名称" prop="wmName">
          <Input style="width: 200px;" v-model="validateForm.wmName" :disabled="isDisabled"/>
        </FormItem>
        <FormItem label="班次工时" prop="hours">
          <Input style="width: 200px;" v-model="validateForm.hours" :disabled="isDisabled"/>
        </FormItem>
        <FormItem label="开始时间" prop="startTime">
          <Time-picker
            :disabled="isDisabled"
            format="HH:mm"
            value-format="HH:mm"
            type="time"
            placeholder="请选择开始时间"
            style="width: 200px"
            v-model="validateForm.startTime"
            confirm
          ></Time-picker>
        </FormItem>
        <FormItem label="结束时间" prop="endTime">
          <Time-picker
            :disabled="isDisabled"
            format="HH:mm"
            type="time"
            placeholder="请选择结束时间"
            style="width: 200px"
            v-model="validateForm.endTime"
            confirm
          ></Time-picker>
        </FormItem>
        <FormItem label="备注" prop="wmRemarks">
          <Input
            :disabled="isDisabled"
            :autosize="{minRows: 4,maxRows: 6}"
            :maxlength="200"
            placeholder="备注..."
            type="textarea"
            v-model="validateForm.wmRemarks"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <div v-if="showFooter">
        <Button @click="resetForm">重置</Button>
        <Button :loading="confirmLoading" @click="confirmComplaint" type="primary">确定</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import showPoptip from '@/mixin/showPoptip'
import dateLimit from '@/mixin/dateLimit'
import timeline from '@/mixin/timeline'
import ShiftsAPI from '@api/common/shifts'
import WmSitesAPI from '@api/common/wmSites'
import WmShiftsTypeAPI from '@api/common/wmShiftsType'
import TimeoffTypeAPI from '@api/common/timeoffType'
import FileAPI from '@api/sys/file'
import { addHours, addMinutes, differenceInDays, getTime } from 'date-fns'
import COMMEN_CONFIG from '@conf'
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'shift-setting',
  mixins: [ timeline, dateLimit, showPoptip],
  data () {
    return {
      SITE_ITEM: [],
      TYPE_ITEM: [],
      searchLoading: false,
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 150,
          align: 'center'
        },
        {
          title: '所属中心',
          //width: 150,
          key: 'siteName'
        },
        {
          title: '班次种类',
          //width: 150,
          key: 'shiftType',
          sortable: 'custom',
        },
        {
          title: '班次名称',
          key: 'wmName',
          sortable: 'custom'
        },
        {
          title: '班次时间',
          key: 'shiftTime',
          tooltip: true
        },
        {
          title: '班次工时',
          key: 'hours',
          //width: 140
          // tooltip: true
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            //console.log(params);
            return h('div', [
              h(
                'Button',
                {
                  // directives: [
                  //   {
                  //     name: 'permission',
                  //     arg: 'view',
                  //     value: 'trajectory-model'
                  //   }
                  // ],
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.infoView(params.row)
                    }
                  }
                },
                '查看'
              ),
              h(
                'Button',
                {
                  // directives: [
                  //   {
                  //     name: 'permission',
                  //     arg: 'edit',
                  //     value: 'trajectory-model'
                  //   }
                  // ],
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.infoEdit(params.row)
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定删除该行信息？'
                  },
                  on: {
                    'on-ok': () => {
                      this.infoRemove(params.row)
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      // directives: [
                      //   {
                      //     name: 'permission',
                      //     arg: 'delete',
                      //     value: 'trajectory-model'
                      //   }
                      // ],
                      props: {
                        type: 'warning',
                        size: 'small'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ])
          }
        }
      ],
      list: [],
      searchForm: {
        pageNum: 1,
        // pageSize: this.$config.PAGE_SIZE,
        pageSize: 20,
        wmName: null,
        orderBy: null
      },
      total: 0,
      current: 0,
      // form
      showModal: false,
      confirmLoading: false,
      showFooter: true,
      modalTitle: '新增班次',
      isDisabled: false,
      validateForm: {
        startTime: '',
        endTime: '',
        hours: '',
        wmName: '',
        wmRemarks: '',
        wmSiteId: '',
        wmTypeId: '',
        wmShiftId: ''
      },
      ruleValidate: {
        // map: [
        //     {
        //       //type: 'number',
        //       required: true,
        //       message: '请选择',
        //       //trigger: 'blur'
        //     }
        // ],
        hours: [
          {
            required: true,
            message: '请填写',
            //trigger: 'change'
          }
        ],
        startTime: [
          {
            required: true,
            message: '请选择',
            //trigger: 'change'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择',
            //trigger: 'change'
          }
        ],
        wmSiteId: [
          {
            required: true,
            message: '请选择',
            //trigger: 'change'
          }
        ],
        wmTypeId: [
          {
            required: true,
            message: '请选择',
            //trigger: 'change'
          }
        ],  
        wmName: [
          {
            required: true,
            message: '请填写',
            //trigger: 'change'
          }
        ],
        wmRemarks: [
          {
            required: true,
            message: '不能为空',
            //trigger: 'change'
          }
        ]
      },
      deepCloneData: {}
    }
  },
  created () {
    this.doInitSearch()
    // 获取所在重中心
    WmSitesAPI.listOwer().then(({ data }) => {
      //console.log('data', data)
      if (data.code === 200) {
        if (data.data && data.data.length > 0) {
          this.SITE_ITEM = data.data
        }
      }
    })

    // 获取班次类型
    WmShiftsTypeAPI.list().then(({ data }) => {
      console.log('data', data)
      if (data.code === 200) {
        if (data.data && data.data.length > 0) {
          this.TYPE_ITEM = data.data
        }
      }
    })
  },
  methods: {
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.doSearch()
    },
    sortChange({ column, key, order }){
      // console.log('column',column);
      // console.log('key',key);
      // console.log('order',order);
      //TABLE_SORT
      if(key == 'shiftType'){
        if(order == 'desc'){
          this.searchForm.orderBy = COMMEN_CONFIG.TABLE_SORT[3]
          this.doSearch()
        }else{
          this.searchForm.orderBy = COMMEN_CONFIG.TABLE_SORT[2]
          this.doSearch()
        }
      }else if(key == 'wmName'){
        if(order == 'desc'){
          this.searchForm.orderBy = COMMEN_CONFIG.TABLE_SORT[1]
          this.doSearch()
        }else{
          this.searchForm.orderBy = COMMEN_CONFIG.TABLE_SORT[0]
          this.doSearch()
        }
      }
    },
    doSearch () {
      this.searchLoading = true
      //_this = this
      // this.$nextTick(() => {
        console.log(this.searchForm);
        ShiftsAPI.shiftList({ ...this.searchForm })
            .then(({ data }) => {
              //console.log(data);
              this.searchLoading = false
              if (data.status === 'success') {
                this.list = data.data.list.map(item => {
                  item.wmName = item.wmName
                  item.hours = item.map.hours
                  item.siteName = item.map.siteName
                  item.shiftTime = item.map.shiftTime
                  item.shiftType = item.map.shiftType
                  return item
                })
                //this.list = data.data.list
                this.total = data.data.total
              }
            })
            .catch(err => {
              console.error('err:', err)
              this.searchLoading = false
            })
      // })
    },
    onVisibleChange(){
      this.$refs['formValidate'].resetFields()
      //this.resetForm()
    },
    confirmComplaint () {
      //console.log(this.validateForm);
      // debugger;
      this.$refs['formValidate'].validate(valid => {
        console.log(valid);
        if (valid) {
          this.confirmLoading = true
          var params = {}
          params.map = {}
          params.map.startTime = this.validateForm.startTime
          params.map.endTime = this.validateForm.endTime
          params.map.hours = this.validateForm.hours

          params.wmName = this.validateForm.wmName
          params.wmRemarks = this.validateForm.wmRemarks
          params.wmSiteId = this.validateForm.wmSiteId
          params.wmTypeId = this.validateForm.wmTypeId
          if(this.modalTitle != '编辑班次') {
            this.validateForm.wmShiftId = ''
          }
          params.wmShiftId = this.validateForm.wmShiftId
          console.log(params);
          ShiftsAPI.saveShift(params)
            .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('err', err)
              this.confirmLoading = false
            })
        }
      })
    },
    resetForm () {
      this.validateForm = cloneDeep(this.deepCloneData)
      //this.$refs['formValidate'].resetFields()
    },
    addModal(){//新建班次
      this.modalTitle = '新增班次'
      this.showModal = true
      this.isDisabled = false // 指标是否可编辑
      this.showFooter = true // 是否显示底部操作按钮
    },
    // 表格操作-查看
    infoView (row) {
      let infoId = row.wmShiftId
      this.viewLoading = true
      this.modalTitle = '查看班次'
      ShiftsAPI.info({'wmShiftId':infoId})
        .then(({ data }) => {
          console.log("data",data);
          this.viewLoading = false
          if (data.status === 'success') {
            this.showModal = true
            this.isDisabled = true // 指标是否可编辑
            this.showFooter = false // 是否显示底部操作按钮
            let oj ={}
            oj.startTime = data.data.map.startTime
            oj.endTime = data.data.map.endTime
            oj.hours = data.data.map.hours
            oj.wmName = data.data.wmName
            oj.wmRemarks = data.data.wmRemarks
            oj.wmSiteId = data.data.wmSiteId
            oj.wmTypeId = data.data.wmTypeId
            this.validateForm = oj
            this.deepCloneData = cloneDeep(oj)
            //console.log(this.validateForm);
          }
        })
        .catch(err => {
          console.error(err)
          this.viewLoading = false
        })
    },
    // 表格操作-编辑
    infoEdit (row) {
      this.editLoading = true
      this.modalTitle = '编辑班次'
      let infoId = row.wmShiftId
      console.log('wmShiftId',infoId)
      ShiftsAPI.info({'wmShiftId':infoId})
        .then(({ data }) => {
          console.log("data",data);
          this.viewLoading = false
          if (data.status === 'success') {
            this.showModal = true
            this.isDisabled = false // 指标是否可编辑
            this.showFooter = true // 是否显示底部操作按钮
            let oj ={}
            oj.startTime = data.data.map.startTime
            oj.endTime = data.data.map.endTime
            oj.hours = data.data.map.hours
            oj.wmName = data.data.wmName
            oj.wmRemarks = data.data.wmRemarks
            oj.wmSiteId = data.data.wmSiteId
            oj.wmTypeId = data.data.wmTypeId
            oj.wmShiftId = infoId
            this.validateForm = oj
            this.deepCloneData = cloneDeep(oj)
            console.log(this.validateForm);
          }
        })
        .catch(err => {
          console.error(err)
          this.viewLoading = false
        })
    },
    // 表格操作-删除
    infoRemove (row) {
      let infoId = row.wmShiftId.toString()
      this.deleteLoading = true
      ShiftsAPI.delete({'wmShiftId':infoId})
        .then(({ data }) => {
          this.deleteLoading = false
          if (data.status === 'success') {
            this.$Message.destroy()
            this.$Message.success('删除成功!')
            this.doInitSearch()
          }
        })
        .catch(err => {
          console.error('err: ', err)
          this.deleteLoading = false
        })
    },
  }
}
</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>
