<template>
  <div>
    <div class="gva-search-box">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchInfo"
      >
        <el-form-item label="项目名称：">
          <el-select
            v-model="searchInfo.projectId"
            filterable
            collapse-tags
            placeholder="选择项目"
            clearable
            @change="getTableData()"
          >
            <el-option
              v-for="item in projects"
              :key="item.ID"
              :label="item.projectName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备SN：">
          <el-input
            v-model="searchInfo.sn"
            placeholder="搜索sn"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="getTableData"
          >查询</el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="add()"
        >添加显示屏</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :table-layout="'fixed'"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          prop="ID"
          label="编号"
          :width="100"
        />
        <el-table-column
          label="名称"
          :width="200"
          prop="screensName"
        />
        <el-table-column
          label="sn"
          :width="220"
          prop="sn"
        />
        <el-table-column
          label="ip地址"
          :width="200"
          prop="ipAddress"
        />
        <el-table-column
          label="所属项目"
          :width="180"
          prop="Project.projectName"
        />
        <el-table-column
          prop="Remark"
          label="备注"
        />
        <el-table-column
          prop="status"
          label="在线状态"
          :width="100"
        >
          <template #default="scope">
            <div
              class="onlinebox"
              :style="{'background': scope.row.status===0 ? 'red':'green' }"
            />
            <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '离线' : '在线' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          fixed="right"
          label="操作"
          :width="300"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="openSet(scope.row)"
            >操作</el-button>
            <el-button
              type="primary"
              link
              icon="edit"
              @click="editScreens(scope.row)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteScreens(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>

      <el-dialog
        v-model="addScreensDialog"
        title="LED屏"
        width="600"
      >
        <el-form
          ref="screensForm"
          :rules="rules"
          :model="screensInfo"
          label-width="100px"
          style="padding: 15px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="LED名称："
                :inline="false"
                prop="screensName"
              >
                <el-input v-model="screensInfo.screensName" />
              </el-form-item>
              <el-form-item
                label="设备Sn："
                :inline="false"
                prop="sn"
              >
                <el-input v-model="screensInfo.sn" />
              </el-form-item>
              <el-form-item
                label="所属项目："
                prop="projectId"
              >
                <el-select
                  v-model="screensInfo.projectId"
                  filterable
                  collapse-tags
                  placeholder="选择项目"
                >
                  <el-option
                    v-for="item in projects"
                    :key="item.ID"
                    :label="item.projectName"
                    :value="item.ID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="ip地址："
                :inline="false"
              >
                <el-input v-model="screensInfo.ipAddress" />
              </el-form-item>
              <el-form-item
                label="备注："
                :inline="false"
              >
                <el-input
                  v-model="screensInfo.Remark"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeAddScreensDialog">取消</el-button>
            <el-button
              type="primary"
              @click="enterAddScreensDialog"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog
        v-model="showSettingDialog"
        :title="`操作,设备序号=`+deviceSn"
        width="1000"
      >
        <el-tabs v-model="activeName">
          <el-tab-pane
            label="节目"
            name="first"
          >
            <el-form
              :model="programData"
              label-width="auto"
            >
              <el-form-item label="内容编号">
                <el-select
                  v-model="programData.num"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in contentNumberOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="显示方式">
                <el-select
                  v-model="programData.effect"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in displayModeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="移动速度">
                <el-input
                  v-model="programData.speed"
                  placeholder="默认推荐 3"
                  style="width: 240px;"
                />
              </el-form-item>
              <el-form-item label="节目停留时间">
                <el-input
                  v-model="programData.stay"
                  placeholder="默认推荐 5"
                  style="width: 240px;"
                />
              </el-form-item>
              <el-form-item label="预留">
                <el-input
                  v-model="programData.total"
                  placeholder="默认推荐 100"
                  style="width: 240px;"
                />
              </el-form-item>
              <el-form-item label="节目颜色">
                <el-select
                  v-model="programData.color"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in colorOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="节目内容">
                <el-input
                  v-model="programData.content"
                  placeholder="默认推荐 [32M]注意弯道"
                  style="width: 240px;"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="success"
                  @click="storageProgram"
                >存储</el-button>
                <el-button type="primary">发送</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane
            label="声音"
            name="second"
          >
            <el-form
              :model="soundPeriodData"
              label-width="auto"
            >
              <el-alert
                v-if="isWarning"
                title="当前值未保存"
                type="warning"
              />
              <el-form-item label="星期">
                <el-select
                  v-model="soundPeriodData.time"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in timeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <div
                v-for="(period, key) in formDataPeriods"
                :key="key"
              >
                <el-form-item :label="key">
                  <el-row :gutter="10">
                    <el-col :span="8">
                      <span>小时:</span>
                      <el-input-number
                        v-model.number="period[0]"
                        :min="0"
                        :max="23"
                        label="小时"
                      />
                    </el-col>
                    <el-col :span="8">
                      <span>分钟:</span>
                      <el-input-number
                        v-model.number="period[1]"
                        :min="0"
                        :max="59"
                        label="分钟"
                      />
                    </el-col>
                    <el-col :span="8">
                      <span>音量:</span>
                      <el-input-number
                        v-model.number="period[2]"
                        :min="0"
                        :max="10"
                        label="音量"
                      />
                    </el-col>
                  </el-row>
                </el-form-item>
              </div>
              <el-form-item>
                <el-button
                  type="success"
                  @click="storageSoundPeriod"
                >存储</el-button>
                <el-button type="primary">发送</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showSettingDialog = false">取消</el-button>
            <el-button
              type="primary"
              @click="showSettingDialog = false"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

    </div>
  </div>
</template>
<script setup>
import { addScreens, delScreens, getProjectList, getScreensList, updateScreens } from '@/api/screens'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createProgram, updateProgram } from '@/api/program'
import {createSoundPeriod, updateSoundPeriod} from "@/api/soundPeriod";

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const screensInfo = ref({})
const searchInfo = ref({})
const screensForm = ref(null)
const dialogFlag = ref('add')
const isFlag = ref('')
const addScreensDialog = ref(false)

const rules = ref({
  screensName: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    // { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择归属项目', trigger: 'blur' },
    // { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  sn: [
    { required: true, message: '请输入设备sn', trigger: 'blur' },
    // { min: 5, message: '最低5位字符', trigger: 'blur' }
  ]
})

// eslint-disable-next-line no-unused-vars
const getNowDay = () => {
  const timestamp = Date.now() // 获取当前时间戳，单位是毫秒
  screensInfo.value.startTime = new Date(timestamp)
}

const tableRowClassName = ({ row, rowIndex }) => {
  if ((rowIndex + 1) % 2 === 0) {
    return 'success-row'
  }
  return ''
}
const getTableData = async() => {
  const table = await getScreensList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const projects = ref([])

onMounted(async() => {
  getTableData()
  const res = await getProjectList()
  projects.value = res.data
})

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const add = () => {
  screensInfo.value = {}
  dialogFlag.value = 'add'
  getNowDay()
  addScreensDialog.value = true
}

const closeAddScreensDialog = () => {
  screensForm.value.resetFields()
  addScreensDialog.value = false
  isFlag.value = ''
}

const enterAddScreensDialog = async() => {
  screensForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...screensInfo.value
      }
      if (dialogFlag.value === 'add') {
        const res = await addScreens(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          await getTableData()
          closeAddScreensDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await updateScreens(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddScreensDialog()
        }
      }
    }
  })
}

const editScreens = (row) => {
  dialogFlag.value = 'edit'
  screensInfo.value = JSON.parse(JSON.stringify(row))
  addScreensDialog.value = true
}
const deleteScreens = (obj) => {
  ElMessageBox.confirm('您确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async() => {
      const res = await delScreens({ ID: obj.ID })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
const showSettingDialog = ref(false)

const openSet = (val) => {
  showSettingDialog.value = true
  deviceSn.value = val.sn
  programData.value = val.Program
  if (val.soundPeriodId === 0) {
    isWarning.value = true
    soundPeriodData.value = soundPeriodForm.value
  } else {
    isWarning.value = false
    soundPeriodData.value = val.SoundPeriod
  }
  formDataPeriods.value = {
    period0: soundPeriodData.value.period0,
    period1: soundPeriodData.value.period1,
    period2: soundPeriodData.value.period2,
    period3: soundPeriodData.value.period3,
    period4: soundPeriodData.value.period4,
    period5: soundPeriodData.value.period5,
    period6: soundPeriodData.value.period6,
    period7: soundPeriodData.value.period7,
  }
}

const isWarning = ref(false)

// 切换
const activeName = ref('first')

const deviceSn = ref()

// 节目program
const programData = ref({
  mum: undefined,
  effect: undefined,
  speed: '',
  stay: '',
  total: '',
  color: '',
  content: '',
})

// 节目选择参数
const contentNumberOptions = [
  {
    value: '0',
    label: '待机',
  },
  {
    value: '1',
    label: '正常速度',
  },
  {
    value: '2',
    label: '超速',
  },
  {
    value: '3',
    label: '对向',
  },
  {
    value: '4',
    label: '双向',
  },
  {
    value: '5',
    label: '无车',
  },

  {
    value: '6',
    label: '快速显示配置',
  },

  {
    value: '7',
    label: '无信号',
  },
]

const displayModeOptions = [
  {
    value: '10',
    label: '闪烁显示',
  },
  {
    value: '11',
    label: '立即打出',
  }
]

const colorOptions = [
  {
    value: '0',
    label: '红',
  },
  {
    value: '1',
    label: '绿',
  },
  {
    value: '2',
    label: '蓝',
  },
  {
    value: '3',
    label: '黄',
  },
]

// 存储
const storageProgram = async() => {
  if (programData.value.ID === 0) {
    console.log('create')
    await createProgram({
      deviceSn: deviceSn.value,
      program: programData.value,
    }).then(res => {
      if (res.code === 0) {
        ElMessage.success('存储成功')
      }
      getTableData()
    })
  } else {
    console.log('update')
    await updateProgram({
      deviceSn: deviceSn.value,
      program: programData.value,
    }).then(res => {
      if (res.code === 0) {
        ElMessage.success('存储成功')
      }
      getTableData()
    })
  }
}

// 声音调节soundPeriod
const soundPeriodData = ref({
  ID: 0,
  time: '0',
  period0: [],
  period1: [],
  period2: [],
  period3: [],
  period4: [],
  period5: [],
  period6: [],
  period7: [],
})

const timeOptions = [
  {
    label: '整周',
    value: '0',
  },
  {
    label: '星期一',
    value: '1',
  },
  {
    label: '星期二',
    value: '2',
  },
  {
    label: '星期三',
    value: '3',
  },
  {
    label: '星期四',
    value: '4',
  },
  {
    label: '星期五',
    value: '5',
  },
  {
    label: '星期六',
    value: '6',
  },
  {
    label: '星期七',
    value: '7',
  },
]

// 初始化表单数据
const soundPeriodForm = ref({
  ID: 0,
  time: '1',
  period0: [0, 0, 0],
  period1: [7, 0, 4],
  period2: [8, 30, 8],
  period3: [12, 0, 6],
  period4: [13, 30, 8],
  period5: [19, 0, 0],
  period6: [22, 0, 0],
  period7: [23, 59, 5],
})

const formDataPeriods = ref({
  period0: soundPeriodData.value.period0,
  period1: soundPeriodData.value.period1,
  period2: soundPeriodData.value.period2,
  period3: soundPeriodData.value.period3,
  period4: soundPeriodData.value.period4,
  period5: soundPeriodData.value.period5,
  period6: soundPeriodData.value.period6,
  period7: soundPeriodData.value.period7,
})

// 存储
const storageSoundPeriod = async() => {
  console.log(soundPeriodData.value)
  if (soundPeriodData.value.ID === 0) {
    console.log('create')
    await createSoundPeriod({
      deviceSn: deviceSn.value,
      soundPeriod: soundPeriodData.value,
    }).then(res => {
      if (res.code === 0) {
        ElMessage.success('存储成功')
      }
      getTableData()
    })
  } else {
    console.log('update')
    await updateSoundPeriod({
      deviceSn: deviceSn.value,
      soundPeriod: soundPeriodData.value,
    }).then(res => {
      if (res.code === 0) {
        ElMessage.success('存储成功')
      }
      getTableData()
    })
  }
}
</script>
<style>
.el-table .success-row {
  background: #f3fdef;
}

.onlinebox{
  width: 10px; height: 10px;border-radius: 50%; display: inline-block; margin-right: 4px; position: relative; top: 1px;
}

.el-dialog__header{
  border-bottom: 1px solid #e8eaec;
}
.el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
</style>
