<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" append-to-body @close="closeDialog">
      <!--查询结果Table显示-->
      <div style="margin-bottom: 30px">
        <el-row class="table-title">
          <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col>
          <el-col :span="12" :offset="6" class="edit_btns">
            <el-button :disabled="remarksTypeList.length === 0 || listLoading" class="edit_btn" size="small" @click="add">添加备注</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="listLoading" :data="list" class="table" border>
          <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row[column.value] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注操作" align="center" width="160">
            <template slot-scope="scope">
              <el-button :disabled="!hasPerm('/remarks/add')" type="text" @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="addShow" >
        <el-form ref="dataForm" :rules="rules" :model="remarksForm" label-well-code="right" label-width="100px">
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-form-item label="备注类型" prop="remarksType">
                <el-select v-model="remarksForm.remarksType" placeholder="必填" clearable @change="selectRemarksType">
                  <el-option v-for="item in remarksTypeList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注信息" prop="remarks">
                <el-select v-model="remarksForm.remarks" placeholder="必填" clearable>
                  <el-option v-for="item in remarksList" :key="item.value" :label="item.name" :value="item.name"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="remarksForm.remarksType === '5' && remarksForm.remarks!='请假-哺乳假'" type="flex" justify="center">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="beginDate">
                <el-date-picker
                  v-model="remarksForm.beginDate"
                  :picker-options="beginDateOptions"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="remarksForm.endDate"
                  :picker-options="endDateOptions"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="remarksForm.remarks === '请假-哺乳假'" type="flex" justify="center">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="breastfeedBeginDate">
                <el-date-picker
                  v-model="remarksForm.breastfeedBeginDate"
                  :picker-options="beginDateOptions"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止日期" prop="breastfeedEndDate">
                <el-date-picker
                  v-model="remarksForm.breastfeedEndDate"
                  :picker-options="endDateOptions"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="截止日期"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="remarksForm.remarks === '请假-哺乳假'" type="flex" >
            <el-col :span="12">
              <el-form-item label="哺乳假用于" prop="breastfeedType" label-width="100px">
                <el-select v-model="remarksForm.breastfeedType" :disabled="breastfeedTypeDisabled" placeholder="必填" clearable>
                  <el-option v-for="item in breastfeedTypeList" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="remarksForm.remarks === '其他原因'" label="其他原因" prop="other">
            <el-input v-model="remarksForm.other" :maxlength="200" type="textarea" placeholder="请输入‘其他原因’" show-word-limit/>
          </el-form-item>
          <el-form-item v-if="remarksForm.remarks === '其他原因'" prop="onBusiness">
            <el-radio v-model="remarksForm.onBusiness" label="1">因公</el-radio>
            <el-radio v-model="remarksForm.onBusiness" label="0">因私</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :disabled="saveBtnDisabeld" type="primary" @click="saveData">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRemarks, getRemarksList, getEnabledTypeList, delRemarks } from '@/api/attendance'

export default {
  name: 'EditRemarks',
  data() {
    const validateOtherReason = (rule, value, callback) => {
      const reg = /[:;：；]/im
      if (value !== '' && value.length > 0) {
        if (reg.test(value)) {
          callback(new Error('不能含有冒号或分号'))
        } else {
          if (value.indexOf('哺乳假') !== -1 || value.indexOf('年假') !== -1 || value.indexOf('事假') !== -1 || value.indexOf('病假') !== -1 ||
            value.indexOf('婚假') !== -1 || value.indexOf('丧假') !== -1 || value.indexOf('工伤') !== -1 || value.indexOf('探亲假') !== -1 ||
            value.indexOf('生育假') !== -1) {
            callback(new Error('请在“备注信息”下拉框里选择请假类型'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('其他原因不能为空'))
      }
    }
    return {
      listLoading: true,
      saveBtnDisabeld: false,
      edited: false,
      curDate: '',
      beginDateOptions: {
        disabledDate: this.disabledBeginDate
      },
      endDateOptions: {
        disabledDate: this.disabledEndDate
      },
      addShow: false,
      checkList: [],
      dialogFormVisible: false, // 对话框是否显示
      remarksForm: {
        id: '',
        reportId: '',
        personId: '',
        remarksType: '',
        remarks: '',
        beginDate: '',
        endDate: '',
        breastfeedType: '',
        breastfeedBeginDate: '',
        breastfeedEndDate: '',
        other: '',
        onBusiness: ''
      }, // 表单
      title: '', // 表头显示标题
      rules: {
        remarksType: [{ required: true, message: '备注类型不能为空', trigger: ['change'] }],
        remarks: [{ required: true, message: '备注信息不能为空', trigger: ['change'] }],
        beginDate: [{ required: true, message: '请选择开始日期', trigger: ['blur'] }],
        breastfeedBeginDate: [{ required: true, message: '请选择哺乳假开始日期', trigger: ['blur'] }],
        breastfeedEndDate: [{ required: true, message: '请选择哺乳假结束日期', trigger: ['blur'] }],
        breastfeedType: [{ required: true, message: '请选择哺乳假类型', trigger: ['change'] }],
        other: [{ validator: validateOtherReason, required: true, trigger: ['blur'] }],
        endDate: [{ required: true, message: '请选择结束日期', trigger: ['blur'] }],
        onBusiness: [{ required: true, message: '请选择“因公”或“因私”', trigger: ['blur'] }]
      }, // 前端校验规则
      isEditMode: false,
      columns: [
        {
          text: '备注类型',
          value: 'remarksTypeName',
          align: 'center'
        },
        {
          text: '备注信息',
          value: 'remarks',
          align: 'center'
        }
      ], // 显示列
      remarksTypeList: [],
      remarksList: [
        { name: '出差', value: '1' },
        { name: '请假-年假', value: '2' },
        { name: '请假-事假', value: '3' },
        { name: '请假-病假', value: '4' },
        { name: '请假-婚假', value: '5' },
        { name: '请假-丧假', value: '6' },
        { name: '请假-工伤', value: '7' },
        { name: '请假-探亲假', value: '8' },
        { name: '请假-生育假', value: '9' },
        { name: '请假-哺乳假', value: '10' },
        { name: '值班调休', value: '11' },
        { name: '其他原因', value: '12' }],
      breastfeedTypeList: [{ name: '上午晚到', value: '1' }, { name: '下午早走', value: '2' }],
      list: [],
      breastfeedTypeDisabled: false
    }
  },
  watch: { },
  mounted() { },
  methods: {
    closeDialog() {
      this.list = []
      this.listLoading = true
      if (this.edited) {
        this.edited = false
        this.$parent.fetchData(true)
      }
    },
    disabledBeginDate(time) {
      return time.getTime() > new Date(this.curDate)
    },
    disabledEndDate(time) {
      return time.getTime() < new Date(this.curDate + ' 00:00:00')
    },
    // 初始化对话框
    initDialog: function(title = null, dialogFormVisible, row) {
      this.addShow = false
      this.title = '编辑备注 - ' + row.name + ' - ' + row.date
      this.curDate = row.date
      this.remarksForm.reportId = row.id
      this.remarksForm.personId = row.personId
      this.dialogFormVisible = dialogFormVisible
      this.fetchRemarksType()
      this.fetchData()
    },
    // 重置表单
    resetForm() {
      this.remarksForm.id = ''
      this.remarksForm.remarksType = ''
      this.remarksForm.remarks = ''
      this.remarksForm.beginDate = ''
      this.remarksForm.endDate = ''
      this.remarksForm.breastfeedType = ''
      this.remarksForm.breastfeedBeginDate = ''
      this.remarksForm.other = ''
      this.remarksForm.onBusiness = ''
      this.remarksForm.beginDate = this.curDate
      this.remarksForm.endDate = this.curDate
      this.remarksForm.breastfeedBeginDate = this.curDate
      this.remarksForm.breastfeedEndDate = ''
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    selectRemarksType() {
      if (this.remarksForm.remarksType === '1' || this.remarksForm.remarksType === '3') {
        this.remarksForm.breastfeedType = '1'
        this.breastfeedTypeDisabled = true
      } else if (this.remarksForm.remarksType === '2' || this.remarksForm.remarksType === '4') {
        this.remarksForm.breastfeedType = '2'
        this.breastfeedTypeDisabled = true
      } else {
        this.breastfeedTypeDisabled = false
      }
    },
    add() {
      this.resetForm()
      this.addShow = true
      // 选择一个初始值
      if(this.remarksTypeList.length === 1){
        this.remarksForm.remarksType = this.remarksTypeList[0].id
      } else {
        for(var i=0; i<this.remarksTypeList.length;i++){
          if(this.remarksTypeList[i].name === '旷工一天'){
            this.remarksForm.remarksType = '5'
            break
          }
        }
      }
      // 根据remarksType的值，自动选择breastfeedType
      if (this.remarksForm.remarksType === '1' || this.remarksForm.remarksType === '3') {
        this.remarksForm.breastfeedType = '1'
        this.breastfeedTypeDisabled = true
      } else if (this.remarksForm.remarksType === '2' || this.remarksForm.remarksType === '4') {
        this.remarksForm.breastfeedType = '2'
        this.breastfeedTypeDisabled = true
      } else {
        this.breastfeedTypeDisabled = false
      }
    },
    // 保存数据
    saveData: function() {
      // 表单校验
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          debugger
          this.saveBtnDisabeld = true
          // 如果备注为哺乳假，则需要特别处理
          if (this.remarksForm.remarks === '请假-哺乳假') {
            var startDates = this.remarksForm.breastfeedBeginDate.split('-')
            var endDates = this.remarksForm.breastfeedEndDate.split('-')
            var startDate = new Date(startDates[0], startDates[1] - 1, startDates[2])
            var endDate = new Date(endDates[0], endDates[1] - 1, endDates[2])
            if (parseInt(Math.abs(endDate - startDate) / 1000 / 60 / 60 / 24) > (365 - 128)) {
              this.$message.error('哺乳假时间太长，请选择合理的起止日期')
              this.saveBtnDisabeld = false
              return
            }// 把相差的毫秒数
            this.remarksForm.remarks = this.remarksForm.remarks + this.remarksForm.breastfeedType
            this.remarksForm.beginDate = this.remarksForm.breastfeedBeginDate
            this.remarksForm.endDate = this.remarksForm.breastfeedEndDate
          }
          // 如果备注了其他原因
          if (this.remarksForm.remarks === '其他原因') {
            var v = '(私)'
            if (this.remarksForm.onBusiness === '1') v = '(公)'
            this.remarksForm.remarks = v + this.remarksForm.other
          }
          addRemarks(this.remarksForm).then(response => {
            if (response.code === 200) {
              this.fetchData()
              this.fetchRemarksType()
              this.addShow = false
              this.$message.success('添加成功！')
              this.edited = true
              if(this.remarksForm.remarks.indexOf('哺乳假')>-1) this.remarksForm.remarks = '请假-哺乳假'
            }
            this.saveBtnDisabeld = false
          }).catch(err => {
            console.log(err)
            this.saveBtnDisabeld = false
            if(this.remarksForm.remarks.indexOf('哺乳假')>-1) this.remarksForm.remarks = '请假-哺乳假'
          })
        }
      })
    },
    // 删除备注
    del(row) {
      this.$confirm(
        '确定要删除该条备注信息吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        var params = {}
        params.reportId = this.remarksForm.reportId
        params.remarksId = row.id
        delRemarks(params).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
            this.fetchRemarksType()
            this.edited = true
          }
        })
      })
    },
    // 获取已添加的备注信息列表
    fetchData() {
      var params = {}
      params.personId = this.remarksForm.personId
      params.date = this.curDate
      getRemarksList(params).then(response => {
        if (response.code === 200) {
          this.list = response.data
        }
        this.listLoading = false
      })
    },
    // 获取可添加的备注类型列表
    fetchRemarksType() {
      var params = {}
      params.personId = this.remarksForm.personId
      params.date = this.curDate
      params.reportId = this.remarksForm.reportId
      getEnabledTypeList(params).then(response => {
        if (response.code === 200) {
          this.remarksTypeList = response.data
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
  .dialog-footer{
    text-align: right;
    margin-top: 10px;
  }
</style>
