<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="layerParams.layerName"
            placeholder="请输入图层名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="layerOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="layerTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <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.createBy"
              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-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="id"
            width="150"
          />
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column label="存档时间" align="center" prop="createTime" />

          <el-table-column label="是否分配" align="center" prop="createBy">
            <template #default="scope">
              <div>
                <el-tag v-if="scope.row.authUserCount" type="success"
                  >已分配({{ scope.row.authUserCount }})</el-tag
                >
                <el-tag v-else type="danger">无分配</el-tag>
              </div>
            </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="handleOpenUser(scope.row)"
                >存档分配</el-button
              >
              <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:porfiles: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-col>
    </el-row>

    <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="profiles">
import  * as requestUrl from "@/api/system/porfiles";
import { listLayers } from "@/api/system/layers";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();

const props = defineProps({
  type:String
})
const data = reactive({
  // 按钮loading
  buttonLoading: false,
  // 遮罩层
  loading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 图层管理表格数据
  layersList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createBy: undefined,
    layersId: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
});

const {
  open,
  showSearch,
  queryParams,
  form,
  ids,
  title,
  layersList,
  total,
  multiple,
  single,
  loading,
  buttonLoading,
} = toRefs(data);
const userSelect = ref("档案分配用户");
const openUser = ref(false);
const layerName = ref();

const layerParams = reactive({
  layerName: undefined,
  pageNum: 1,
  pageSize: 100,
});
watch(layerParams, (val) => {

  console.log(val.layerName);
  proxy.$refs["layerTreeRef"].filter(val.layerName);
});
const getLayerTree = () => {
  const data = [];
  return new Promise((resolve, reject) => {
    listLayers(layerParams).then((res) => {
      let parent = [
        {
          id: 0,
          label: "所有图层",
          parentId: -1,
          children: res.rows.map((item) => {
            return {
              id: item.id,
              label: item.layerName,
              parentId: 0,
            };
          }),
        },
      ];

      resolve(parent);
    });
  });
};

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 = "添加图层管理";
}
//用户分配
async function handleOpenUser(row) {
  let res = await  requestUrl[props.type+'layerUsers'](row.id);
  form.value.id = row.id;
  userData.value = res.data.map((item) => {
    return {
      label: item.nickName,
      key: item.userId,
      initial: item.nickName,
    };
  });
  res = await requestUrl[props.type+'authUserGet'](row.id);
  userQuery.value = res.data
  openUser.value = true;
}
const filterNode=(value,data)=>{
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

//所有用户
const generateData = () => {
  const data = [];
  return new Promise((resolve, reject) => {
    listUser().then((res) => {
      console.log(res);

      const states = res.rows;

      states.forEach((item, index) => {
        data.push({
          label: item.nickName,
          key: item.userId,
          initial: item.nickName,
        });
      });
      console.log(data);
      resolve(data);
    });
  });
};
// generateData().then((res) => {
//   console.log(res)
//   debugger
//   userData.value = res;
// });
/** 提交按钮 */
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;

  requestUrl[props.type+'list'](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 handleDelete(row) {
  const idsData = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除档案管理编号为"' + idsData + '"的数据项？')
    .then(() => {
      loading.value = true;
      return profilesDel(idsData);
    })
    .then(() => {
      loading.value = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}
//开始分配
function submitUser() {
  console.log(userQuery.value);
  let data = {
    profilesId: form.value.id,
    userIds: userQuery.value,
  };
  console.log(data);
  proxy.$modal
    .confirm("是否将当前图层分配给已选用户？")
    .then(() => {
      requestUrl[props.type+'authUserPut'](data).then((res) => {
        proxy.$modal.msgSuccess("分配成功");
        openUser.value = false;
        getList()
      });
    })
    .then(() => {})
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

const layerOptions = ref();
getLayerTree().then((res) => {
  layerOptions.value = res;
});
const handleNodeClick = (e) => {
  console.log(e);
  queryParams.value.layersId = e.id;
  getList();
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: end;
}
</style>
