<template>
  <div class="app-container">
    <el-header>
      <i class="el-icon-back" @click="goBack"></i>
      资源目录管理
      <span>/详情</span>
    </el-header>
    <el-container v-if="directoryInfo">
      <div class="top">
        <span class="title">图层资源目录详情</span>
        <div class="directoryInfo">
          <span> 图层资源目录名称：{{ directoryInfo.name }}</span>
          <span> 图层资源目录编号： {{ directoryInfo.id }}</span>
          <span> 图层数量： {{ pageOptions.total }}</span>
          <span> 创建时间： {{ directoryInfo.pubDate }}</span>
          <span> 创建人：{{ directoryInfo.createUser }} </span>
        </div>
      </div>
      <div class="middle">
        <el-button type="primary" plain @click="dialogFormVisible = true">添加图层</el-button>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="基础字段" name="1">
              <el-form :model="editDataInfoForm">
                <el-form-item label="服务类型" style="font-size: 1rem" :label-width="'120px'">
                  <el-select style="width: 80%" v-model="editDataInfoForm.serviceType" placeholder="请选择">
                    <el-option v-for="item in serviceTypeOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="服务名称" prop="serviceName" style="font-size: 1rem" :label-width="'120px'"
                  v-if="editDataInfoForm.serviceType === '081100'">
                  <el-input v-model.trim="editDataInfoForm.serviceName"
                    placeholder="服务名称由两部分构成：数据服务url(如/iserver/services/data-supermap_shuili/rest);服务名称(如namespace:layer1)"
                    style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="服务名称" style="font-size: 1rem" :label-width="'120px'" v-else>
                  <el-input v-model.trim="editDataInfoForm.serviceName" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="服务别名" prop="serviceNameAlias" style="font-size: 1rem" :label-width="'120px'">
                  <el-input v-model.trim="editDataInfoForm.serviceNameAlias" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="服务地址" prop="serviceUrl" style="font-size: 1rem" :label-width="'120px'">
                  <el-input v-model.trim="editDataInfoForm.serviceUrl" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="服务token" prop="serviceToken" style="font-size: 1rem" :label-width="'120px'">
                  <el-input v-model.trim="editDataInfoForm.serviceToken" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="是否需要聚合" prop="isNeedCluster" style="font-size: 1rem" :label-width="'120px'"
                  v-if="editDataInfoForm.serviceType === '081100'">
                  <el-select style="width: 80%" v-model="editDataInfoForm.isNeedCluster" placeholder="请选择">
                    <!-- 是和否两种选择 -->
                    <el-option v-for="item in isNeedClusterOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否支持一键搜索" prop="isSupportFastQuery" style="font-size: 1rem" :label-width="'120px'"
                  v-if="editDataInfoForm.serviceType === '081100'">
                  <el-select style="width: 80%" v-model="editDataInfoForm.isSupportFastQuery" placeholder="请选择">
                    <!-- 是和否两种选择 -->
                    <el-option v-for="item in isSupportFastQueryOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="editDataInfoForm.serviceType === '030300'" label="服务索引" prop="serviceIndex"
                  style="font-size: 1rem" :label-width="'120px'">
                  <el-input v-model="editDataInfoForm.serviceIndex" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item v-show="['030300'].includes(editDataInfoForm.serviceType)" label="样式选择"
                  style="font-size: 1rem" :label-width="'120px'">
                  <div class="styleBtn">
                    <el-tag type="info" effect="plain" class="style-button" :class="{
                      'style-button-none': editDataInfoForm.relationStyleName,
                    }" @click="handleLayerStyleTypeChange">
                      {{
                        editDataInfoForm.relationStyleName
                          ? editDataInfoForm.relationStyleName
                          : "点击选择样式"
                      }}
                    </el-tag>
                    <el-button style="margin-left: 15px" :disabled="editDataInfoForm.relationStyleName === ''" @click="
                      editDataInfoForm.relationStyleName = '';
                    editDataInfoForm.relationStyleId = '';
                    ">取消选择样式</el-button>
                  </div>
                  <styleListDialogVue :visible="styleDialogVisible" :$currentStyleId="editDataInfoForm.relationStyleId"
                    @closeDialog="styleDialogVisible = false" @confirm="handleConfirm"></styleListDialogVue>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="扩展字段" name="2">
              <div class="fn-btns">
                <el-button type="primary" class="btn" @click="addRow">添加</el-button>
                <el-button type="danger" class="btn" @click="deleteRow">删除</el-button>
              </div>
              <el-table max-height="400px" :data="extendTable" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center"></el-table-column>
                <el-table-column prop="field" label="字段名称">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.field" :disabled="!scope.row.isEdit"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="alias" label="别名">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.alias" :disabled="!scope.row.isEdit"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="字段值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" :disabled="!scope.row.isEdit"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.isEdit" type="primary" icon="el-icon-success" size="mini"
                      @click="saveRow(scope.$index)">保存</el-button>
                    <el-button v-if="scope.row.isEdit" type="warning" icon="el-icon-error" size="mini"
                      @click="cancelRow(scope.$index)">取消</el-button>
                    <el-button v-if="!scope.row.isEdit" type="primary" icon="el-icon-edit" size="mini"
                      @click="editRow(scope.$index)">编辑</el-button>
                    <el-button v-if="!scope.row.isEdit" type="danger" icon="el-icon-delete-solid" size="mini"
                      @click="deleteRow(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="字段配置" v-if="showFieldExtend()" name="3">
              <div class="field-box">
                <div class="field-filter">
                  <el-input class="keyword-input" placeholder="请输入搜索字段" v-model="fieldValue" clearable>
                  </el-input>
                  <el-button class="search-btn">搜索</el-button>
                </div>
              </div>
              <el-table max-height="400px" :data="fieldsTable" border>
                <el-table-column type="index" width="50" align="center"></el-table-column>
                <el-table-column prop="field" label="字段名称">
                </el-table-column>
                <el-table-column prop="fieldName" label="字段别名">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.fieldName"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="fieldType" label="字段类型">
                </el-table-column>
                <el-table-column prop="isShow" label="支持查询" width="80" align="center">
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.isShow" :true-label="1" :false-label="0"></el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdateLayer">确 定</el-button>
          </div>
        </el-dialog>
        <div class="keyword-filter">
          <el-input class="keyword-input" placeholder="请输入内容" v-model="keyword" clearable>
          </el-input>
          <el-button class="search-btn">搜索</el-button>
        </div>
      </div>
      <div class="content">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" :index="(index) =>
            index + (pageOptions.pageNum - 1) * pageOptions.pageSize + 1
            " label="序号" width="50" header-align="center"></el-table-column>
          <el-table-column prop="id" label="图层资源目录编号" width="350">
          </el-table-column>
          <el-table-column prop="serviceNameAlias" label="图层资源名称">
          </el-table-column>
          <el-table-column prop="pubDate" label="创建时间"> </el-table-column>
          <el-table-column prop="createUser" label="创建人"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="prev, pager, next" :current-page.sync="pageOptions.pageNum"
          :total="pageOptions.total" :page-size="pageOptions.pageSize" @current-change="getLayerList">
        </el-pagination>
      </div>
    </el-container>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import styleListDialogVue from "./styleListDialog.vue";
import {
  saveOrUpdateLayerApi,
  getLayerListApi,
  deleteLayerApi,
  getDirectoryByIdApi,
  queryServiceInfoApi,
} from "@/api/aiSupervision/layerConfigApi.js";
export default {
  components: {
    styleListDialogVue,
  },
  data() {
    return {
      tableData: [],
      editDataInfoForm: {
        id: "",
        serviceType: "", //服务类型,wms/wmts/wfs/3d tiles/terrain
        serviceUrl: "", //服务地址
        serviceToken: "", //服务token
        isNeedCluster: "0",
        isSupportFastQuery: "0",
        serviceName: "", //服务名称
        serviceNameAlias: "", //服务别名
        serviceIndex: "", //服务索引
        dirId: "",
        dirNames: "",
        tileSize: "256",
        relationStyleId: "",
        relationStyleName: "",
      },
      directoryInfo: null, // 目录信息
      dialogTitle: "添加图层",
      isNeedClusterOptions: [
        {
          value: "0",
          label: "否",
        },
        {
          value: "1",
          label: "是",
        },
      ],
      isSupportFastQueryOptions: [
        {
          value: "0",
          label: "否",
        },
        {
          value: "1",
          label: "是",
        },
      ],
      serviceTypeOptions: [
        {
          value: "021102",
          label: "ArcGISRest图层",
        },
        {
          value: "081100",
          label: "SuperMapRest图层",
        },
        {
          value: "030300",
          label: "WFS200",
        },
        {
          value: "080100",
          label: "S3M图层",
        },
        {
          value: "",
          label: "XYZ底图",
        },
      ],
      pageOptions: {
        pageNum: 1,
        pageSize: 8,
        total: 0,
      },
      dialogFormVisible: false, //是否显示对话框
      keyword: "",
      styleDialogVisible: false, //是否显示样式选择对话框
      activeName: "1",
      extendTable: [],
      multipleSelection: [],
      activeFields: [],
      fieldsTable: [],
      queryServiceUrlMap: new Map(),
      fieldValue: "",
    };
  },
  watch: {
    keyword() {
      this.debouncedGetLayerList();
    },
    fieldValue() {
      this.searchField();
    },
    dialogFormVisible(val) {
      if (val === false) {
        this.initData();
      }
    },
    "editDataInfoForm.serviceUrl"(val) {
      if (val) {
        if (!this.queryServiceUrlMap.has(val)) {
          this.queryLayerByUrl(val);
        } else {
          this.fieldsTable = this.queryServiceUrlMap.get(val);
        }
      } else {
        this.fieldsTable = [];
      }
    },
  },
  created() {
    // 使用 lodash 的 debounce 函数创建防抖版本
    this.debouncedGetLayerList = debounce(this.getLayerList, 500);

    getDirectoryByIdApi(this.$route.query.id).then((res) => {
      this.directoryInfo = res.data.children[0];
      this.initData();
      this.getLayerList();
    });
  },
  methods: {
    searchField() {
      if (this.fieldValue === "") {
        this.fieldsTable = this.queryServiceUrlMap.get(
          this.editDataInfoForm.serviceUrl
        );
      } else {
        this.fieldsTable = this.fieldsTable.filter((item) =>
          item.field.includes(this.fieldValue)
        );
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    handleEdit(index, row) {
      this.editDataInfoForm.id = row.id;
      this.editDataInfoForm.serviceType = row.serviceType;
      this.editDataInfoForm.serviceName = row.serviceName;
      this.editDataInfoForm.serviceNameAlias = row.serviceNameAlias;
      this.editDataInfoForm.serviceUrl = row.serviceUrl;
      this.editDataInfoForm.serviceToken = row.serviceToken;
      this.editDataInfoForm.isNeedCluster = row.isNeedCluster;
      this.editDataInfoForm.isSupportFastQuery = row.isSupportFastQuery;
      this.editDataInfoForm.serviceIndex = row.serviceIndex;
      this.editDataInfoForm.relationStyleId = row.relationStyleId;
      this.editDataInfoForm.relationStyleName = row.relationStyleName;
      this.extendTable = (row.extendData && JSON.parse(row.extendData)) || [];
      this.activeFields = row?.fields?.map((item) => item.field) || [];
      this.dialogTitle = "编辑图层";
      this.dialogFormVisible = true;
    },

    handleDelete(row) {
      this.$confirm(
        "删除图层将同时删除该图层资源以及关联的图层数据，删除后将不可恢复，是否继续删除？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const res = await deleteLayerApi(row.id);
          if (res.success) {
            this.getLayerList();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取图层列表
    getLayerList() {
      const params = {
        pageNum: this.pageOptions.pageNum,
        pageSize: this.pageOptions.pageSize,
        data: {
          serviceName: this.keyword,
          dirId: this.directoryInfo.id,
        },
        params: {
          orderBy: "pub_date",
          sortBy: "asc",
        },
      };
      getLayerListApi(params).then((res) => {
        this.pageOptions.total = res.total;
        this.tableData = res.records;
      });
    },
    async saveOrUpdateLayer() {
      // const reg = /^(?=.{1,100}$)[\u4e00-\u9fa5\w:./-;]+$/;
      // if (!reg.test(this.editDataInfoForm.serviceName)) {
      //   this.$message({
      //     type: "info",
      //     message:
      //       "格式有误，目录名称仅支持中文、数字、字母、下划线、冒号，最大长度不超过100",
      //   });
      //   return;
      // }
      const params = {
        ...this.editDataInfoForm,
        extendData: JSON.stringify(this.extendTable),
        fields: this.fieldsTable,
      };
      this.queryServiceUrlMap.set(
        this.editDataInfoForm.serviceUrl,
        this.fieldsTable
      );
      await saveOrUpdateLayerApi(params);
      this.getLayerList();
      this.dialogFormVisible = false;
      this.fieldsTable = [];
      this.extendTable = [];
    },
    handleLayerStyleTypeChange() {
      this.styleDialogVisible = true;
    },
    handleConfirm(val) {
      this.editDataInfoForm.relationStyleId = val.id;
      this.editDataInfoForm.relationStyleName = val.name;
    },
    initData() {
      this.editDataInfoForm.id = "";
      this.editDataInfoForm.serviceUrl = "";
      this.editDataInfoForm.serviceToken = "";
      this.editDataInfoForm.isNeedCluster = "0";
      this.editDataInfoForm.isSupportFastQuery = "0";
      this.editDataInfoForm.serviceName = "";
      this.editDataInfoForm.serviceNameAlias = "";
      this.editDataInfoForm.serviceIndex = "";
      this.editDataInfoForm.relationStyleId = "";
      this.editDataInfoForm.relationStyleName = "";

      this.editDataInfoForm.serviceType = this.serviceTypeOptions[0].value;
      this.editDataInfoForm.dirId = this.directoryInfo.id;
      this.editDataInfoForm.dirNames = this.directoryInfo.name;
      this.editDataInfoForm.tileSize = "256";
      this.dialogTitle = "添加图层";
    },
    addRow() {
      const editRow = this.extendTable.find((item) => item.isEdit);
      if (editRow) {
        this.$message({
          type: "info",
          message: "请先保存当前编辑行",
        });
        return;
      }
      this.extendTable.push({
        id: "",
        field: "",
        alias: "",
        value: "",
        isEdit: true,
      });
    },
    deleteRow(index) {
      this.$messageBox
        .confirm("是否删除该行数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          if (index !== undefined) {
            this.extendTable.splice(index, 1);
          } else {
            this.extendTable = this.extendTable.filter(
              (item) => !this.multipleSelection.includes(item)
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editRow(index) {
      this.extendTable[index].isEdit = true;
    },
    cancelRow(index) {
      if (!this.extendTable[index].id) {
        this.extendTable.splice(index, 1);
      } else {
        this.extendTable[index].isEdit = false;
      }
    },
    saveRow(index) {
      if (!this.extendTable[index].id) {
        this.extendTable[index].id = sycim.Cesium.createGuid();
      }
      // 表格名字校验不重复
      const name = this.extendTable[index].field;
      const isRepeat = this.extendTable.some(
        (item, i) => item.field === name && i !== index
      );
      if (isRepeat) {
        this.$message({
          type: "info",
          message: "字段名称重复，请重新输入",
        });
        return;
      }
      this.extendTable[index].isEdit = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    showFieldExtend() {
      return ["021102", "081100", "030300"].includes(
        this.editDataInfoForm.serviceType
      );
    },
    queryLayerByUrl(url) {
      queryServiceInfoApi(url, {
        type: this.editDataInfoForm.serviceType,
        url: url,
        index: this.editDataInfoForm.serviceIndex,
        name: this.editDataInfoForm.serviceName,
        token: this.editDataInfoForm.serviceToken,
        alias: this.editDataInfoForm.serviceNameAlias,
      }).then((res) => {
        this.fieldsTable =
          res?.fields?.map((item) => {
            return {
              field: item.name,
              fieldName: item.alias,
              fieldType: item.type,
              isShow: this.activeFields.includes(item.name) ? 1 : 0,
            };
          }) || [];
        this.queryServiceUrlMap.set(url, this.fieldsTable);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

header,
.el-container,
aside {
  background-color: #fff;
}

header {
  display: flex;
  align-items: center;
  border-radius: 10px;
  gap: 10px;
  box-shadow: rgba(17, 12, 46, 0.15) 0px 48px 100px 0px;

  .el-icon-back {
    cursor: pointer;

    &:hover {
      color: rgb(135, 231, 140);
    }
  }

  span {
    color: #999;
    font-style: italic;
    font-size: 14px;
  }
}

.el-container {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 20px;
  padding-top: 5px;
  border-radius: 3px;
  box-shadow: rgba(17, 12, 46, 0.15) 0px 48px 100px 0px;

  .top {
    display: flex;
    flex-direction: column;
    gap: 15px;
    padding: 20px 40px;
    width: 100%;
    border-bottom: 2px solid #d9d9d9;

    .title {
      font-weight: bold;
      font-size: 16px;
    }

    .directoryInfo {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 5px 10px;
    }
  }

  .middle {
    display: flex;
    justify-content: space-between;

    .keyword-filter {
      display: flex;
      border-radius: 4px;
      border: 1px solid #d9d9d9;

      ::v-deep .el-input__inner {
        border: none;
      }

      .search-btn {
        border: none;
        border-radius: 0px;
        border-left: 1px solid #d9d9d9;
      }
    }

    .styleBtn {
      display: flex;

      .style-button-none {
        color: #4b535e;
        background: #fff;
        border-color: rgba(144, 147, 153, 0.27);
      }
    }
  }

  .content {
    display: flex;
    flex-direction: column;
    gap: 10px;
    justify-content: space-between;
    flex: 1;

    .el-pagination {
      text-align: center;
    }
  }
}

.el-dialog {
  .field-box {
    display: flex;
    justify-content: flex-end;

    .field-filter {
      width: 400px;
      margin-bottom: 16px;
      display: flex;
      border-radius: 4px;
      border: 1px solid #d9d9d9;

      ::v-deep .el-input__inner {
        border: none;
      }

      .search-btn {
        border: none;
        border-radius: 0px;
        border-left: 1px solid #d9d9d9;
      }
    }
  }

  .fn-btns {
    margin-bottom: 10px;
  }
}
</style>
