<template>
  <ai-detail>
    <template #title>
      <ai-title title="添加广播" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
    </template>
    <template #content>
      <ai-card title="基础信息">
        <template #content>
          <el-form class="ai-form" :model="formData" :rules="formRules" ref="ruleForm" label-width="120px">
            <el-form-item label="播发内容" prop="mediaId">
              <ai-select v-model="formData.mediaId" placeholder="播发内容" clearable :selectList="mediaList"></ai-select>
            </el-form-item>
            <el-form-item label="播放设备" prop="serialNo">
              <ai-select v-model="formData.serialNo" placeholder="播放设备" clearable
                         :selectList="equipmentList"></ai-select>
            </el-form-item>
            <el-form-item label="播发级别" prop="messageLevel">
              <ai-select v-model="formData.messageLevel" placeholder="播发级别" clearable
                         :selectList="$dict.getDict('dlbMessageUrgency')"></ai-select>
            </el-form-item>
            <el-form-item label="播放方式" prop="taskType" class="buildingTypes">
              <el-radio-group v-model="formData.taskType">
                <el-radio label="0">立即播放</el-radio>
                <el-radio label="1">定时播放</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="定时策略" prop="cyclingType" v-if="formData.taskType != 0">
              <ai-select v-model="formData.cyclingType" placeholder="定时策略" clearable
                         :selectList="$dict.getDict('dlbDyclingType')"></ai-select>
            </el-form-item>
            <el-form-item label="播放天数" prop="checkList" class="buildingTypes"
                          v-if="formData.taskType != 0 && formData.cyclingType == 2">
              <el-checkbox-group v-model="formData.checkList">
                <el-checkbox label="1">每周一</el-checkbox>
                <el-checkbox label="2">每周二</el-checkbox>
                <el-checkbox label="3">每周三</el-checkbox>
                <el-checkbox label="4">每周四</el-checkbox>
                <el-checkbox label="5">每周五</el-checkbox>
                <el-checkbox label="6">每周六</el-checkbox>
                <el-checkbox label="7">每周日</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="播放天数" prop="broadcastDay" v-if="formData.taskType != 0 && formData.cyclingType == 3">
              <el-input v-model="formData.broadcastDay" placeholder="播放天数" clearable size="small"
                        maxlength="4"></el-input>
            </el-form-item>
            <el-form-item label="开始日期" prop="startDate" v-if="formData.taskType != 0">
              <el-date-picker v-model="formData.startDate" type="date" placeholder="选择日期" size="small"
                              value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime" v-if="formData.taskType != 0">
              <el-time-picker v-model="formData.startTime" placeholder="开始时间" size="small"
                              :picker-options="{ start: newDate, minTime: newDate}"
                              value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime" v-if="formData.taskType != 0">
              <el-time-picker v-model="formData.endTime" placeholder="结束时间" size="small"
                              :picker-options="{ start: formData.startTime, minTime: formData.startTime}"
                              value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm()">提交</el-button>
    </template>
  </ai-detail>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: 'Add',
  components: {},
  props: {
    dict: Object,
    params: Object,
    instance: Function,
  },
  data() {
    let startTimePass = (rule, value, callback) => {
      if (value) {
        var myDate = new Date();
        var time = myDate.getHours() + ':' + myDate.getMinutes() + ':' + myDate.getSeconds()
        if (this.timeToSec(value) - this.timeToSec(time) > 0) {
          callback()
        } else {
          callback(new Error('开始时间要大于当前时间'));
        }
      } else {
        callback(new Error('请选择开始时间'));
      }
    };
    let endTimePass = (rule, value, callback) => {
      if (value) {
        if (this.timeToSec(value) - this.timeToSec(this.formData.startTime) > 0) {
          callback()
        } else {
          callback(new Error('结束时间要大于开始时间'));
        }
      } else {
        callback(new Error('请选择结束时间'));
      }
    }
    return {
      formData: {
        mediaId: '',
        serialNo: '',
        messageLevel: '',
        cyclingType: '',
        taskType: '0',
        cyclingDate: '',
        broadcastDay: '',
        startDate: '',
        startTime: '',
        endTime: '',
        checkList: []
      },
      formRules: {
        mediaId: [
          {required: true, message: '请选择播发内容', trigger: 'change'}
        ],
        serialNo: [
          {required: true, message: '请选择播放设备', trigger: 'change'}
        ],
        messageLevel: [
          {required: true, message: '请选择播发级别', trigger: 'change'}
        ],
        cyclingType: [
          {required: true, message: '请选择定时策略', trigger: 'change'}
        ],
        taskType: [
          {required: true, message: '请选择播放方式', trigger: 'change'}
        ],
        broadcastDay: [
          {required: true, message: '请输入播放天数', trigger: 'change'}
        ],
        startDate: [
          {required: true, message: '请选择开始日期', trigger: 'change'}
        ],
        startTime: [
          {required: true, validator: startTimePass, trigger: 'change'}
        ],
        endTime: [
          {required: true, validator: endTimePass, trigger: 'change'}
        ],
        checkList: [
          {required: true, message: '播放天数', trigger: 'change'}
        ],
      },
      mediaList: [],
      equipmentList: []
    }
  },
  computed: {
    ...mapState(['user']),

    isEdit() {
      return !!this.params.id
    },
    newDate() {
      var myDate = new Date();
      return myDate.getHours() + ':' + myDate.getMinutes() + ':' + myDate.getSeconds()
    }
  },
  created() {
    this.dict.load('dlbMessageUrgency', 'dlbBroadTaskType', 'dlbDyclingType')
    Promise.all([this.getEquipmentList(), this.getMediaList()]).then(() => {
      this.formData.mediaId = this.params.id
    })
  },
  methods: {
    getMediaList() {
      return this.instance.post(`/app/appdlbresource/list?current=1&size=10000`).then((res) => {
        if (res?.data) {
          this.mediaList = res.data.records?.map((item) => ({
            dictName: item.name,
            dictValue: item.id
          })) || []
        }
      })
    },
    getEquipmentList() {
      return this.instance.post(`/app/appdlbquipment/getDlbDeviceList?current=1&size=10000&devStatus=5`).then((res) => {
        if (res?.data) {
          this.equipmentList = res.data.records?.map((item) => ({
            dictName: item.deviceName,
            dictValue: item.serialNo
          })) || []
        }
      })
    },
    confirm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.formData.checkList.length) {
            this.formData.cyclingDate = this.formData.checkList.join(',')
          }
          this.formData.coverageType = '4'
          this.formData.id = ''
          this.instance.post(`/app/appzyvideobroadcast/play`, {
            ...this.formData,
          })
          .then((res) => {
            if (res.code == 0) {
              this.$message.success('提交成功')
              setTimeout(() => {
                this.cancel(true)
              }, 1000)
            }
          })
        }
      })
    },
    getDetail() {
      this.instance.post(`/app/appzyvideobroadcast/queryDetailById?id=${this.params.id}`).then((res) => {
        if (res?.data) {
          this.formData = {
            ...res.data,
            checkList: []
          }
          this.formData.mediaId = String(this.formData.mediaId)
          this.formData.cyclingType = String(this.formData.cyclingType)
          if (this.formData.cyclingDate) {
            this.formData.checkList = this.formData.cyclingDate.split(',')
          }
        }
      })
    },
    timeToSec(time) {
      var s = "";
      var hour = time.split(":")[0];
      var min = time.split(":")[1];
      var second = time.split(":")[2];
      s = Number(hour * 3600) + Number(min * 60) + Number(second)
      return s;
    },
    // 返回按钮
    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh,
      })
    },
  },
}
</script>

<style lang="scss" scoped>

</style>
