<template>
  <div class="route-detail-page">
    <el-form
      ref="formRef"
      label-position="top"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <div class="form-row-title">水闸选择</div>
      <div class="flex items-start">
        <el-form-item label="选择水闸" prop="wagaName">
          <el-select
            :disabled="!canEdit"
            class="w-240"
            size="small"
            remote
            filterable
            reserve-keyword
            :maxlength="50"
            :remote-method="handleGetRemoteDikeMethod"
            @focus="handleGetRemoteDikeMethod('')"
            @change="handleChangeDike"
            v-model="formData.wagaName"
            placeholder="请选择水闸"
          >
            <el-option
              v-for="item in dikeList"
              :key="item.id"
              :label="item.wagaName"
              :value="item.wagaName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水闸类型" prop="wagaType" class="ml-24">
          <el-select
            v-model="formData.wagaType"
            :disabled="true"
            class="w-240"
            size="small"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水闸巡查责任人" prop="dutyHolder" class="ml-24">
          <el-input
            class="w-240"
            size="small"
            v-model="formData.dutyHolder"
            :disabled="true"
            placeholder=""
          ></el-input>
        </el-form-item>
      </div>
      <div class="form-row-title">巡查路线设置</div>
      <div class="flex items-start">
        <el-form-item label="巡查路线名称" prop="name">
          <el-input
            :disabled="!canEdit"
            class="w-240"
            size="small"
            v-model="formData.name"
            placeholder="请输入名称"
            :maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡查路线类型" prop="type" class="ml-24">
          <el-select
            :disabled="!canEdit"
            class="w-240"
            v-model="formData.type"
            @change="handleChangeLineType"
          >
            <el-option
              v-for="(item, index) in xcClassfyOptions"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="巡查责任人类型"
          prop="dutyHolderType"
          class="ml-24"
        >
          <el-select
            :disabled="!canEdit"
            class="w-240"
            v-model="formData.dutyHolderType"
          >
            <el-option label="巡查责任人" value="0"></el-option>
            <el-option label="行政责任人" value="2"></el-option>
            <el-option label="技术责任人" value="1"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="map-box">
        <SyMixMap ref="syMapRef" :canEdit="canEdit" :entries="entries">
          <div class="tool-box">
            <div>
              <div class="font-700 tc-text1 mb-12">路线标定</div>
              <div class="flex flex-wrap">
                <div
                  class="tool-item cursor-pointer"
                  :class="{ 'cursor-not-allowed': !canEdit }"
                  @click="handleDraw('billboard', 'pos_start.svg')"
                >
                  <img
                    class="icon"
                    :src="`${baseUrl}icons/pos_start.svg`"
                    alt=""
                  />
                  设定起点
                </div>
                <div
                  class="tool-item cursor-pointer"
                  :class="{ 'cursor-not-allowed': !canEdit }"
                  @click="handleDraw('billboard', 'pos_end.svg')"
                >
                  <img
                    class="icon"
                    :src="`${baseUrl}icons/pos_end.svg`"
                    alt=""
                  />
                  设定终点
                </div>
                <div
                  class="tool-item cursor-pointer"
                  :class="{ 'cursor-not-allowed': !canEdit }"
                  @click="handleDraw('polyline', '')"
                >
                  <div class="line-path"></div>
                  路线方向
                </div>
              </div>
            </div>
            <div class="mt-12">
              <el-form-item label="巡查项目选择" prop="xcName">
                <el-select
                  class="w-full"
                  v-model="formData.xcName"
                  :disabled="!canEdit"
                  filterable
                  remote
                  reserve-keyword
                  @change="handleChangeXcItem"
                  @focus="handleGetRemoteProjectMethod('')"
                  placeholder="请输入关键词搜索"
                  :remote-method="handleGetRemoteProjectMethod"
                >
                  <el-option
                    v-for="item in xcProjectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <div class="mt-8 tree-style">
                <el-tree
                  :data="checkTreeData"
                  :default-expand-all="true"
                  ref="treeRef"
                  node-key="id"
                  :filter-node-method="filterNode"
                  :props="{
                    children: 'children',
                    label: 'value',
                  }"
                >
                </el-tree>
              </div>
            </div>
          </div>
        </SyMixMap>
      </div>
    </el-form>
  </div>
</template>
<script>
import SyMixMap from "@/views/components/SyMixMap.vue";
import { postDFInspectionProjectList } from "@/api/management";
import {
  getCheckingDictTree,
  getProjectCheckingLineRouteDetails,
  getInspectionProjectDetails,
  getRunProjectList,
  postProjectCheckingLineRoute,
  putProjectCheckingLineRoute,
} from "@/api/sluice";

export default {
  components: {
    SyMixMap,
  },
  props: {
    id: String,
    canEdit: Boolean,
  },
  data() {
    return {
      baseUrl: process.env.BASE_URL,
      formData: {
        wagaName: "",
        wagaCode: "",
        wagaType: "",
        name: "",
        points: [],
        status: "1",
        type: "", //巡查路线类型
        dutyHolder: "",
        // entries: "",
        xcId: "",
        checkingDetail: {},
      },
      rules: {
        wagaName: [
          { required: true, message: "请选择水闸", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入路线名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择路线类型", trigger: "change" },
        ],
        dutyHolderType: [
          { required: true, message: "请选择责任人类型", trigger: "change" },
        ],
        xcName: [
          { required: true, message: "请选择巡查项目", trigger: "change" },
        ],
      },
      entries: {},
      filterText: "",
      xcProjectList: [],
      projectTypeOptions: [],
      xcClassfyOptions: [],
      dikeList: [],
      treeData: [],
      checkTreeData: [],
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          getProjectCheckingLineRouteDetails(val).then((response) => {
            this.formData = response.data;
            this.dealXcProject(response.data.xcId);
            this.entries =
              response.data.entries && typeof response.data.entries === "string"
                ? JSON.parse(response.data.entries)
                : [];
          });
        }
      },
      immediate: true,
    },
    filterText(val) {
      this.$refs.treeRef?.filter(val);
    },
  },
  created() {
    getCheckingDictTree("df_xs_c_classfy").then((response) => {
      this.treeData = this.transformArr(response.data);
    });
    this.getDicts("sluice_type").then((response) => {
      this.projectTypeOptions = response.data;
    });
    this.getDicts("xs_classfy").then((response) => {
      this.xcClassfyOptions = response.data;
    });
  },
  mounted() {},
  methods: {
    handleDraw(type, iconName) {
      if (!this.canEdit) return;
      this.$refs.syMapRef.draw(type, iconName);
    },
    handleChangeDike() {
      let res = this.dikeList.find(
        (v) => v.wagaName === this.formData.wagaName
      );
      if (res) {
        const { dikeStartLat, dikeStartLong } = res;
        if (dikeStartLat && dikeStartLong) {
          this.$refs.syMapRef.setMapCenter(dikeStartLong, dikeStartLat);
        }
        this.formData.wagaCode = res.wagaCode;
        this.formData.wagaType = res.wagaType;
        this.formData.wagaName = res.wagaName;

        this.formData.dutyHolder = res.dutyHolders.find(
          (v) => v.dutyHolderType === "0"
        )?.name;
      }
    },
    handleGetRemoteDikeMethod(query) {
      getRunProjectList({
        pageSize: 10,
        pageNum: 1,
        data: {
          wagaName: query,
        },
      }).then((res) => {
        if (res) {
          this.dikeList = res.records;
        }
      });
    },
    handleGetRemoteProjectMethod(query) {
      postDFInspectionProjectList({
        data: {
          timeView: {
            timeField: "create_time",
          },
          type: this.formData.type || "",
        },
        cv: {
          name: "name",
          type: "like",
          value: query,
        },
        pageSize: 10,
        pageNum: 1,
      }).then((res) => {
        if (res) {
          this.xcProjectList = res.records;
        }
      });
    },
    // 树转换
    transformArr(treeList) {
      // 递归设置路径
      function deepCalc(item, part = []) {
        item.parts = [...part, item.key];
        if (item.children?.length) {
          item.children.forEach((v) => {
            if (!v.children || v.children.length === 0) {
              v.parts = [...item.parts, v.key];
              v.content = v.remark || "";
            } else {
              deepCalc(v, item.parts);
            }
          });
        }
      }

      treeList.forEach((item) => {
        deepCalc(item);
      });
      return treeList;
    },

    // 获取巡查项目
    dealXcProject(id) {
      getInspectionProjectDetails(id).then((response) => {
        this.formData.checkingDetail = response.data;
        this.formData.xcName = response.data.name;
        let _treeData = [];
        // 处理三级节点，最多三级
        for (let i = 0; i < response.data.items.length; i++) {
          const item = response.data.items[i];
          if (item.parts && item.parts[0]) {
            // 一级节点处理
            let exitTreeItem1 = _treeData.find((v) => v.key === item.parts[0]);
            if (exitTreeItem1) {
              let treeItem = this.treeData.find((v) => v.key === item.parts[0]);
              // 已存在一级节点
              if (item.parts[1]) {
                let exitTreeItem2 = exitTreeItem1.children.find(
                  (v) => v.key === item.parts[1]
                );
                if (exitTreeItem2) {
                  let treeItem2 = treeItem.children.find(
                    (v) => v.key === item.parts[1]
                  );
                  // 已存在二级节点
                  if (item.parts[2]) {
                    let exitTreeItem3 = exitTreeItem2.children.find(
                      (v) => v.key === item.parts[2]
                    );
                    if (!exitTreeItem3) {
                      let _treeItem3 = treeItem2.children.find(
                        (v) => v.key === item.parts[2]
                      );
                      exitTreeItem2.children.push({
                        key: _treeItem3.key,
                        value: _treeItem3.value,
                        children: [],
                      });
                    }
                  }
                } else {
                  // 不存在二级节点
                  let _treeItem2 = treeItem.children.find(
                    (v) => v.key === item.parts[1]
                  );
                  exitTreeItem1.children.push({
                    key: _treeItem2.key,
                    value: _treeItem2.value,
                    children: [],
                  });
                }
              }
            } else {
              // 不存在一级节点
              let treeItem = this.treeData.find((v) => v.key === item.parts[0]);
              if (treeItem) {
                let _treeItem1 = {
                  key: treeItem.key,
                  value: treeItem.value,
                  children: [],
                };
                _treeData.push(_treeItem1);
                if (item.parts[1]) {
                  let treeItem2 = treeItem.children.find(
                    (v) => v.key === item.parts[1]
                  );
                  if (treeItem2) {
                    let _treeItem2 = {
                      key: treeItem2.key,
                      value: treeItem2.value,
                      children: [],
                    };
                    _treeItem1.children.push(_treeItem2);
                    if (item.parts[2]) {
                      let treeItem3 = treeItem2.children.find(
                        (v) => v.key === item.parts[2]
                      );
                      if (treeItem3) {
                        let _treeItem3 = {
                          key: treeItem3.key,
                          value: treeItem3.value,
                          children: [],
                        };
                        _treeItem2.children.push(_treeItem3);
                      }
                    }
                  }
                }
              }
            }
          }
        }
        this.checkTreeData = _treeData;
      });
    },
    // 修改路线类型
    handleChangeLineType() {
      if (this.formData.xcId) {
        this.formData.xcName = "";
        this.formData.xcId = "";
        this.xcProjectList = [];
        this.checkTreeData = [];
      }
    },
    handleChangeXcItem(val) {
      const res = this.xcProjectList.find((item) => item.name === val);
      if (res.id) {
        this.formData.xcId = res.id;
        this.dealXcProject(res.id);
      }
    },
    handleAddNewPlan() {
      this.formData.planList.push({
        planDateTimeArr: [],
        xcUsers: [],
        scScope: "",
      });
    },
    handleDelPlanItem(index) {
      this.formData.planList.splice(index, 1);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    submit(reset) {
      return new Promise((r, j) => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                let entries = this.$refs.syMapRef.submit();
                (this.id
                  ? putProjectCheckingLineRoute
                  : postProjectCheckingLineRoute)({
                  id: this.id || null,
                  ...this.formData,
                  entries: JSON.stringify(entries),
                })
                  .then((res) => {
                    this.$message.success("提交成功");
                    if (reset) {
                      this.reset();
                    }
                    r();
                  })
                  .catch(() => {
                    j();
                  });
              })
              .catch(() => {
                j();
              });
          } else {
            j();
          }
        });
      });
    },
    reset() {
      this.$refs.formRef.resetFields();
      this.$refs.syMapRef.reset();
      this.checkTreeData = [];
      this.formData.xcName = "";
      this.formData.xcId = "";
    },
  },
};
</script>
<style scoped lang="scss">
.route-detail-page {
  font-size: 14px;
  width: 100%;
  max-width: 1232px;
  padding: 16px;
  padding-bottom: 78px;
  border-radius: 6px;
  .form-row-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    border-left: 4px solid #36b29e;
    padding-left: 8px;
  }
  .w-100 {
    width: 100px !important;
  }
  .w-240 {
    width: 240px !important;
  }

  .plan-list-item {
    position: relative;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 16px;
    margin-top: 16px;
  }

  .del-btn {
    position: absolute;
    cursor: pointer;
    z-index: 1;
    width: 18px;
    top: 8px;
    right: 8px;
    font-size: 18px;
  }

  .map-box {
    position: relative;
    width: 100%;
    height: 610px;
    padding: 12px;
    background: #f4f4f4;
    border-radius: 6px;
    #routeCesiumContainer {
      position: relative;
      width: 100%;
      height: 100%;
    }
    .tool-box {
      position: absolute;
      z-index: 1;
      top: 15px;
      left: 15px;
      background-color: #fff;
      padding: 12px 16px;
      box-sizing: border-box;
      height: 534px;
      width: 224px;
      border-radius: 6px;
      .tool-item {
        width: 86px;
        height: 26px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        border: 1px solid #dcdcdc;
        margin-right: 16px;
        margin-bottom: 16px;
        .line-path {
          width: 16px;
          height: 6px;
          background: #36b29e;
        }
        .icon {
          width: 16px;
          height: 16px;
          margin-right: 6px;
        }

        &:nth-child(even) {
          margin-right: 0;
        }
      }
    }

    .tree-style {
      height: 280px;
      width: 100%;
      overflow: auto;
    }

    .position-box {
      position: absolute;
      top: 2px;
      right: 2px;
      padding: 6px 12px;
      background: rgba($color: #000000, $alpha: 0.4);
      color: #fff;
      border-radius: 4px;
    }
  }
}
</style>
