<template>
  <ai-detail class="Play">
    <template #title>
      <ai-title title="添加广播" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
    </template>
    <template #content>
      <ai-card title="基础信息">
        <template #content>
          <el-alert title="温馨提示：请先选择行政区划，再选择播放设备！" type="warning" show-icon :closable="false" style="margin-bottom: 12px;padding: 4px 20px;"></el-alert>
          <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="messageLevel">
              <ai-select v-model="formData.messageLevel" placeholder="播发级别" clearable
                         :selectList="$dict.getDict('dlbMessageUrgency')"></ai-select>
            </el-form-item>
            <el-form-item label="行政区划" prop="areaId">
              <ai-area-get v-model="areaId" :root="areaRootId"  :instance="instance" @select="handleAreaSelect" multiple  size="small" placeholder="全部地区"/>
            </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-item label="播放设备" prop="serialNo" style="width: 100%;">
              <ai-table-select :instance="instance" :action="`/app/appresident/list?householdName=1&areaId=${areaId}&auditStatus=1`"
                              @select="v=>chooseUser=v" multiple/>
            </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'}
        ],
        areaId: [
          {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'}
        ],
      },
      areaRootId: '',
      mediaList: [],
      equipmentList: [],
      detailDialog: false,
      isAll: false,
      input3: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // tree
      data: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }, {
        label: '一级 2',
        children: [{
          label: '二级 2-1',
          children: [{
            label: '三级 2-1-1'
          }]
        }, {
          label: '二级 2-2',
          children: [{
            label: '三级 2-2-1'
          }]
        }]
      }, {
        label: '一级 3',
        children: [{
          label: '二级 3-1',
          children: [{
            label: '三级 3-1-1'
          }]
        }, {
          label: '二级 3-2',
          children: [{
            label: '三级 3-2-1'
          }]
        }]
      }],
      // 复选框
      checkAll: false,
      checkedCities: [],
      cities: ['上海', '北京', '广州', '深圳','湖北','湖南','河北','河南'],
      isIndeterminate: true,
      // 标签
      tags: [
        { name: '标签一', type: '' },
        { name: '标签二', type: 'success' },
        { name: '标签三', type: 'info' },
        { name: '标签四', type: 'warning' },
        { name: '标签五', type: 'danger' }
      ],
      serialNoList: [],
      areaId: '',
      areaName: '',
      chooseUser: '',
    }
  },
  computed: {
    ...mapState(['user']),

    isEdit() {
      return !!this.params.id
    },
    newDate() {
      var myDate = new Date();
      return myDate.getHours() + ':' + myDate.getMinutes() + ':' + myDate.getSeconds()
    },
    areaRoot() {
      return this.areaRootId = [this.user.info.areaId.substr(0,6),'000000'].join("")
    }

  },
  created() {
    this.dict.load('dlbMessageUrgency', 'dlbBroadTaskType', 'dlbDyclingType')
    Promise.all([this.getEquipmentList(), this.getMediaList()]).then(() => {
      this.formData.mediaId = this.params.id
    })
  },
  methods: {
    // 选择设备
    getSelect() {},
    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
          })) || []
        }
      })
    },
    // 地区选择
    handleAreaSelect() {
      this.areaName = v?.[0]?.label
    },
    // 全选按钮
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },
    // 复选框
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount == this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 搜索设备
    searchEquipment() {
      console.log('搜索设备');
    },
    // 关闭标签
    closeTags(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1);
    },
    // 清空标签
    emptyBtn() {
      this.tags = []
    },
    handleNodeClick(data) {
      console.log(data);
    },
    // 行政区划
    bindAdministrative() {
      this.instance.post(`/app/appdlbquipment/addOrUpdate`, this.changeInfo).then((res) => {
        if (res.code == 0) {
          // this.$message.success('绑定行政区划成功！')
          // this.bindVisible = false
          // this.getList()
        }
      })
    },
    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>
.Play {
  .equipment {
    position: relative;
    .select {
      position: absolute;
      right: 0;
      top: 0;
    }
  }

  .equipments {
    display: flex;
    width: 100%;
    height: 32px;
    align-items: center;
    border-radius: 4px;
    border: 1px solid #DDD;
    justify-content: space-between;
  }

  .container {
    display: flex;
    width: 100%;
    height: 100%;
    .item {
      flex: 1;
      display: inline-block;
      height: auto;
      border: 1px solid #DDD;
      .title {
        display: flex;
        justify-content: space-between;
        padding: 10px;
        box-sizing: border-box;
        height: 50px;
        align-items: center;
        border-bottom: 1px solid #DDD;
        .checkBox {
          align-self: center;
        }
      }
      .content {
        padding: 10px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
