<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="head-container">
      <el-row type="flex">
        <el-col :span="20" class="col_flex">
          <div class="form_item">
            <span>设备ID:</span>
            <el-input v-model="queryInfo.device_id" clearable size="small" placeholder="请输入设备ID" style="width: 200px" class="filter-item" @keyup.enter.native="getStartUpList" @blur="getStartUpList" />
          </div>
          <div class="form_item">
            <span>设备名称：</span>
            <el-input v-model="queryInfo.device_name" clearable size="small" placeholder="请输入设备名称" style="width: 200px" class="filter-item" @keyup.enter.native="getStartUpList" @blur="getStartUpList" />
          </div>
        </el-col>
        <el-col class="page_add" :span="4">
          <el-button class="table_add clear_btn" plain :disabled="clearBtnDisabled" @click="removeStartUp(sels)">清空</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 配置开关机列表 -->
    <el-row :gutter="15">
      <el-col>
        <el-table style="width: 100%;" :data="startUpList" :header-cell-style="{ background: '#3a8aeb', color: '#fff' }" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="device_id" label="设备ID" align="center" />
          <el-table-column prop="device_account" label="设备账号" align="center" width="150" />
          <el-table-column prop="device_name" label="设备名称" align="center" />
          <el-table-column label="设备方向" align="center">
            <template slot-scope="{row}">
              <div>{{ row.device_direction==1? '竖屏' : '横屏' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="period" label="配置周期" align="center" width="300">
            <template slot-scope="{row}">
              <div v-show="row.open_setting">{{ row.open_setting==1? '每天 - 开机 '+row.open_time :'每周'+setWeekly(row.open_weekly)+'开机'+row.open_time }}</div>
              <div v-show="row.open_setting">{{ row.close_setting==1?'每天 - 关机'+row.close_time :'每周'+setWeekly(row.close_weekly)+'关机'+row.close_time }}</div>
            </template>
          </el-table-column>
          <el-table-column label="启动画面" align="center">
            <template slot-scope="{row}">
              <el-image v-show="row.startup_screen" class="cover_img" :src="row.startup_screen" />
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="创建时间" align="center" width="200">
            <template slot-scope="{row}">
              <div>{{ row.update_time | parseTime }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-button type="primary" class="edit_btn" @click="editFormData(scope.row)">编辑</el-button>
              <el-button type="info" class="record_btn">记录</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 20px;" background :current-page="queryInfo.page" :total="total" :page-size="queryInfo.size" :pager-count="7" :page-sizes="[3, 5, 10]" layout="prev, pager, next, jumper,->,sizes,total" @current-change="getStartUpList" @size-change="handleSizeChange" />

      </el-col>
    </el-row>
    <!-- 编辑设备 -->
    <div class="layer device_layer">
      <el-dialog title="编辑" :close-on-click-modal="false" :show-close="false" :visible.sync="addFromVisible" width="880px">
        <el-form ref="form" :model="form">
          <div class="setting_item">
            <h4>开机时间</h4>
            <div class="setting_cont">
              <span>设置时间：</span>
              <div>
                <el-form-item
                  prop="open_setting"
                  :rules="[
                    { required: true, message: '请选择开机时间', trigger: 'change' },
                  ]"
                  :class="{'no_margin': form.open_setting === 2}"
                >
                  <el-radio-group v-model="form.open_setting" @change="clearCheckbox()">
                    <el-radio :label="1" value="everyday">每天</el-radio>
                    <el-radio :label="2" value="weekly">每周</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="form.open_setting === 2"
                  :class="{'weekly_margin': form.open_setting === 2}"
                  prop="open_weekly"
                  :rules="[
                    { required: true, message: '请选择每周开机时间', trigger: 'change' },
                  ]"
                >
                  <el-checkbox-group v-model="selectOpenWeekly">
                    <el-checkbox v-for="item in weeklyList" :key="item.id" :label="item.id" :value="item.id" name="type">{{ item.name }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item
                  prop="open_time"
                  :rules="[
                    {type: 'string', required: true, message: '请选择具体开机时间', trigger: 'change' },
                  ]"
                >
                  <el-time-picker
                    v-model="form.open_time"
                    :picker-options="{
                      selectableRange: '00:00:00 - 23:59:59'
                    }"
                    placeholder="任意时间点"
                    value-format="HH:mm:ss"
                  />
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="setting_item">
            <h4>关机时间</h4>
            <div class="setting_cont">
              <span>设置时间：</span>
              <div>
                <el-form-item
                  prop="close_setting"
                  :rules="[
                    {required: true, message: '请选择关机时间', trigger: 'change' },
                  ]"
                  :class="{'no_margin': form.close_setting === 2}"
                >
                  <el-radio-group v-model="form.close_setting" @change="clearCheckbox()">
                    <el-radio :label="1" value="everyday">每天</el-radio>
                    <el-radio :label="2" value="weekly">每周</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="form.close_setting === 2"
                  :class="{'weekly_margin': form.close_setting === 2}"
                  prop="close_weekly"
                  :rules="[
                    { required: true, message: '请选择每周关机时间', trigger: 'change' },
                  ]"
                >
                  <el-checkbox-group v-model="selectCloseweekly">
                    <el-checkbox v-for="item in weeklyList" :key="item.id" :label="item.id" :value="item.id" name="type">{{ item.name }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item
                  prop="close_time"
                  :rules="[
                    {type: 'string', required: true, message: '请选择具体关机时间', trigger: 'change' },
                  ]"
                >
                  <el-time-picker
                    v-model="form.close_time"
                    :picker-options="{
                      selectableRange: '00:00:00 - 23:59:59'
                    }"
                    placeholder="任意时间点"
                    value-format="HH:mm:ss"
                  />
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="setting_item">
            <h4>设备方向</h4>
            <div class="setting_cont">
              <span>设备方向：</span>
              <el-form-item
                prop="device_direction_name"
                :rules="[
                  { required: true, message: '请选择具体设备方向', trigger: 'change' },
                ]"
              >
                <el-select v-model="form.device_direction_name" size="small" class="filter-item" value-key="name" @change="selectDirection">
                  <el-option v-for="item in deviceData" :key="item.key" :label="item.name" :value="item" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="setting_item">
            <h4>启动画面</h4>
            <!--   action="https://jsonplaceholder.typicode.com/posts/" -->
            <div class="setting_cont upload_img">
              <el-form-item prop="startup_screen">
                <UploadCover ref="childUpload" />
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" round @click="submitForm('form')">确 定</el-button>
          <el-button round @click="resetForm('form')">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import UploadCover from '../components/upload_cover.vue'
import { reqStartUpList, reqEditStartUp, reqClearStartUp } from '@/api/device/startUpList.js'
import { parseTime } from '@/utils/index.js'
export default {
  name: 'DeviceConfig',
  components: { UploadCover },
  filters: {
    parseTime(time, cFormat) {
      return parseTime(time, cFormat)
    }
  },
  data() {
    return {
      query: {
        blurry: ''
      },
      // 获取开关机列表的参数
      queryInfo: {
        device_id: '',
        device_name: '',
        is_state: '',
        page: 1,
        size: 10
      },
      total: 0,
      // 开关机列表的数据
      startUpList: [],
      form: {
        device_direction: null,
        device_direction_name: null,
        device_id: '',
        open_setting: null, // 开机状态的每天和每周
        close_setting: null, // 关机状态的每天和每周
        open_time: '', // 具体的开机时间
        close_time: '', // 具体的关机时间
        startup_screen: '', // 启动画面的图片
        open_weekly: [],
        close_weekly: []
      },
      selectOpenWeekly: [], // 选中的开机每周状态
      selectCloseweekly: [], // 选中的关机机每周状态
      addFromVisible: false,
      // 被选中的行
      sels: [],
      clearBtnDisabled: true,
      deviceData: [{ key: '1', name: '竖屏' }, { key: '2', name: '横屏' }],
      weeklyList: [
        {
          id: '0',
          name: '周日'
        },
        {
          id: '1',
          name: '周一'
        },
        {
          id: '2',
          name: '周二'
        },
        {
          id: '3',
          name: '周三'
        },
        {
          id: '4',
          name: '周四'
        },
        {
          id: '5',
          name: '周五'
        },
        {
          id: '6',
          name: '周六'
        }
      ]
    }
  },
  computed: {
    // 将字符串渲染成汉字显示到页面
    setWeekly() {
      const a = {
        0: '日',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六'
      }
      return function(str) {
        if (str) {
          return str.split(',').map(i => a[i]).join('/')
        }
      }
    }

  },
  watch: {},
  mounted() {
    this.getStartUpList()
  },
  methods: {
    // 获取开关机列表
    getStartUpList() {
      // this.queryInfo.page = pager
      const params = this.queryInfo
      reqStartUpList(params).then(res => {
        if (res.code == 200) {
          this.startUpList = res.data.content
          this.total = res.data.totalElements
          this.queryInfo.size = res.data.size
        } else {
          return this.$message.error('获取设备列表失败！')
        }
      })
    },
    // 编辑开关机
    editFormData(row) {
      this.addFromVisible = true
      this.form.device_id = row.device_id
      this.form.open_setting = row.open_setting
      this.form.close_setting = row.close_setting
      this.form.open_time = row.open_time
      this.form.close_time = row.close_time
      this.form.startup_screen = row.startup_screen
      this.form.open_weekly = row.open_weekly
      if (row.open_weekly) {
        this.selectOpenWeekly = row.open_weekly.split(',')
      }
      this.form.close_weekly = row.close_weekly
      if (row.close_weekly) {
        this.selectCloseweekly = row.close_weekly.split(',')
      }
      this.form.device_direction_name = row.device_direction == 1 ? '竖屏' : '横屏'
      this.form.device_direction = row.device_direction
      this.$nextTick(() => {
        this.$refs.childUpload.imageUrl = this.form.startup_screen
      })
    },
    // 每天/每周切换的情况下数据处理
    clearCheckbox() {
      if (this.form.open_setting === 1) {
        this.open_weekly = []
        this.form.open_weekly = null
      }
      if (this.form.close_setting === 1) {
        this.close_weekly = []
        this.form.close_weekly = null
      }
    },
    // 选择设备方向处理
    selectDirection(selVal) {
      console.log(selVal)
      this.form.device_direction = selVal.key
      this.form.device_direction_name = selVal.name
    },
    // 重置表单数据
    resetForm(formName) {
      this.addFromVisible = false
      this.$refs[formName].resetFields()
    },
    // 提交表单数据
    submitForm(formName) {
      this.form.startup_screen = this.$refs.childUpload.imageUrl
      if (this.form.open_setting === 2) {
        this.form.open_weekly = this.selectOpenWeekly.join(',')
      }
      if (this.form.close_setting === 2) {
        this.form.close_weekly = this.selectCloseweekly.join(',')
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = {
            close_setting: this.form.close_setting,
            close_time: this.form.close_time,
            close_weekly: this.form.close_weekly,
            device_id: this.form.device_id,
            open_setting: this.form.open_setting,
            open_time: this.form.open_time,
            open_weekly: this.form.open_weekly,
            device_direction: this.form.device_direction,
            startup_screen: this.form.startup_screen
          }
          console.log(params)
          reqEditStartUp(params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '修改设备成功'
              })
              this.addFromVisible = false
              this.getStartUpList(this.queryInfo.page)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 列表多选操作 - 清空btn状态
    // 单选单个复选框
    handleSelectionChange(sels) {
      this.sels = sels
      if (sels.length > 0) {
        this.clearBtnDisabled = false
      } else {
        this.clearBtnDisabled = true
      }
    },
    // 清空
    removeStartUp(rows) {
      const ids = []
      rows.forEach(item => {
        ids.push(item.device_id)
      })
      // console.log(ids)
      this.$confirm('确定要清空选中的配置周期和启动画面吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          ids
        }
        reqClearStartUp(params).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message({
              message: '清空成功',
              type: 'success'
            })
            this.getStartUpList(this.startUpList.length > 1 ? this.queryInfo.page : this.queryInfo.page - 1)
          }
        }).catch(() => {
          this.$message({
            message: '清空失败',
            type: 'info'
          })
        })
      })
    },
    // 每条显示数据改变时的事件
    handleSizeChange(size) {
      // 整理参数
      this.queryInfo.size = size
      this.getStartUpList()
    }
  }
}
</script>

<style lang="scss" scoped>
.setting_btn {
  margin-right: 10px;
}
.clear_btn {
  color: #3a8aeb;
  border-color: #3a8aeb;
}
.cover_img {
  width: 65px;
}
.device_layer {
  ::v-deep .el-dialog__body {
    padding: 0 20px;
  }
  .setting_item {
    padding-top: 24px;
    color: #333;
    h4 {
      font-size: 16px;
      margin-bottom: 10px;
    }
    .setting_cont {
      display: flex;
      span {
        display: block;
        width: 80px;
        line-height: 32px;
      }
      .no_margin {
        margin: 0;
      }
      .weekly_margin {
        margin-bottom: 6px;
        ::v-deep .el-form-item__error {
          top: 70%;
        }
      }
      ::v-deep .el-form-item--small.el-form-item:last-child {
        margin: 0;
      }
      ::v-deep .el-radio-group {
        display: block;
        // line-height: 32px;
        .el-radio {
          line-height: 32px;
        }
      }
    }
    .upload_img {
      padding-left: 82px;
    }
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
