<template>
  <el-dialog v-model="props.gzkShow" title="选择图片" width="1000px" :before-close="close">
    <div class="main">
      <!-- 查询条件部分 -->
      <section class="query-flex">
        <section class="query-section">
          <section class="flex">
            <el-input placeholder="请输入安全标识名称进行查询" v-model="pageData.listQuery.signName" clearable
              style='width:250px'></el-input>
            <MOSTY.DictTree class="ml12" v-model="pageData.listQuery.signType" :zdlist="aqbslist"
              :placeholder='"安全标识类型"' :type='"array"' style="width: 250px;" />
            <MOSTY.DictRidioAndSelect class="ml12" style="width: 250px;" :dictData="D_SAFETY_SIGN_BUSINESS"
              v-model="pageData.listQuery.businessType" selectType="select" :placeholder='"业务分类"' :disabled="false" />
          </section>
        </section>
        <div class="query-btn">
          <el-button @click="seachchange" class="ml6">
            <el-icon>
              <Search />
            </el-icon>
            <span>查询</span>
          </el-button>
          <el-button @click="handleRest">
            <el-icon>
              <Refresh />
            </el-icon>
            <span>重置</span>
          </el-button>
        </div>
      </section>

      <!-- 已选择的图片区域 -->
      <div class="title">已选择的图片</div>
      <div class="imgbox">
        <div v-for="(it, ind) in list" :key="ind" class="img-item">
          <img :src="getImgUrl(`${it.signImg}.png`)" alt="" @click="delImg(it)">
          <div class="img-name">{{ it.signName }}</div>
        </div>
      </div>

      <!-- 可选图片区域 - 从表格数据中获取 -->
      <div class="title">点击下方图片选择合适的安全标志</div>
      <div class="imgbox">
        <div v-for="item in availableImages" :key="item.id" class="img-item">
          <img :src="getImgUrl(`${item.signImg}.png`)" alt="" @click="addImg(item)">
          <div class="img-name">{{ item.signName }}</div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="save">保存</el-button>
        <el-button @click="close">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import { getImgUrl } from "@/utils/tools.js"
import { ref, watch, getCurrentInstance, onMounted, reactive, computed } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();

const {
  D_SAFETY_SIGN_BUSINESS,
} = proxy.$dict("D_SAFETY_SIGN_BUSINESS")

const emits = defineEmits(["close"]);

const props = defineProps({
  gzkShow: false,
  imgList: {
    type: Array,
    default: []
  }
});

const list = ref([])
const tableloading = ref(false)
const aqbslist = ref([])

// 分页数据
const pageData = reactive({
  listQuery: {
    signName: "",
    signType: "",
    businessType: "",
    pageCurrent: 1,
    pageSize: 16, // 调整为适合图片展示的数量
  },
  tableData: [],
  pageConfiger: {
    pageSize: 16,
    pageCurrent: 1,
    total: 0
  }
})

// 计算可用的图片（过滤掉已选择的）
const availableImages = computed(() => {
  const selectedIds = list.value.map(item => item.id);
  return pageData.tableData.filter(item => !selectedIds.includes(item.id));
})

// 安全标识类型字典
const resultAqbs = {};

watch(
  () => props.imgList,
  (val) => {
    list.value = val || [];
  },
  { deep: true, immediate: true }
)

// 查询
const seachchange = () => {
  gettablist()
}

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.listQuery.pageCurrent = val
  pageData.pageConfiger.pageCurrent = val
  gettablist()
}

//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.listQuery.pageSize = val
  pageData.pageConfiger.pageSize = val
  gettablist()
}

// 重置
const handleRest = () => {
  pageData.listQuery.signName = ""
  pageData.listQuery.signType = ""
  pageData.listQuery.businessType = ""
  pageData.listQuery.pageCurrent = 1
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}

// 添加图片
const addImg = (item) => {
  if (list.value.length >= 4) {
    ElMessage.warning("最多添加4张图片");
    return;
  }
  list.value.push(item)
}

// 删除图片
const delImg = (item) => {
  list.value = list.value.filter(it => it.id !== item.id)
}

// 保存
const save = () => {
  emits('close', list.value)
}

// 关闭
const close = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits('close')
    })
    .catch(() => {
      // catch error
    })
}

//安全标识库分页查询
const gettablist = () => {
  tableloading.value = true
  postApi(pageData.listQuery, '/mosty-jcgl/safetySign/getSafetySignPage')
    .then((res) => {
      if (res) {
        tableloading.value = false
        pageData.tableData = res.records
        pageData.pageConfiger.total = res.total
      }
    })
    .catch(() => {
      tableloading.value = false
    })
}

//获取安全标识类型
const getaqbslb = () => {
  getApi({
    zdbh: "D_TB_JCYWLX",
    dm: "2003",
    level: 2
  }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    aqbslist.value = res[0].itemList
    aqbslist.value.forEach(obj => {
      if (obj.dm && obj.zdmc) {
        resultAqbs[obj.dm] = obj.zdmc;
      }
    });
    gettablist();
  })
}

onMounted(() => {
  getaqbslb();
})
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  text-align: center;
  background: rgb(242, 242, 242);
  min-height: 500px;

  .query-flex {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .query-section {
      width: 68%;
    }

    .query-btn {
      width: 360px;
      display: flex;
      justify-content: end;
    }
  }

  .title {
    text-align: center;
    line-height: 60px;
    color: red;
    text-decoration: underline;
    font-size: 13px;
    margin-top: 20px;
  }

  .imgbox {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 15px;
    padding: 0 20px;

    .img-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;

      >img {
        width: 100px;
        height: 100px;
        object-fit: contain;
        background: white;
        border: 2px solid #ddd;
        border-radius: 4px;
        padding: 5px;
        transition: all 0.3s ease;

        &:hover {
          border-color: #409eff;
          transform: scale(1.05);
        }
      }

      .img-name {
        margin-top: 8px;
        font-size: 12px;
        color: #666;
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .fenye {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>