<template>
  <div class="tab-content h-full">
    <div class="subtitle"><span></span> <el-button type="primary" v-auth="'add'" size="small" @click="addDevice()">添加场景</el-button></div>
    <el-table :data="tableData" style="width: 100%" v-loading="loading" max-height="calc(100vh - 280px)">
      <el-table-column prop="id" label="ID" min-width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="name" label="场景名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sceneType" label="触发方式" align="center">
        <template #default="scope">
          <el-tag size="small" v-if="scope.row.sceneType == 'device'">设备触发</el-tag>
          <el-tag size="small" v-if="scope.row.sceneType == 'manual'">手动触发</el-tag>
          <el-tag size="small" v-if="scope.row.sceneType == 'timer'">定时触发</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag size="small" type="success" v-if="scope.row.status == 1">启用</el-tag>
          <el-tag size="small" type="info" v-if="scope.row.status == 0">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="场景描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="160" align="center"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button size="small" text type="primary" v-auth="'detail'" @click="$router.push('/iotmanager/scene/manage/' + scope.row.id)">场景详情</el-button>
          <el-button size="small" text type="warning" v-auth="'del'" @click="onDel(scope.row)">解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
    <el-dialog title="添加场景" v-model="isShowDialog" width="400">
      <el-form v-if="isShowDialog">
        <el-form-item label="场景" style="margin-bottom: 0;">
          <el-select v-model="form.resourcesKey" filterable placeholder="选择场景" :clearable="false" style="width: 100%">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import sceneApi from '/@/api/scene';
import api from '/@/api/projects';
import { useSearch } from '/@/hooks/useCommon';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
const route = useRoute();

const props = defineProps({ resourcesTypes: Number })
const isShowDialog = ref(false)
const options = ref<any[]>([])
const resourcesTypes = props.resourcesTypes
const projectsCode = route.params.id

const baseForm = {
  resourcesKey: '',
  projectsCode,
  resourcesTypes
}

const form = reactive({
  ...baseForm
})

const { params, tableData, getList, loading } = useSearch<any[]>(sceneApi.manage.getList, 'Data', { ids: [], status: undefined });

getOptions();
getSourceList();

function getSourceList() {
  api.getProjectResourcesByCode({ projectsCode }).then((res: any) => {
    params.ids = (res || []).filter((item: any) => item.resourcesTypes === resourcesTypes).map((item: any) => item.resourcesKey)
    if (!params.ids.length) {
      params.pageNum = 1
      tableData.value = []
    } else {
      getList();
    }
  })
}


function getOptions() {
  sceneApi.manage.getList({ status: -1, pageNum: 1, pageSize: 500 }).then((res: any) => {
    options.value = (res?.list || []).map((item: any) => ({ label: item.name, value: item.id }))
  })
}

function onCancel() {
  Object.assign(form, baseForm)
  isShowDialog.value = false
}

function onSubmit() {
  if (!form.resourcesKey) return ElMessage('请先选择场景')
  api.bindResources(form).then((res: any) => {
    onCancel()
    getSourceList()
    ElMessage.success('添加成功')
  })
}

function addDevice() {
  isShowDialog.value = true
}

function onDel(row: any) {
  ElMessageBox.confirm(`确定要解绑该场景？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.unbindResources({
      projectsCode,
      resourcesTypes,
      resourcesKey: row.id
    }).then(() => {
      getSourceList()
      ElMessage.success('解绑成功')
    })
  });
}

</script>
