<!--
 * @Author: your name
 * @Date: 2024-01-25 16:21:46
 * @LastEditTime: 2024-01-26 10:10:33
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \my_web_new\src\views\backOfficeSystem\patrolManagement\task\editAddForm.vue
-->
<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">{{ title }}</span>
      <div>
        <!-- <el-button type="primary" size="small" :loading="loading" @click="submit">保存</el-button> -->
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <el-steps class="box_main" :active="stepActive" finish-status="success">
      <el-step title="步骤1" />
      <el-step title="步骤2" />
    </el-steps>
    <el-form ref="elform" :model="listQuery" :rules="rules" :inline="true" label-position="top" v-if="stepActive == 0">
      <el-form-item style="width: 48%" prop="fgRwmc" label="任务名称">
        <el-input v-model="listQuery.fgRwmc" placeholder="请输入任务名称" style="width: 100%" clearable />
      </el-form-item>
      <el-form-item style="width: 45%" label="方格" prop="fgData">
        <div :class="listQuery?.fgData && listQuery?.fgData.length === 0 ? 'ipt mj' : 'ipt'"
          @click.stop="fgVisible = true">
          <el-tag v-for="(tag, idx) in listQuery?.fgData" :key="tag.id" class="mx-1" closable :type="tag.type"
            @close="handleClose(idx)">
            {{ tag.fgmc }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item style="width: 48%" prop="dkjgsj" label="间隔时间">
        <el-input v-model="listQuery.dkjgsj" type="number" placeholder="请输入间隔时间" style="width: 100%" clearable />
      </el-form-item>
      <div class="center-btn"><el-button style="margin: 12px 0;" @click="next">下一步</el-button></div>
      <div style="height: 40vh; width: 100%">
        <gd-map />
      </div>
    </el-form>
    <div class="box_main" v-if="stepActive == 1">
      <el-button style="margin: 12px 0 10px 0;" @click="addDw" v-if="openType !== 'detail'">新增点位</el-button>
      <MyTable :tableData="pageData.tableData" :tableColumn="pageData.tableColumn" :tableHeight="pageData.tableHeight"
        :key="pageData.keyCount" :tableConfiger="pageData.tableConfiger" :controlsWidth="pageData.controlsWidth"
        @chooseData="chooseData">
        <template #dktp="{ row }">
          <el-image :append-to-body="true" :preview-src-list="[
            `/mosty-api/mosty-base/minio/image/download/${row.dktp}`
          ]" style="width: 75px; height: 75px" :src="`/mosty-api/mosty-base/minio/image/download/${row.dktp}`"
            fit="cover" lazy />
        </template>
        <!-- 操作 -->
        <template #controls="{ row, index }">
          <el-button @click="deletList(index)" type="danger" size="small">删除</el-button>
        </template>
      </MyTable>
      <div class="center-btn">
        <el-button style="margin-top: 12px" @click="stepFn">上一步</el-button>
        <el-button style="margin-top: 12px" @click="submit" v-if="openType !== 'detail'">提交</el-button>
      </div>
    </div>
  </div>
  <FgLoad v-model="fgVisible" @choosedUsers="hanlderChoose" :Single="true" />
  <AddDw v-model="showDialog" v-if="showDialog" :data="listQuery?.fgData"
    :dic="{ D_ZDXL_FGXLRW_YJYS, D_ZDXL_FGXLRW_YJDJ, D_ZDXL_FGXLRW_RWZT }" @submit="dwSubmit" />
</template>

<script setup>
import FgLoad from "./fgLoad.vue";
import AddDw from "./addDw.vue";
import emitter from "@/utils/eventBus";
import MyTable from "@/components/aboutTable/MyTable.vue";
import { qcckGet, qcckPost } from "@/api/qcckApi.js";
import GdMap from "@/components/Map/GdMap/index.vue";
import { fetchTbZdxlFgdwSelectList } from "@/api/service/taskProgress";
import {
  ref,
  defineExpose,
  reactive,
  onMounted,
  defineEmits,
  getCurrentInstance
} from "vue";
const props = defineProps({
  dic: Object
});
const { proxy } = getCurrentInstance();
const { D_ZDXL_FGXLRW_YJYS, D_ZDXL_FGXLRW_YJDJ, D_ZDXL_FGXLRW_RWZT } = proxy.$dict("D_ZDXL_FGXLRW_YJYS", "D_ZDXL_FGXLRW_YJDJ", "D_ZDXL_FGXLRW_RWZT");
const showDialog = ref(false);
const stepActive = ref(0)
const emit = defineEmits(["updateDate"]);
const dialogForm = ref(false); //弹窗
const listQuery = ref({ fgData: [] }); //表单
const fgPlaneList = ref([]);
const fgVisible = ref(false);
const loading = ref(false);
const elform = ref();
const title = ref("");
const openType = ref("")
const rules = reactive({
  fgRwmc: [{ required: true, message: "请输入任务名称", trigger: "change" }],
  fgData: [{ required: true, message: "请选择方格", trigger: "change" }],
  dkjgsj: [{ required: true, message: "请输入间隔时间", trigger: "change" }],
  sblx: [{ required: true, message: "请选择任务类型", trigger: "change" }],
  jd: [{ required: true, message: "请选择坐标", trigger: ["change", "blur"] }]
});
const pageData = reactive({
  tableData: [], //表格数据
  keyCount: 0,
  tableConfiger: {
    loading: false,
    rowHieght: 61,
    haveControls: true,
  },
  total: 0,
  pageConfiger: {
    pageSize: 20,
    pageNum: 1
  }, //分页
  controlsWidth: 210, //操作栏宽度
  tableColumn: [
    { label: "点位名称", prop: "bxdMc", showOverflowTooltip: true },
    { label: "经度", prop: "jd", showOverflowTooltip: true },
    { label: "维度", prop: "wd", showOverflowTooltip: true },
  ]
});
onMounted(() => {
  // 点击地图方格选择
  emitter.on("showTaskFgInfo", (val) => {
    if (openType.value !== 'detail') {
      listQuery.value.fgData = [{
        id: val.id,
        fgmc: val.mc1,
        x1: val.x1,
        y1: val.y1,
        x2: val.x2,
        y2: val.y2,
        x11: val.x11,
        y11: val.y11,
        x21: val.x21,
        y21: val.y21,
        zxX: val.zxX,
        zxY: val.zxY,
      }];
      renderBaseFg();
      renderSelectedFg(val);
    }
  })
});

const renderBaseFg = () => {
  emitter.emit("deletePointArea", "taskFg-flag");
  if (fgPlaneList.value.length === 0) return;
  emitter.emit("echoPlane", {
    fontColor: "#12fdb8",
    coords: fgPlaneList.value,
    type: "rectangle",
    flag: "taskFg-flag",
    color: "rgba(2,20,51,0.5)",
    linecolor: "#1C97FF"
  });
};

const renderSelectedFg = (fg) => {
  if (!fg?.x1 || !fg?.y1 || !fg?.x2 || !fg?.y2) return;
  emitter.emit("deletePointArea", "taskFg-info");
  const position = [
    [Number(fg.x1), Number(fg.y1)],
    [Number(fg.x2), Number(fg.y2)]
  ];
  const selected = [{
    position,
    text: fg.mc1 || fg.mc || fg.fgmc,
    id: fg.id,
    userData: fg
  }];
  emitter.emit("echoPlane", {
    fontColor: "white",
    coords: selected,
    type: "rectangle",
    flag: "taskFg-info",
    color: "red",
    linecolor: "red"
  });
};

// 初始化数据
const init = (type, row) => {
  dialogForm.value = true;
  openType.value = type;
  title.value = row ? "编辑任务" : "新增任务";
  stepActive.value = 0;
  getData()
  pageData.tableColumn = [
    { label: "点位名称", prop: "bxdMc", showOverflowTooltip: true },
    { label: "经度", prop: "jd", showOverflowTooltip: true },
    { label: "维度", prop: "wd", showOverflowTooltip: true },
  ]
  pageData.tableConfiger.haveControls = true
  if (row) {
    getDataById(row);
    if (openType.value == 'detail') {
      pageData.tableColumn = [
        { label: "点位名称", prop: "bxdMc", showOverflowTooltip: true },
        { label: "经度", prop: "jd", showOverflowTooltip: true },
        { label: "维度", prop: "wd", showOverflowTooltip: true },
        { label: "打卡时间", prop: "dksj", showOverflowTooltip: true },
        { label: "图片", prop: "dktp", showOverflowTooltip: true, showSolt: true },
      ]
      pageData.tableConfiger.haveControls = false
    }
  } else {
    listQuery.value = { fgData: [] };
    pageData.tableData = [];
  }
};
// 根据id查询详情
const getDataById = (row) => {
  qcckGet({ fgrwid: row.id }, "/mosty-yjzl/tbZdyrw/getFgrwXq").then((res) => {
    listQuery.value = res;
    listQuery.value.fgData = [{
      ...res.fgxx,
      fgmc: res.fgmc,
      id: res.fgId,
    }]
    renderSelectedFg(listQuery.value.fgData[0]);
    pageData.tableData = res.bxds
  });
};
const getData = async () => {
  const res = await fetchTbZdxlFgdwSelectList();
  if (res && res?.length > 0) {
    let cc = [];
    fgPlaneList.value = res?.map((el, index) => {
      let centerPoint = [el.zxX, el.zxY];
      if (index == 0) cc = centerPoint;
      let position = [
        [Number(el.x1), Number(el.y1)],
        [Number(el.x2), Number(el.y2)]
      ];
      let text = el.mc;
      let obj = { position: position, text, id: el.id, userData: el };
      return obj;
    });
    renderBaseFg();
    emitter.emit("setMapCenter", { location: cc, zoomLevel: 11 });
  }
};
const next = () => {
  elform.value.validate((valid) => {
    if (!valid) return false;
    stepActive.value++;

  });
}
// 上一步
const stepFn = () => {
  stepActive.value--;
  getData()
}
const addDw = () => {
  showDialog.value = true
}
//选择方格
function hanlderChoose(arr) {
  const jzryList = arr.map((item) => {
    return {
      id: item.id,
      fgmc: item.mc1,
      x1: item.x1,
      y1: item.y1,
      x2: item.x2,
      y2: item.y2,
      x11: item.x11,
      y11: item.y11,
      x21: item.x21,
      y21: item.y21,
      zxX: item.zxX,
      zxY: item.zxY,
    };
  });
  listQuery.value.fgData = jzryList;
}

const dwSubmit = (val) => {
  pageData.tableData.push(val)
}
// 提交
const submit = () => {
  loading.value = true;
  const pramas = {
    fgRwmc: listQuery.value.fgRwmc,
    fgId: listQuery.value.fgData[0].id,
    dkjgsj: listQuery.value.dkjgsj,
    dtoList: pageData.tableData.map(item => {
      return {
        bxdMc: item.bxdMc,
        jd: item.jd,
        wd: item.wd
      }
    })
  }
  if (title.value == "新增任务") {
    qcckPost(pramas, "/mosty-yjzl/tbZdyrw/addTbZdyrw")
      .then((res) => {
        proxy.$message({ type: "success", message: "新增成功" });
        close();
        emit("updateDate");
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    pramas.id = listQuery.value.id
    qcckPost(pramas, "/mosty-yjzl/tbZdyrw/editTbZdyrw")
      .then((res) => {
        proxy.$message({ type: "success", message: "修改成功" });
        close();
        emit("updateDate");
      })
      .catch(() => {
        loading.value = false;
      });
  }
  // });
};
const deletList = (idx) => {
  pageData.tableData.splice(idx, 1)
}
// 关闭
const close = () => {
  listQuery.value = { qcys: "#409eff" };
  dialogForm.value = false;
  loading.value = false;
  fgPlaneList.value = [];
  emitter.emit("deletePointArea", "taskFg-info");
  emitter.emit("deletePointArea", "taskFg-flag");
};

defineExpose({ init });
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.mapBox {
  width: 100%;
  height: 600px;
}

.latlng {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.ipt {
  border: 1px solid rgb(7, 85, 188);
  width: 100%;
  line-height: 32px;
  min-height: 32px;
  border-radius: 4px;
  position: relative;
  background: #001238;
}

.mj::after {
  content: "请选择方格";
  position: absolute;
  top: 0;
  left: 12px;
  color: #c0c4cc;
}

.box_main {
  padding: 2rem 12rem 0rem 12rem;
  width: 100%;
}

.center-btn {
  width: 100%;
  margin: 0 auto;
  text-align: center;
}
</style>
