<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入策略名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="queryParams.reviewStatus" placeholder="请选择审核状态" clearable>
            <el-option v-for="dict in state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable>
            <el-option v-for="dict in enable_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['light:screenProgramStrategy:query']">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['light:screenProgramStrategy:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['light:screenProgramStrategy:remove']">删除</el-button>
          <el-button @click="handleExport" icon="Download" v-hasPermi="['light:screenProgramStrategy:export']">导出</el-button>
        </div>
      </div>
      <div class="content-con">
        <el-table v-loading="loading" :data="screenProgramList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
          <el-table-column label="策略名称" align="center" prop="name" />
          <el-table-column label="开始日期" align="center" prop="beginDate" width="140">
            <template #default="scope">
              <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期" align="center" prop="endDate" width="140">
            <template #default="scope">
              <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="应用设备" align="center" prop="deviceNum">
            <template #default="scope">
              <a v-if="scope.row.status === '1' && scope.row.ids.length" style="color: #7099f9" @click="jumpDetail(scope.row)">{{ scope.row.deviceNum }} </a>
              <a v-if="scope.row.status === '0'">{{ scope.row.deviceNum }} </a>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="reviewStatus">
            <template #default="scope">
              <dict-tag :options="state" :value="scope.row.reviewStatus" />
            </template>
          </el-table-column>
          <el-table-column label="发布状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="enable_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="操作人" align="center" prop="createBy" />
          <el-table-column label="操作时间" align="center" prop="createTime" />
          <el-table-column label="操作" align="center" width="220">
            <template #default="scoped">
              <div class="ctrl-btn d-flex">
                <el-tooltip content="提交审核" placement="top" v-if="scoped.row.reviewStatus !== '2' && scoped.row.reviewStatus !== '3'">
                  <el-button icon="Promotion" circle @click="handleSubmitAudit(scoped.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="审核" placement="top" v-if="scoped.row.reviewStatus === '2'">
                  <el-button icon="RefreshRight" circle @click="handleAudit(scoped.row)" v-hasPermi="['light:screenProgramStrategy:review']"></el-button>
                </el-tooltip>
                <el-tooltip content="发布" placement="top" v-if="scoped.row.reviewStatus === '3'">
                  <el-button icon="DataAnalysis" circle @click="handleRelease(scoped.row)" v-hasPermi="['lightProgramStrategy:strategy:release']"></el-button>
                </el-tooltip>
                <el-tooltip content="查看" placement="top">
                  <el-button icon="View" circle @click="handleView(scoped.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top" v-if="scoped.row.status === '0'">
                  <el-button icon="Edit" circle @click="handleUpdate(scoped.row)" v-hasPermi="['light:screenProgramStrategy:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top" v-if="scoped.row.canDeletedFlag === 1">
                  <el-button icon="Delete" circle @click="handleDelete(scoped.row)" v-hasPermi="['light:screenProgramStrategy:remove']"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination small background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增修改节目策略dialog -->
    <el-dialog :title="title" v-model="open" width="70%" append-to-body @close="cancelAdd" destroy-on-close>
      <OperatePanel @close="handleAddFormClose" :currentId="currentId" v-if="open" :title="title" />
    </el-dialog>
    <!-- 修改节目策略dialog -->
    <el-dialog :title="title" v-model="showEditPanel" width="70%" @close="cancelEdit" append-to-body destroy-on-close>
      <EditPanel @close="handleEditFormClose" :currentId="currentId" v-if="showEditPanel" :title="title" />
    </el-dialog>
    <!-- 查看节目策略dialog -->
    <el-dialog :title="title" v-model="showViewPanel" width="70%" append-to-body destroy-on-close>
      <ViewPanel :currentId="currentId" />
    </el-dialog>
    <!-- 审核节目策略dialog -->
    <el-dialog :title="title" v-model="showAuditPanel" width="70%" @close="cancelAudit" append-to-body destroy-on-close>
      <AuditPanel @close="handleAuditFormClose" :currentId="currentId" v-if="showAuditPanel" />
    </el-dialog>
    <!-- 发布节目策略对话框 -->
    <el-dialog :title="titleRelease" v-model="openRelease" width="1200px" append-to-body @close="closeReleaseList">
      <div class="content_strategy" style="font-size: 16px; margin-bottom: 18px">
        <div class="strategyName" :title="queryParamsRelease.strategyName">策略名称:{{ queryParamsRelease.strategyName }}</div>
        <span style="margin-left: 150px">有效日期：{{ queryParamsRelease.beginDate + '至' + queryParamsRelease.endDate }}</span>
        <span v-if="true" style="margin-left: 150px">执行周期：{{ queryParamsRelease.periodName }}</span>
      </div>
      <el-form ref="releaseRef" :model="queryParamsRelease" :inline="true">
        <el-form-item label="发布类型" prop="type">
          <el-select placeholder="请选择发布类型" v-model="queryParamsRelease.type" @change="getReleaseList" clearable @keyup.enter="handleQuery">
            <el-option v-for="dict in screen_publication_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属层级" prop="buildingId" v-if="queryParamsRelease.type === '1'">
          <el-tree-select
            v-model="queryParamsRelease.buildingId"
            :data="buildingOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择所属层级"
            ref="addBuildingTreeRef"
            check-strictly
            clearable
            @change="getReleaseList"
            @node-click="getCheckedNodes"
          />
        </el-form-item>
        <el-form-item label="场所名称" prop="poleName" v-if="queryParamsRelease.type === '1'">
          <el-input v-model="queryParamsRelease.poleName" placeholder="请输入场所名称" @keyup.enter="handleQuery" @change="getList" />
        </el-form-item>
        <el-form-item label="屏幕名称" prop="name" v-if="queryParamsRelease.type === '1'">
          <el-input v-model="queryParamsRelease.name" placeholder="请输入屏幕名称" @keyup.enter="handleQuery" @change="getList" />
        </el-form-item>
        <el-form-item label="分组用途" prop="purpose" v-if="queryParamsRelease.type !== '1'">
          <el-select v-model="queryParamsRelease.purpose" placeholder="请选择分组用途" clearable>
            <el-option v-for="dict in light_group_purpose" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组名称" prop="name" v-if="queryParamsRelease.type !== '1'">
          <el-input v-model="queryParamsRelease.name" placeholder="请输入分组名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryRelease">搜索</el-button>
          <el-button type="info" icon="Refresh" @click="resetQueryRelease">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingRelease" :data="groupList" @selection-change="handleReleaseSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="所属层级" align="center" prop="buildingName" v-if="queryParamsRelease.type == '1'" />
        <el-table-column label="场所编号" align="center" prop="poleCode" v-if="queryParamsRelease.type == '1'" />
        <el-table-column label="场所名称" align="center" prop="poleName" v-if="queryParamsRelease.type == '1'" />
        <el-table-column label="屏幕编号" align="center" prop="code" v-if="queryParamsRelease.type == '1'" />
        <el-table-column label="屏幕名称" align="center" prop="name" v-if="queryParamsRelease.type == '1'" />
        <el-table-column label="在线状态" align="center" width="100" prop="networkStatus" v-if="queryParamsRelease.type == '1'">
          <template #default="scope">
            <dict-tag :options="network_status" :value="scope.row.networkStatus" :style="{ color: scope.row.networkStatus === '0' ? 'red' : 'green' }" />
          </template>
        </el-table-column>
        <el-table-column label="分组用途" align="center" prop="purpose" v-if="queryParamsRelease.type !== '1'">
          <template #default="scope">
            <dict-tag :options="light_group_purpose" :value="scope.row.purpose" />
          </template>
        </el-table-column>
        <el-table-column label="分组名称" align="center" prop="name" v-if="queryParamsRelease.type !== '1'" />
        <el-table-column label="分组描述" align="center" prop="remark" v-if="queryParamsRelease.type !== '1'" />
      </el-table>
      <el-pagination small background layout="total, prev, pager, next" :total="totalRelease" @current-change="handleReleaseCurrentChange" />
      <template #footer>
        <span class="dialog-footer">
          <div class="search-btn-con">
            <el-button type="primary" @click="submitRelease">发布 </el-button>
            <el-button @click="closeRelease">取消</el-button>
          </div>
        </span>
      </template>
    </el-dialog>
    <!-- 开关策略设备列表对话框（list--应用设备） -->
    <el-dialog title="设备列表" v-model="openView" width="68%" append-to-body @close="closeDeviceList">
      <el-form ref="viewRef" :model="queryParamsView" :inline="true" label-width="110px">
        <el-form-item label="层级名称" prop="buildingId">
          <el-tree-select
            v-model="queryParamsView.buildingId"
            :data="buildingOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择所属层级"
            check-strictly
            clearable
            @change="getDeviceList"
          />
        </el-form-item>
        <el-form-item label="场所编号" prop="poleCode">
          <el-input v-model="queryParamsView.poleCode" placeholder="请输入场所编号" />
        </el-form-item>
        <el-form-item label="场所名称" prop="poleName">
          <el-input v-model="queryParamsView.poleName" placeholder="请输入场所名称" />
        </el-form-item>
        <el-form-item label="屏幕名称" prop="name">
          <el-input v-model="queryParamsView.name" placeholder="请输入屏幕名称" />
        </el-form-item>
        <div class="search-btn-con">
          <el-button type="primary" icon="Search" @click="handleQueryDevice">搜索</el-button>
          <el-button type="info" icon="Refresh" @click="resetQueryDevice">重置</el-button>
        </div>
        <el-table v-loading="loadingView" :data="deviceList">
          <el-table-column label="所属层级" align="center" prop="buildingName" />
          <el-table-column label="场所编号" align="center" prop="poleCode" />
          <el-table-column label="场所名称" align="center" prop="poleName" />
          <el-table-column label="屏幕编号" align="center" prop="code" />
          <el-table-column label="屏幕名称" align="center" prop="name" />
          <el-table-column label="在线状态" align="center" prop="networkStatus">
            <template #default="scope">
              <dict-tag :options="network_status" :value="scope.row.networkStatus" :style="{ color: scope.row.networkStatus === '0' ? 'red' : 'green' }" />
            </template>
          </el-table-column>
          <el-table-column label="配置时间" align="center" prop="createTime" />
        </el-table>
        <el-pagination small background layout="total, prev, pager, next" :total="totalView" @current-change="handleViewCurrentChange" />
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="screenSwitch">
import {
  listScreenStrategy,
  addScreenStrategy,
  updateScreenStrategy,
  delScreenStrategy,
  release,
  clearScreenStrategy,
  getScreenStrategyInfoScreenList
} from '@/api/light/screenStrategy'
import { buildingTree } from '@/api/building/buildingInfo'
import { getProgramList, delProgramStrategy, auditProgramStrategy, releaseProgramStrategy, getDeviceInfoList, listScreen } from '@/api/light/screenProgram'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listGroup } from '@/api/light/group'
import OperatePanel from './components/OperatePanel.vue'
import EditPanel from './components/EditPanel.vue'
import ViewPanel from '@/views/components/screen/ViewPanel.vue'
import AuditPanel from './components/AuditPanel'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const { state, enable_status, network_status, light_group_purpose, screen_publication_type } = proxy.useDict(
  'state',
  'enable_status',
  'network_status',
  'light_group_purpose',
  'light_group_type',
  'screen_publication_type'
)
const checkAll = ref(true)
const isIndeterminate = ref(false)
const openView = ref(false) //应用设备dialog显隐
const loadingView = ref(true)
const showViewPanel = ref(false) //详情面板
const showAuditPanel = ref(false) //审核面板
const currentType = ref(1)
const releaseArr = ref([]) //发布数据
const isHasPermi = ref(false) //是否有审核权限
const currentSelection = ref([]) //当前选中发布设备or分组
const DaysList = ref([
  { value: 1, label: '周一' },
  { value: 2, label: '周二' },
  { value: 3, label: '周三' },
  { value: 4, label: '周四' },
  { value: 5, label: '周五' },
  { value: 6, label: '周六' },
  { value: 7, label: '周日' }
])
//用户权限
const userPermi = computed(() => userStore.permissions)
const dateRange = ref([])
watch(
  () => dateRange.value,
  (value) => {
    form.value.beginDate = value[0]
    form.value.endDate = value[1]
  }
)
const groupList = ref([])
const deviceList = ref([])
const screenProgramList = ref([])
const open = ref(false) //dialog显隐
const showEditPanel = ref(false) //编辑dialog显隐
const openRelease = ref(false)
const loading = ref(true)
const loadingRelease = ref(false)
const ids = ref([]) //多选id
const multiple = ref(true) //是否已多选
const total = ref(0)
const totalView = ref(0)
const totalRelease = ref(0)
const buildingOptions = ref(undefined)
const titleRelease = ref('')
const title = ref('')
const currentId = ref(0) //查看详情数据id
const releaseDeviceList = ref([])
const idArr = ref([])
const data = reactive({
  form: {
    checkedDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    period: '1,2,3,4,5,6,7',
    playType: '定时播放',
    lightScreenStrategyActList: [
      {
        type: '1',
        executeTime: '',
        idx: '',
        act: '1',
        actValue: '',
        sunriseAct: '',
        sunsetAct: '',
        sunriseActValue: '',
        sunsetActValue: '',
        condition: '',
        symbol: '',
        conditionValue: ''
      }
    ]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null
  },
  addForm: {},
  queryParamsRelease: {
    pageNum: 1,
    pageSize: 10,
    screenStrategyId: null,
    type: null,
    ids: null,
    buildingId: null,
    deviceName: null,
    purpose: null,
    name: null,
    strategyName: null
  },
  queryParamsView: {
    pageNum: 1,
    pageSize: 10,
    screenStrategyId: null,
    poleId: null,
    buildingId: null,
    imeiName: null,
    name: null
  },
  rules: {
    name: [{ required: true, message: '策略名称不能为空', trigger: ['blur', 'change'] }]
  }
})
const { queryParams, queryParamsRelease, queryParamsView, form, rules, addForm } = toRefs(data)
const handleCheckAllChange = (val) => {
  form.value.checkedDays = val ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] : []
  isIndeterminate.value = false
  form.value.period = '1,2,3,4,5,6,7'
}
const handleCheckedCitiesChange = (value) => {
  const arr = []
  value.forEach((item) => {
    DaysList.value.forEach((item1, index) => {
      if (item1.label === item) {
        arr.push(index + 1)
      }
    })
  })
  form.value.period = arr.join(',')
  const checkedCount = value.length
  checkAll.value = checkedCount === DaysList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < DaysList.value.length
}

// 查看设备列表dialog
const jumpDetail = (row) => {
  openView.value = true
  queryParamsView.value.screenStrategyId = row.id
  releaseDeviceList.value = row.ids

  getDeviceList()
}
/** 查询照明策略列表 */
function getList() {
  loading.value = true
  getProgramList(queryParams.value).then((response) => {
    screenProgramList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getCheckedNodes(val) {
  idArr.value = []
  idArr.value.push(val.id)
  findChildrenId(val, 'children')
}
// 发布dialog--获取发布list
function getReleaseList(val) {
  if (val) {
    currentType.value = val
  }
  currentType.value = val || currentType.value
  switch (queryParamsRelease.value.type) {
    // 发布类型--设备
    case '1':
      loadingRelease.value = true
      listScreen({
        pageNum: queryParamsRelease.value.pageNum,
        pageSize: queryParamsRelease.value.pageSize,
        buildingIds: idArr.value.join(','),
        poleName: queryParamsRelease.value.poleName,
        name: queryParamsRelease.value.name
        //type: currentType.value
      }).then((response) => {
        groupList.value = response.rows
        totalRelease.value = response.total
        loadingRelease.value = false
      })
      break
    // 发布类型--设备分组
    case '2':
      loadingRelease.value = true
      console.log('queryParamsRelease', queryParamsRelease.value)
      listGroup({
        pageNum: queryParamsRelease.value.pageNum,
        pageSize: queryParamsRelease.value.pageSize,
        //分组名称
        name: queryParamsRelease.value.name,
        //发布类型
        type: '3',
        //分组用途
        purpose: queryParamsRelease.value.purpose
      }).then((response) => {
        groupList.value = response.rows
        totalRelease.value = response.total
        loadingRelease.value = false
      })
      break
    default:
      break
  }
}

// 取消按钮
function cancelAdd() {
  open.value = false
  console.log('add')
}
function cancelEdit() {
  showEditPanel.value = false
  console.log('edit')
}
function cancelAudit() {
  console.log('audit')
  showAuditPanel.value = false
}

// 表单重置
function reset() {
  checkAll.value = true
  form.value = {
    id: null,
    name: null,
    beginDate: null,
    endDate: null,
    trig: null,
    period: '1,2,3,4,5,6,7',
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    checkedDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  }
  form.value.lightScreenStrategyActList = [
    {
      type: '1',
      executeTime: '',
      idx: '',
      act: '1',
      actValue: '',
      sunriseAct: '',
      sunsetAct: '',
      sunriseActValue: '',
      sunsetActValue: '',
      condition: '',
      symbol: '',
      conditionValue: ''
    }
  ]
  proxy.resetForm('screenStrategyRef')
}

/** 总list搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 设备dialog搜索按钮操作 */
function handleQueryDevice() {
  queryParamsView.value.pageNum = 1
  getDeviceList()
}
/** 设备dialog重置按钮操作 */
function resetQueryDevice() {
  proxy.resetForm('viewRef')
  handleQueryDevice()
}
/** 设备dialog关闭清空表单 */
function closeDeviceList() {
  proxy.resetForm('viewRef')
}
/** 发布dialog关闭清空表单 */
function closeReleaseList() {
  proxy.resetForm('releaseRef')
}
// 设备列表--获取设备list
function getDeviceList() {
  getDeviceInfoList({
    pageNum: queryParamsView.value.pageNum,
    pageSize: queryParamsView.value.pageSize,
    ids: releaseDeviceList.value,
    poleCode: queryParamsView.value.poleCode,
    poleName: queryParamsView.value.poleName,
    buildingId: queryParamsView.value.buildingId,
    name: queryParamsView.value.name
  }).then((response) => {
    deviceList.value = response.rows
    totalView.value = response.total
    loadingView.value = false
  })
}
/** 发布页面搜索按钮操作 */
function handleQueryRelease() {
  queryParamsRelease.value.pageNum = 1
  getReleaseList()
}
// 分页
const handleReleaseCurrentChange = (val) => {
  queryParamsRelease.value.pageNum = val
  getReleaseList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
/** 发布页面重置按钮操作 */
function resetQueryRelease() {
  proxy.resetForm('releaseRef')
  handleQueryRelease()
}

// 总list--分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 设备列表dialog--分页
const handleViewCurrentChange = (val) => {
  queryParamsView.value.pageNum = val
  getDeviceList()
}
const selectable = (row, index) => {
  return row.canDeletedFlag === 1
}
// 总list--多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}

// 总list--多选框选中数据
function handleReleaseSelectionChange(selection) {
  currentSelection.value = selection
}
// 发布
const handleRelease = (row) => {
  console.log('发布', row)
  titleRelease.value = '策略发布'
  queryParamsRelease.value.type = '1' // type=1-->设备，type=2-->设备分组
  queryParamsRelease.value.strategyName = row.name
  queryParamsRelease.value.programStrategyId = row.id
  queryParamsRelease.value.periodName = row.periodName
  queryParamsRelease.value.beginDate = row.beginDate
  queryParamsRelease.value.endDate = row.endDate
  getReleaseList()
  openRelease.value = true
}
//审核
const handleAudit = (row) => {
  showAuditPanel.value = true
  title.value = '审核节目策略'
  currentId.value = row.id
}
//提交审核
const handleSubmitAudit = (row) => {
  const _ids = row.id || ids.value
  ElMessageBox.confirm('是否提交审核？', '提交审核', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      isAutoAudit(row.id)
    })
    .catch(() => {})
}
//是否自动审核
const isAutoAudit = (val) => {
  //如果具备审核权限，自动审核
  userPermi.value.map((item) => {
    if (item === 'light:screenProgramStrategy:review') {
      isHasPermi.value = true
    }
  })
  //如果有权限，弹出是否自动审核
  if (userPermi.value[0] === '*:*:*' || isHasPermi.value) {
    ElMessageBox.confirm('是否自动审核？', '审核', {
      confirmButtonText: '审核通过',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then((action) => {
        //确认自动审核
        if (action === 'confirm') {
          const params = {
            id: val,
            reviewStatus: '3'
          }
          auditProgramStrategy(params).then((res) => {
            ElMessage({ type: 'success', message: '审核成功' })
            getList()
          })
        }
      })
      .catch((err) => {
        //取消自动审核时仅提交审核
        if (err === 'cancel') {
          const params = {
            id: val,
            reviewStatus: '2'
          }
          auditProgramStrategy(params).then((res) => {
            ElMessage({ type: 'success', message: '提交成功' })
            getList()
          })
        }
      })
  } else {
    const params = {
      id: val,
      reviewStatus: '2'
    }
    auditProgramStrategy(params).then((res) => {
      ElMessage({ type: 'success', message: '提交成功' })
      getList()
    })
  }
}
// 查看
const handleView = (row) => {
  showViewPanel.value = true
  title.value = '查看节目策略'
  currentId.value = row.id
}
// 编辑
const handleUpdate = (row) => {
  showEditPanel.value = true
  title.value = '修改节目策略'
  currentId.value = row.id
}
/** 新增按钮操作 */
function handleAdd() {
  open.value = true
  currentId.value = 0
  title.value = '新增节目策略'
}
// 取消发布按钮
function closeRelease() {
  openRelease.value = false
  resetQueryRelease()
}
/** 确定发布按钮 */
function submitRelease() {
  releaseArr.value = []
  if (currentSelection.value.length) {
    currentSelection.value.map((item) => {
      const obj = {}
      obj.targetId = item.id
      obj.status = '1'
      obj.type = queryParamsRelease.value.type
      obj.programStrategyId = queryParamsRelease.value.programStrategyId
      releaseArr.value.push(obj)
    })
    const params = {
      programStrategyId: queryParamsRelease.value.programStrategyId,

      lightProgramStrategyTargets: releaseArr.value
    }
    releaseProgramStrategy(params).then((response) => {
      proxy.$modal.msgSuccess('发布成功')
      openRelease.value = false
      getList()
    })
  } else {
    ElMessage({ type: 'info', message: '请选择至少一个设备/分组发布' })
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否删除该策略？')
    .then(function () {
      return delProgramStrategy(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'smartlight/lightProgramStrategy/export',
    {
      ...queryParams.value
    },
    `显示屏节目策略_${new Date().getTime()}.xlsx`
  )
}
//关闭新增弹窗
const handleAddFormClose = () => {
  open.value = false
  getList()
}

//关闭编辑弹窗
const handleEditFormClose = () => {
  showEditPanel.value = false
  getList()
}
//关闭审核弹窗
const handleAuditFormClose = () => {
  showAuditPanel.value = false
  getList()
}
// 设备列表--层级树列表
function getBuildingTree() {
  buildingTree().then((response) => {
    buildingOptions.value = response.data
  })
}
//递归
function findChildrenId(data, children) {
  for (const key in data) {
    if (key === children) {
      data[key].map((item) => {
        idArr.value.push(item.id)
        if (item.children) {
          findChildrenId(item, 'children')
        }
      })
    }
  }
}
onMounted(() => {
  getList()
  getBuildingTree()
})
</script>
<style lang="scss" scoped></style>
