<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="图层名称" prop="layerName">
        <el-input
          v-model="queryParams.layerName"
          placeholder="请输入图层名称"
          clearable
          @keyup.enter.native="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="['system:layers:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:layers:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:layers:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="layersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图层名称" align="center" prop="layerName" />
      <el-table-column label="图层地址" align="center" prop="layerUrl" />
      <el-table-column label="航拍图地址" align="center" prop="tiffUrl" />
      <el-table-column label="高程文件" align="center" prop="ascUrl" />
      <el-table-column label="JPG文件是否生成" align="center" prop="jpgUrl">
        <template #default="scope">
          <span>
            <el-tag v-if="scope.row.jpgUrl"> 已生成 </el-tag>
            <el-tag v-else type="danger"> 未生成 </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="图层坐标体系" align="center" prop="jpgUrl">
        <template #default="scope">
          <span>
            {{scope.row.coordinateSystem.name}}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleCheck(scope.row)"
            >tif转jpg</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleOpenUser(scope.row)"
            >用户分配</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:layers:remove']"
            >删除</el-button
          >
        </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"
    />

    <!-- 添加或修改部门对话框 -->

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="图层名称" prop="layerName">
              <el-input v-model="form.layerName" placeholder="请输入图层名称" />
            </el-form-item>
            <el-form-item label="图层地址" prop="layerUrl">
              <el-input
                type="textarea"
                v-model="form.layerUrl"
                placeholder="请输入图层地址"
              />
            </el-form-item>
            <!--   <el-form-item label="文件夹名称" prop="fileLoad">
              <el-input
                type="textarea"
                v-model="form.fileLoad"
                placeholder="请输入文件夹名称"
              />
            </el-form-item> -->
            <el-form-item label="航拍图地址" prop="tiffUrl">
              <el-input
                type="textarea"
                v-model="form.tiffUrl"
                placeholder="请输入航拍图地址"
              />
            </el-form-item>
            <el-form-item label="高程文件" prop="ascUrl">
              <el-input
                type="textarea"
                v-model="form.ascUrl"
                placeholder="请输入高成文件"
              />
            </el-form-item>
            <el-form-item label="坐标体系" prop="ascUrl">
              <el-select
              style="width: 100%"
              v-model="form.coordinateSystemId"

              placeholder="请选择"
              size="large"
            >
              <el-option  :label="item.name" :value="item.id" v-for="item in coordList" />

            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="userSelect"
      v-model="openUser"
      width="700px"
      append-to-body
    >
      <el-transfer
        v-model="userQuery"
        filterable
        :filter-method="filterMethod"
        filter-placeholder="筛选用户"
        :titles="['所有用户', '已选用户']"
        :button-texts="['移除', '添加']"
        :data="userData"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUser">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Layers">
import {
  listLayers,
  getLayers,
  delLayers,
  addLayers,
  authUserGet,
  authUserPut,
  tifConvert,
  updateLayers,
} from "@/api/system/layers";
import {
  list,
} from "@/api/system/coordinateSystem";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const data = reactive({
  // 按钮loading
  buttonLoading: false,
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 图层管理表格数据
  layersList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    layerName: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    layerName: [
      { required: true, message: "图层名称不能为空", trigger: "blur" },
    ],
    layerUrl: [
      { required: true, message: "图层地址不能为空", trigger: "blur" },
    ],
    tiffUrl: [
      { required: true, message: "航拍图地址不能为空", trigger: "blur" },
    ],
    ascUrl: [{ required: true, message: "高成文件不能为空", trigger: "blur" }],

    fileLoad: [
      { required: true, message: "文件夹名称不能为空", trigger: "blur" },
    ],
  },
});

const {
  open,
  showSearch,
  queryParams,
  form,
  ids,
  rules,
  title,
  layersList,
  total,
  multiple,
  single,
  loading,
  buttonLoading,
} = toRefs(data);
const userSelect = ref("图层分配用户");

const coordList=ref([

])
const openUser = ref(false);




const userData = ref([]);
const userQuery = ref([]);

const filterMethod = (query, item) => {
  return item.initial.toLowerCase().includes(query.toLowerCase());
};
// 表单重置
function reset() {
  form.value = {
    id: undefined,
    layerName: undefined,
    layerUrl: undefined,
    tiffUrl: undefined,
    ascUrl: undefined,
    jpgUrl: undefined,
    createTime: undefined,
    updateTime: undefined,
    createBy: undefined,
    updateBy: undefined,
    fileLoad: undefined,
  };
  proxy.resetForm("deptRef");
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加图层管理";
}
//用户分配
function handleOpenUser(row) {
  authUserGet(row.id).then((res) => {
    form.value.id = row.id;
    userQuery.value = res.data;
    openUser.value = true;
  });
}
function handleCheck(row) {
  proxy.$modal
    .confirm("是否确认将当前tif生成图片JPG")
    .then(() => {
      tifConvert(row.id).then((res) => {
        getList();
        proxy.$modal.msgSuccess("操作成功");
      });
    })
    .then(() => {})
    .catch(() => {})
    .finally(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateLayers(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addLayers(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  openUser.value = false;
  reset();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 查询图层管理列表 */
function getList() {
  //  loading.value = false;
  loading.value = true;
  listLayers(queryParams.value).then((response) => {
    layersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
//开始分配
function submitUser() {
  console.log(userQuery.value);
  let data = {
    layersId: form.value.id,
    userIds: userQuery.value,
  };
  console.log(data);
  proxy.$modal
    .confirm("是否将当前图层分配给已选用户？")
    .then(() => {
      authUserPut(data).then((res) => {
        proxy.$modal.msgSuccess("分配成功");
        openUser.value = false;
      });
    })
    .then(() => {})
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const idsData = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除图层管理编号为"' + idsData + '"的数据项？')
    .then(() => {
      loading.value = true;
      return delLayers(idsData);
    })
    .then(() => {
      loading.value = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}
function handleUpdate(row) {
  loading.value = true;
  reset();
  const id = row.id || ids.value;
  getLayers(id).then((response) => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改图层管理";
  });
}
getList();
const generateData = new Promise((resolve, reject) => {
    listUser().then((res) => {
      console.log(res);
      let data = []
      const states = res.rows;

      states.forEach((item, index) => {
        data.push({
          label: item.nickName,
          key: item.userId,
          initial: item.nickName,
        });
      });
      console.log(data);
      resolve(data);
    });
  });

const getGEPSData=new Promise((resolve,reject)=>{
    list().then(res=>{
      console.log(res)
      resolve(res.rows);
    })
  })
 Promise.all([generateData, getGEPSData]).then(res=>{

    userData.value = res[0];
    coordList.value=res[1]
})


</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: end;
}
</style>
