<template>
  <section style="height: 100%">
    <ai-detail class="Add">
      <!-- 返回按钮 -->
      <template #title>
        <ai-title title="添加广播" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
      </template>

      <template #content>
        <el-form :model="formData" :rules="formRules" ref="ruleForm" label-width="150px" label-suffix="：" align-items="center">
          <ai-bar title="基础信息"></ai-bar>
          <div class="flex">
            <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>
          </div>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm()">提交</el-button>
      </template>
    </ai-detail>
  </section>
</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();
      var time = myDate.getHours() + ':' +  myDate.getMinutes() + ':' + myDate.getSeconds()
      return time
    }
  },
  created() {
    this.dict.load('dlbMessageUrgency', 'dlbBroadTaskType', 'dlbDyclingType').then(() => {
      this.getEquipmentList()
    })
  },
  methods: {
    getMediaList() {
      this.instance.post(`/app/appdlbresource/list?current=1&size=10000`).then((res) => {
        if (res.code == 0) {
          this.mediaList = []
          if(res.data && res.data.records.length) {
            res.data.records.map((item) => {
              let info = {
                dictName: item.name,
                dictValue: item.id
              }
              this.mediaList.push(info)
            })
          }
          if(this.params.id) {
            this.getDetail()
          }
        }
      })
    },
    getEquipmentList() {
      this.instance.post(`/app/appdlbquipment/getDlbDeviceList?current=1&size=10000&devStatus=5&keyword=`).then((res) => {
        if (res.code == 0) {
          this.equipmentList = []
          if(res.data && res.data.records.length) {
            res.data.records.map((item) => {
              let info = {
                dictName: item.deviceName,
                dictValue: item.serialNo
              }
              this.equipmentList.push(info)
            })
          }
          this.getMediaList()
        }
      })
    },
    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.code == 0) {
          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>
.Add {
  height: 100%;
  .ai-detail__title {
    background-color: #fff;
  }
  .ai-detail__content {
    .ai-detail__content--wrapper {
      .el-form {
        background-color: #fff;
        padding: 0 60px;
        .flex {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-form-item {
            width: 48%;
          }
          .buildingTypes {
            width: 100%;
          }
        }
      }
    }
  }
}

::v-deep .mapDialog {
  .el-dialog__body {
    padding: 0;

    .ai-dialog__content {
      padding: 0;
    }

    .ai-dialog__content--wrapper {
      padding: 0 !important;
      position: relative;
    }

    #map {
      width: 100%;
      height: 420px;
    }

    .searchPlaceInput {
      position: absolute;
      width: 250px;
      top: 30px;
      left: 25px;
    }

    #searchPlaceOutput {
      position: absolute;
      width: 250px;
      left: 25px;
      height: initial;
      top: 80px;
      background: white;
      z-index: 250;
      max-height: 300px;
      overflow-y: auto;

      .auto-item {
        text-align: left;
        font-size: 14px;
        padding: 8px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
