<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <!-- <el-form-item label="大屏名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入大屏名称" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['big:screen:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" v-hasPermi="['big:screen:edit']"
          @click="handleUpdate(ids[0])">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" v-hasPermi="['big:screen:delete']"
          @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="screenList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="大屏编号" prop="id" width="120" />
      <el-table-column label="大屏名称" prop="title" :show-overflow-tooltip="true" width="300" />
      <!-- <el-table-column label="" prop="path" :show-overflow-tooltip="true" /> -->
      <el-table-column label="大屏图片" align="center">
        <template #default="scope">
          <el-image :src="scope.row.img" :preview-src-list="[scope.row.img]" fit="cover"
            style="width: 100px; height: 100px">
            <template #error>
              <div class="image-slot">
                <el-icon size="100"><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" width="180" />
      <el-table-column label="是否发布" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.releases" type="success">已发布</el-tag>
          <el-tag v-else type="danger">未发布</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-tooltip :content="`${scope.row.releases == true ? '取消发布' : '发布'}`" placement="top">
            <el-button link :type="`${scope.row.releases == true ? 'danger' : 'primary'}`"
              v-hasPermi="['big:screen:releases']" icon="Position" @click="changeReleases(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="链接" placement="top" v-if="scope.row.releases == true">
            <el-button link type="primary" icon="Link" @click="toScreen(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)"
              v-hasPermi="['big:screen:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" v-hasPermi="['big:screen:delete']"
              @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="分配用户" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="CircleCheck" v-hasPermi="['big:screen:patch']"
              @click="handleAuthUser(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <add_edit @closeDialog="open = false" :type="type" :title="title" :form="form" :visible="open"
      @refreshTable="getList" />
    <!-- 分配用户 -->
    <el-dialog v-model="authOpen" title="分配用户" width="30%">
      <el-form :model="authUserForm">
        <el-form-item label="用户列表">
          <el-checkbox-group v-model="authUserForm.userIds">
            <el-checkbox :label="item.userId" v-model="authUserForm.userIds" v-for="item in arrUserList">{{ item.userName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="authOpen = false">取消</el-button>
          <el-button type="primary" @click="assignUserAdd">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="imgDialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" class="img-preview" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { listUser } from "@/api/system/user";
import { getScreen, updateScreen, assignUser, delScreen, getAssignUser, testScreen } from '@/api/big/screen'
import add_edit from './components/add_edit.vue'

const { proxy } = getCurrentInstance();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: '',
  },
  rules: {
    roleTitle: [{ required: true, message: "大屏名称不能为空", trigger: "blur" }],
    roleUrl: [{ required: true, message: "大屏地址不能为空", trigger: "blur" }],
    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

// testScreen({}).then(res => {
//  alert(JSON.stringify(res))
// })

let screenList = ref([])

const arrUserList = ref([])
const imgDialogVisible = ref(false)
const dialogImageUrl = ref('')
const open = ref(false);
const authOpen = ref(false);
const loading = ref(false);
const showSearch = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const autnUserTitle = ref('');
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const file_list = ref([])
const userIds = ref([])
const authUserForm = ref({
  id: undefined,
  userIds: []
});
const type = ref("add");

function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(res => {
    arrUserList.value = res.rows
  })
}
/** 查询角色列表 */
function getList() {
  loading.value = true;
  // console.log(JSON.stringify(queryParams.value));
  getScreen(queryParams.value).then(res => {
    loading.value = false;
    screenList.value = res.rows.map(item => {
      const regex = /^(http|https):\/\/[^ "]+$/;
      let isTrue = regex.test(item.img);
      item.img = isTrue ? item.img : import.meta.env.VITE_APP_BASE_API + item.img
      return item
    });
    total.value = res.total;
  });

}

/** 重置新增的表单以及其他数据  */
function reset() {
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    title: undefined,
    url: undefined,
    releases: false,
    path: undefined,
    img: undefined,
    remark: undefined,
  };
  proxy.resetForm("roleRef");
}


/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 添加大屏 */
function handleAdd() {
  title.value = "添加大屏";
  form.value = {
    title: undefined,
    url: undefined,
    releases: false,
    path: undefined,
    img: undefined,
    remark: undefined,
  };
  file_list.value = []
  type.value = "add";
  open.value = true;
}
/** 修改大屏 */
function handleUpdate(id) {
  title.value = "修改大屏";
  screenList.value.find(item => {
    if (item.id == id) {
      form.value = item;
    }
  })
  if (form.value.img != '' && form.value.img != undefined) {
    file_list.value = [{
      name: form.value.path,
      url: form.value.img
    }]
  }
  type.value = "update";

  // console.log(form.value, 'form.value');
  open.value = true;
}

/**查询分配用户 */
function handleAuthUser(row) {
  autnUserTitle.value = "分配用户";
  authUserForm.value.id = row.id
  getAssignUser(row.id).then(res => {
    authUserForm.value.userIds = res.data
  })
  authOpen.value = true;
}

//分配用户
function assignUserAdd() {
  let ids = authUserForm.value.userIds.join(',')
  let data = { id: authUserForm.value.id, ids }
  assignUser(data).then(res => {
    authOpen.value = false;
    proxy.$modal.msgSuccess("分配成功");
  })
}

/** 删除按钮操作 */
function handleDelete(row) {

  const screenIds = row.id || ids.value.join(',');
  proxy.$modal.confirm('是否确认删除编号为"' + screenIds + '"的数据项？').then(function () {
    return delScreen(screenIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });

}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/**前往大屏 */
const toScreen = (row) => {
  window.open(row.url + '?hash=' + row.hash);
}

/**修改大屏发布状态 */
const changeReleases = (row) => {
  let msg = '';
  if (row.releases) {
    msg = '取消发布'
  } else {
    msg = '发布'
  }
  let data = { id: row.id, releases: !row.releases }
  proxy.$modal.confirm('是否确认' + msg + '编号为"' + row.id + '"的大屏？').then(function () {
    return updateScreen(data);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(msg + "成功");
  }).catch(() => { });

}

/** 图片预览 */
const handlePreview = (img) => {
  imgDialogVisible.value = true;
  dialogImageUrl.value = img;
}

getList();
getUserList();
</script>

<style lang="scss" scoped>
:deep(.el-table .el-table__cell) {
  z-index: auto;
}

.img-preview {
  max-width: 100%;
  max-height: 100%;
  display: block;
  margin: 0 auto;
}
</style>
