<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body @close="cancel">
    <el-form v-loading="loading" ref="dataForm" :rules="rules" :model="strategyForm" label-well-code="right" label-width="100px">
      <!--策略名称-->
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="策略名称" prop="name">
            <el-input v-model.trim="strategyForm.name" :disabled="isReadMode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--策略类型-->
      <el-row type="flex" justify="center">
        <el-col :span="18" justify="center">
          <el-form-item label="策略类型" prop="type">
            <el-radio-group v-model="strategyForm.type" :disabled="isEditMode">
              <el-radio v-for="item in strategyTypes" :key="'strategy_'+item.value" :label="item.value">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!--星期 仅策略为星期时显示-->
      <el-row v-if="strategyForm.type=='2'" type="flex" justify="center">
        <el-col :span="18" justify="center">
          <el-form-item label="星期" prop="week">
            <el-checkbox-group v-model="strategyForm.week" :disabled="isReadMode">
              <el-checkbox v-for="item in weekList" :key="'week_'+item.value" :label="item.value">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!--生效和失效日期 仅策略为日期时显示-->
      <el-row v-if="strategyForm.type=='1'" type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="有效时间区间" prop="beginDatetime">
            <el-col :span="11">
              <el-date-picker
                v-model.trim="strategyForm.beginDatetime"
                :disabled="isReadMode"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择生效时间"/>
            </el-col>
            <el-col :span="11" :offset="1">
              <el-date-picker
                v-model.trim="strategyForm.endDatetime"
                :disabled="isReadMode"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择失效时间"/>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <!--<el-row v-if="strategyForm.type=='1'" type="flex" justify="center">-->
      <!--<el-col :span="18">-->
      <!--<el-form-item label="失效时间" prop="endDatetime">-->
      <!---->
      <!--</el-form-item>-->
      <!--</el-col>-->
      <!--</el-row>-->
      <!--生效和失效时间  仅策略为星期，当天时显示-->
      <el-row v-if="strategyForm.type!='1'" type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="有效时间区间" prop="beginTime">
            <el-col :span="9">
              <el-time-picker
                v-model.trim="strategyForm.beginTime"
                :default-value = "strategyForm.beginTime"
                :disabled="isReadMode"
                value-format="HH:mm:ss"
                placeholder="选择生效时间"/>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-time-picker
                v-model.trim="strategyForm.endTime"
                :default-value = "strategyForm.endTime"
                :disabled="isReadMode"
                value-format="HH:mm:ss"
                placeholder="选择失效时间"/>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <!--策略类型-->
      <el-row v-if="strategyForm.type=='2'" type="flex" justify="center">
        <el-col :span="18" justify="center">
          <el-form-item label="策略周期" prop="period">
            <el-radio-group v-model="strategyForm.period" :disabled="isReadMode">
              <el-radio v-for="item in strategyPeriodList" :key="'period_'+item.value" :label="item.value">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!--描述-->
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="描述" prop="description">
            <el-input v-model.trim="strategyForm.description" :maxlength="20" :disabled="isReadMode" type="text" placeholder="" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-show="!isReadMode" slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addStrategy, updateStrategy, getStrategyType, getStrategyPeriod, getWeekList, getStrategyDetail } from '@/api/strategy'

export default {
  name: 'EditStrategy',
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      strategyTypes: [], // 策略类型
      weekList: [], // 星期
      strategyPeriodList: [], // 策略周期列表
      strategyForm: {
        id: '', // id
        name: '', // 策略名称
        type: '1', // 策略类型
        beginDatetime: '', // 生效日期
        endDatetime: '', // 失效日期
        week: [], // 星期
        period: '', // 策略周期
        beginTime: '', // 生效时间
        endTime: '', // 失效时间
        description: '' // 描述
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        name: [{ required: true, message: '策略名称不能为空', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '策略类型必选', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false, // 是否为编辑模式
      isReadMode: false, // 是否为只读模式
      loading: false // 加载
    }
  },
  watch: {
    // 监控策略类型，清空表单
    'strategyForm.type': function(val) {
      if (!this.isEditMode) {
        if (val === '1') {
          this.strategyForm.week = []
          this.strategyForm.period = ''
          this.strategyForm.beginTime = ''
          this.strategyForm.endTime = ''
          this.strategyForm.description = ''
        } else if (val === '2') {
          this.strategyForm.week = []
          this.strategyForm.period = ''
          this.strategyForm.beginDatetime = ''
          this.strategyForm.endDatetime = ''
          this.strategyForm.beginTime = ''
          this.strategyForm.endTime = ''
          this.strategyForm.description = ''
        } else if (val === '3') {
          this.strategyForm.week = []
          this.strategyForm.period = ''
          this.strategyForm.beginDatetime = ''
          this.strategyForm.endDatetime = ''
          this.strategyForm.beginTime = ''
          this.strategyForm.endTime = ''
          this.strategyForm.description = ''
        }
      }
    }
  },
  mounted() {
    this.fetchStrategyType()
    this.fetchStrategyPeriod()
    this.fetchWeekList()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = true
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.isReadMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.strategyForm = {
          id: row.id, // id
          name: row.name, // 策略名称
          type: row.type, // 策略类型
          beginDatetime: row.beginDatetime, // 生效日期
          endDatetime: row.endDatetime, // 失效日期
          week: row.week.split(','), // 星期
          period: row.period, // 策略周期
          beginTime: row.beginTime, // 生效时间
          endTime: row.endTime, // 失效时间
          description: row.description // 描述
        }
        this.isEditMode = true
        this.isReadMode = false
      } else if (dialogStatus === 'detail') {
        this.strategyDetail(row.strategyId)
      }
    },
    // 重置表单
    resetForm() {
      this.strategyForm = {
        id: '', // id
        name: '', // 策略名称
        type: '1', // 策略类型
        beginDatetime: '', // 生效日期
        endDatetime: '', // 失效日期
        week: [], // 星期
        period: '', // 策略周期
        beginTime: '08:00:00', // 生效时间
        endTime: '18:00:00', // 失效时间
        description: '' // 描述
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    validateForm(strategyForm) {
      // 策略类型为日期，验证beginDatetime,endDatetime
      if (strategyForm.type === '1') {
        if (strategyForm.beginDatetime === '' || strategyForm.beginDatetime === null) {
          this.$message.warning('生效时间不能为空')
          return false
        }
        if (strategyForm.endDatetime === '' || strategyForm.endDatetime === null) {
          this.$message.warning('失效时间不能为空')
          return false
        }
      } else if (strategyForm.type === '2') {
        if (strategyForm.week.length === 0) {
          this.$message.warning('星期至少选择一个')
          return false
        }
        if (strategyForm.beginTime === '' || strategyForm.beginTime === null) {
          this.$message.warning('生效时间不能为空')
          return false
        }
        if (strategyForm.endTime === '' || strategyForm.endTime === null) {
          this.$message.warning('失效时间不能为空')
          return false
        }
        if (strategyForm.period === '') {
          this.$message.warning('策略周期必选')
          return false
        }
      } else if (strategyForm.type === '3') {
        if (strategyForm.beginTime === '' || strategyForm.beginTime === null) {
          this.$message.warning('生效时间不能为空')
          return false
        }
        if (strategyForm.endTime === '' || strategyForm.endTime === null) {
          this.$message.warning('失效时间不能为空')
          return false
        }
      }
      if (strategyForm.beginTime && strategyForm.endTime) {
        const tmpDate1 = '2020-01-01 ' + strategyForm.beginTime
        const tmpDate2 = '2020-01-01 ' + strategyForm.endTime

        if (new Date(tmpDate1) > new Date(tmpDate2)) {
          this.$message.warning('生效时间不能大于失效时间')
          return false
        }
      }
      if (strategyForm.beginDatetime && strategyForm.endDatetime) {
        if (new Date(strategyForm.beginDatetime) > new Date(strategyForm.endDatetime)) {
          this.$message.warning('生效时间不能大于失效时间')
          return false
        }
      }
      return true
    },
    // 新增数据
    createData: function() {
      if (this.validateForm(this.strategyForm)) {
        // 将星期列表转为字符串
        const strategyForm = this.strategyForm
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            strategyForm.week.sort() // 将星期排序
            strategyForm.week = strategyForm.week.join(',')
            addStrategy(strategyForm).then(response => {
              if (response.code === 200) {
                this.$confirm('新增成功，是否继续新增?', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'info'
                }).then(() => {
                  this.resetForm()
                  this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                  })
                }).catch(() => {
                  this.$emit('watchChild')
                  this.dialogFormVisible = false
                })
              }
            })
          }
        })
      }
    },
    // 修改数据
    updateData: function() {
      if (this.validateForm(this.strategyForm)) {
        // 将星期列表转为字符串
        const strategyForm = this.strategyForm
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            strategyForm.week.sort() // 将星期排序
            strategyForm.week = strategyForm.week.join(',')
            updateStrategy(strategyForm).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功')
                this.$emit('watchChild')
                this.dialogFormVisible = false
              }
            })
          }
        })
      }
    },
    strategyDetail(id) {
      this.loading = true
      getStrategyDetail(id).then(response => {
        if (response.code === 200) {
          const row = response.data
          this.strategyForm = {
            id: row.id, // id
            name: row.name, // 策略名称
            type: row.type, // 策略类型
            beginDatetime: row.beginDatetime, // 生效日期
            endDatetime: row.endDatetime, // 失效日期
            week: row.week.split(','), // 星期
            period: row.period, // 策略周期
            beginTime: row.beginTime, // 生效时间
            endTime: row.endTime, // 失效时间
            description: row.description // 描述
          }
          this.isEditMode = true
          this.isReadMode = true
          this.loading = false
        } else {
          this.loading = false
          this.dialogFormVisible = false
        }
      })
    },
    // 获取策略类型
    fetchStrategyType() {
      getStrategyType().then(response => {
        this.strategyTypes = response.data
      })
    },
    // 获取策略周期
    fetchStrategyPeriod() {
      getStrategyPeriod().then(response => {
        this.strategyPeriodList = response.data
      })
    },
    // 获取星期
    fetchWeekList() {
      getWeekList().then(response => {
        this.weekList = response.data
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
</style>
