<!--   
  *@描述: 重点区域管控列表
  *@作者： 
  *@日期： 
  *@版本：1.0
  */
  -->
<template>
  <div class="create-model-modal" v-if="winVisible">
    <Window
      :title="title"
      @cancel="cancel"
      :width="width"
      :minWidth="600"
      :height="height"
      :left="left"
      :top="top"
      :floatright="false"
      :footervisible="false"
      :showCancelButton="false"
      v-show="show"
      class="window"
    >
      <!-- 顶部区域 -->
      <div style="width: 100%; height: 40px; padding: 5px">
        <a-button class="editable-add-btn" ghost @click="AreaSet()" style="margin-bottom: 8px">添加区域</a-button>
      </div>

      <b-table :dataSource="keyControlAreaList" :columns="columns" :pagination="pagination" :rowClassName="`  `" @change="tableChange">
        <template #action="{ record }">
          <a href="#" @click="clickFlyTo(record)">定位</a>
          <span class="ml"> | </span>
          <a href="#" @click="AreaSet(record)" class="ml">编辑</a>
          <span class="ml"> | </span>
          <a-popconfirm title="确定删除吗?" ok-text="" cancel-text="" @confirm="del_(record)">
            <!-- <a href="#" @click="del_(record)" class="ml">删除</a> -->
            <a href="#" class="ml">删除</a>
          </a-popconfirm>
        </template>
      </b-table>
    </Window>

    <AddKeyControlArea v-if="addKeyControlAreaShow" :cData="cData" :cModel="cModel"></AddKeyControlArea>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, getCurrentInstance, onBeforeUnmount, onMounted, ref } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useEarthMapStore } from '/@/store/modules/earthMap';
  import { defHttp } from '/@/utils/http/axios';
  import { MeasurementType } from '/@/utils/earthMap/earthSDKEnum';
  import $mitt from '@/utils/earthMap/mitt';
  import Window from '@/components/earthMap/components/Window.vue';
  import BTable from '@/components/earthMap/components/B-table.vue';
  import { addArrow, addCustomPrimitive, addRoamPath } from '@/utils/earthMap/earthObj';
  import AddKeyControlArea from '@/components/earthMap/toolbar/AddKeyControlArea.vue';
  export default defineComponent({
    name: 'KeyControlAreaList',
    props: {
      title: {
        type: String,
        default: '重点管控区域',
      },
    },
    components: {
      Window,
      BTable,
      AddKeyControlArea,
    },
    setup(props, ctx) {
      const { proxy }: any = getCurrentInstance();
      const userStore = useUserStore();
      const store = useEarthMapStore();
      let winVisible = ref(true); // 窗口显示或隐藏
      let show = ref(true);
      let isUpdateModel = ref(false); // 是否有更新模型
      let addKeyControlAreaShow = ref(false);
      let cData: any = ref(null); //当前列表中选中的信息
      let cModel: any = ref(null); //当前列表中选中的模型
      let measurementType = ref(MeasurementType.NONE); // 测量类状态
      let keyControlAreaList = ref([]); //重点管控区域列表
      let heightCoefficient = ref(0.5); //  高
      let widthCoefficient = ref(0.3); //  宽
      let param: any = ref({
        column: 'createTime',
        order: 'desc',
        pageNo: 1,
        pageSize: 5,
        belongTo: '',
      });
      let pagination = ref({
        pageSize: 5,
        total: 0,
        size: 'small',
      });
      let columns = ref([
        {
          title: '序号',
          dataIndex: 'myindex',
          key: '#', //如需序号 需要key 为 #
          width: 80,
        },
        {
          title: '管控区域名称',
          dataIndex: '',
          key: 'areaName',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: '',
          key: 'x',
          slots: {
            customRender: 'action',
          },
        },
      ]);
      //computed
      const width = computed(() => {
        return window.outerWidth * widthCoefficient.value;
      });
      const height = computed(() => {
        return window.outerHeight * heightCoefficient.value;
      });
      const top = computed(() => {
        return window.outerHeight * ((1.0 - heightCoefficient.value - 0.15) / 2);
      });
      const left = computed(() => {
        return (window.outerWidth * (1.0 - widthCoefficient.value)) / 2;
      });

      //
      function cancel() {
        if (isUpdateModel.value) {
          // updateClose()
        } else {
          close();
        }
      }

      function close() {
        //关闭窗口
        // this.winVisible = false
        proxy.$parent.keyControlAreaListShow = false;
      }

      //**************************
      /**
       * 初次进入 如果不是更新 即立即创建
       */
      onMounted(() => {
        $mitt.on('windowCancel', cancel);
        //获取列表
        getKeyControlAreaList();
      });
      onBeforeUnmount(() => {
        $mitt.off('windowCancel');
      });

      // 获取列表
      function getKeyControlAreaList() {
        param.value.sysOrgCode = userStore.userInfo?.orgCode;
        defHttp
          .get(
            {
              url: '/military/dtKeyControlArea/list',
              // params: param.value,
            },
            { isTransformResponse: false }
          )
          .then(
            (res) => {
              let arr = res.result.records;
              arr.forEach((element, index) => {
                element.myindex = index + 1 + (param.value.pageNo * 5 - 5);
                element.key = element.id;
              });
              //获取总条数
              pagination.value.total = res.result.total;
              // 当前页路径赋值
              keyControlAreaList.value = res.result.records;
            },
            (err) => {}
          )
          .catch((res) => {
            proxy.$message.error('获取列表失败！');
            console.error('获取列表失败！', res);
          });
      }

      // 点击分页
      function tableChange(e) {
        param.value.pageNo += e;
        // 获取列表
        defHttp
          .get(
            {
              url: '/military/dtKeyControlArea/list',
              params: param.value,
            },
            { isTransformResponse: false }
          )
          .then(
            (res) => {
              let arr = res.result.records;
              arr.forEach((element, index) => {
                element.myindex = index + 1 + (e.current * 5 - 5);
                element.key = element.id;
              });
              keyControlAreaList.value = res.result.records;
            },
            (err) => {}
          )
          .catch((res) => {
            console.error('信息出错！', res);
          });
      }

      //模型编辑
      function AreaSet(data: any = null) {
        if (data) {
          //飞入该模型 进行编辑
          clickFlyTo(data);
          //传入数据 cModel,cData
          const item = sessionStorage.getItem('keyControlAreaList');
          const sessionKeyControlAreaList = new Map(JSON.parse(item || ''));
          const id: string = (sessionKeyControlAreaList.get(data.id) as string) || '';
          const viewer = window?.$earth.czm.viewer;
          const model = viewer.entities.getById(id);

          cData.value = data;
          cModel.value = model;
        } else {
          //创建
          cData.value = null;
          cModel.value = null;
        }
        //打开编辑页面
        addKeyControlAreaShow.value = true;
      }

      //模型飞入
      function clickFlyTo(data: any = null) {
        const item = sessionStorage.getItem('keyControlAreaList');
        const sessionKeyControlAreaList = new Map(JSON.parse(item || ''));
        const id: string = (sessionKeyControlAreaList.get(data.id) as string) || '';
        const viewer = window?.$earth.czm.viewer;
        const model = viewer.entities.getById(id);
        if (model) {
          viewer.flyTo(model);
        } else {
          // Msg.error('该区域不存在, 请刷新页面重试');
          proxy.$message.error('该区域不存在, 请刷新页面重试');
        }
      }

      //模型删除
      function del_(record: any = null) {
        defHttp
          .delete(
            {
              url: '/military/dtKeyControlArea/delete',
              params: { id: record.id },
            },
            { isTransformResponse: false, joinParamsToUrl: true }
          )
          .then((res) => {
            // 删除地图中的对象
            const item = sessionStorage.getItem('keyControlAreaList');
            const sessionKeyControlAreaList = new Map(JSON.parse(item || ''));
            const id: string = (sessionKeyControlAreaList.get(record.id) as string) || '';
            const viewer = window?.$earth.czm.viewer;
            const model = viewer.entities.getById(id);
            if (model) {
              viewer.entities.remove(model);
            } else {
              // Msg.error('该区域不存在, 请刷新页面重试');
              proxy.$message.error('该区域不存在, 请刷新页面重试');
            }

            // 删除会话中的数据
            sessionKeyControlAreaList.delete(record.id);
            sessionStorage.setItem('keyControlAreaList', JSON.stringify(Array.from(sessionKeyControlAreaList.entries())));

            //刷新列表
            getKeyControlAreaList();
          })
          .catch((res) => {
            proxy.$message.error('删除失败！');
            console.error('删除失败！', res);
          });
      }

      return {
        winVisible,
        param,
        pagination,
        columns,
        width,
        height,
        top,
        left,
        show,
        keyControlAreaList,
        measurementType,
        addKeyControlAreaShow,
        cData,
        cModel,
        AreaSet,
        cancel,
        tableChange,
        clickFlyTo,
        del_,
        getKeyControlAreaList,
      };
    },
  });
</script>

<style scoped lang="less">
  .window {
    height: 380px !important;
    width: 600px !important;
  }

  :deep(.xbsj-model-arrow) {
    display: none;
  }

  .ml {
    margin-left: 5px;
  }
</style>
