<template>
  <DesignPropertiesBox v-if="data.show">
    <a-collapse v-model:activeKey="activeKey" ghost expandIconPosition="right">
      <a-collapse-panel key="1" :header="t('基础配置')">
        <a-form-item :label="t('标题')" :colon="false" labelAlign="left">
          <a-input v-model:value="data.info.config.title" />
        </a-form-item>
        <a-form-item
          :label="t('显示标题')"
          :wrapperCol="{
            style: { textAlign: 'right', paddingRight: '10px' },
          }"
        >
          <a-switch v-model:checked="data.info.config.showTitle" />
        </a-form-item>
      </a-collapse-panel>
      <a-collapse-panel key="2" :header="t('地图配置')">
        <FormItem :label="t('接口配置')">
          <SelectApi
            v-model:value="data.info.config.apiConfig"
            :exampleStr="exampleStr"
            @save="changeApiConfig"
          />
        </FormItem>
        <FormItem :label="t('点位字段')">
          <a-select v-model:value="data.info.config.primaryKey" style="width: 100%">
            <a-select-option
              v-for="(item, index) in data.info.config.apiColumns"
              :key="index"
              :value="item.prop"
              >{{ item.label ? item.label : item.prop }}</a-select-option
            >
          </a-select>
        </FormItem>
        <FormItem :label="t('名称字段')">
          <a-select v-model:value="data.info.config.primaryName" style="width: 100%">
            <a-select-option
              v-for="(item, index) in data.info.config.apiColumns"
              :key="index"
              :value="item.prop"
              >{{ item.label ? item.label : item.prop }}</a-select-option
            >
          </a-select>
        </FormItem>
        <FormItem :label="t('点位面板')">
          <div @click="openModal"
            ><InputModel
              :value="data.info.config.panelConfig?.enabled ? '已配置' : ''"
              :placeholder="t('点位面板配置')"
              style="width: 100%; min-width: 100px"
          /></div>
        </FormItem>
      </a-collapse-panel>
    </a-collapse>
    <ModalPanel
      :visible="visible"
      :width="1000"
      :height="1000"
      :title="t('点位面板配置')"
      @submit="submitModal"
      @close="closeModal"
    >
      <div v-if="visible" class="model-form-box">
        <div class="form-box">
          <div class="form-item">
            <div class="label">{{ t('点位面板配置') }}</div>
            <div class="value"> <a-switch v-model:checked="data.panelConfig.enabled" /></div>
          </div>
          <div class="form-item" v-if="data.panelConfig.enabled">
            <div class="label">{{ t('排列方式') }}</div>
            <div class="value" v-if="data.panelConfig.enabled"
              ><a-select
                v-model:value="data.panelConfig.arrangeType"
                style="width: 100%"
                allowClear
              >
                <a-select-option
                  v-for="(val, valIndex) in arrangeTypeList"
                  :key="valIndex"
                  :value="val.value"
                  >{{ val.label }}</a-select-option
                >
              </a-select></div
            >
          </div>
        </div>
        <div class="form-box" v-if="data.panelConfig.enabled">
          <div class="form-item">
            <div class="label">{{ t('点击显示') }}</div>
            <div class="value"> <a-switch v-model:checked="data.panelConfig.clickShow" /></div>
          </div>
        </div>
        <NodeHead :nodeName="t('面板标题')" class="node-head" v-if="data.panelConfig.enabled" />
        <div class="form-box" v-if="data.panelConfig.enabled">
          <div class="form-item">
            <div class="label">{{ t('标题类型') }}</div>
            <div class="value">
              <a-select v-model:value="data.panelConfig.titleType" style="width: 100%" allowClear>
                <a-select-option
                  v-for="(val, valIndex) in titleTypeList"
                  :key="valIndex"
                  :value="val.value"
                  >{{ val.label }}</a-select-option
                >
              </a-select></div
            >
          </div>

          <div class="form-item" v-if="data.panelConfig.titleType == PanelTitleTypeEnum.DEFAULT">
            <div class="label">{{ t('标题内容') }}</div>
            <div class="value">
              <a-input v-model:value="data.panelConfig.title" :placeholder="t('标题内容')"
            /></div>
          </div>
          <div class="form-item" v-else>
            <div class="label">{{ t('标题字段') }}</div>
            <div class="value">
              <a-select v-model:value="data.panelConfig.titleField" style="width: 100%">
                <a-select-option
                  v-for="(item, index) in data.info.config.apiColumns"
                  :key="index"
                  :value="item.prop"
                  >{{ item.label ? item.label : item.prop }}</a-select-option
                >
              </a-select></div
            >
          </div>
        </div>
        <NodeHead :nodeName="t('面板字段')" class="node-head" v-if="data.panelConfig.enabled" />
        <div v-if="data.panelConfig.enabled" style="padding: 0 10px">
          <a-table
            size="small"
            :columns="panelConfigColumns"
            :pagination="false"
            :dataSource="data.panelConfig.config"
            class="search-config"
            :key="queryTableKey"
          >
            <template #headerCell="{ column }">
              <template v-if="column.key === 'sort'">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-fangxiang1" />
                </svg>
              </template>
            </template>
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key !== 'action'">
                <template v-if="column.key === 'sort'">
                  <svg class="icon queryDraggable-icon" aria-hidden="true" style="cursor: move">
                    <use xlink:href="#icon-paixu" />
                  </svg>
                </template>
                <template v-if="column.key === 'label'">
                  <a-input
                    v-model:value="record[column.dataIndex]"
                    :placeholder="t('请填写字段标题，不需要可以不填')"
                  />
                </template>
                <template v-if="column.key === 'value'">
                  <a-select v-model:value="record[column.dataIndex]" style="width: 100%">
                    <a-select-option
                      v-for="(item, index2) in data.info.config.apiColumns"
                      :key="index2"
                      :value="item.prop"
                      >{{ item.label ? item.label : item.prop }}</a-select-option
                    >
                  </a-select>
                </template>
                <template v-if="column.key === 'fontWeightBold'">
                  <a-switch v-model:checked="record[column.dataIndex]" />
                </template>
                <template v-if="column.key === 'fontAlign'">
                  <a-select v-model:value="record[column.dataIndex]" style="width: 100%" allowClear>
                    <a-select-option
                      v-for="(val, valIndex) in fontAlignList"
                      :key="valIndex"
                      :value="val.value"
                      >{{ val.label }}</a-select-option
                    >
                  </a-select>
                </template>
                <template v-if="column.key === 'hasFullRow'">
                  <a-switch v-model:checked="record[column.dataIndex]" />
                </template>
              </template>
              <template v-if="column.key === 'action'">
                <span @click="queryRemove(index)" class="delete-box">删除</span>
              </template>
            </template>
          </a-table>

          <a-button type="dashed" block @click="queryAdd">
            <PlusOutlined />
            {{ t('新增') }}
          </a-button>
        </div>
      </div>
    </ModalPanel>
  </DesignPropertiesBox>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref, watch } from 'vue';
  import { DesignPropertiesBox } from '/@/components/Desktop';
  import { mapInfo } from '../config/info';
  import SelectApi from './collapse/complex/SelectApi.vue';
  import { InputModel } from '/@/components/ApiConfig';
  import { ModalPanel, NodeHead } from '/@/components/ModalPanel/index';
  import {
    MapInfo,
    PanelArrangeTypeEnum,
    PanelConfig,
    PanelTableConfig,
    PanelTableConfigFontAlignEnum,
    PanelTitleTypeEnum,
  } from '/@/model/desktop/designer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import useApiRequest from '/@/hooks/event/useApiRequest';
  import FormItem from '/@bpmn/layout/FormItem.vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import Sortable from 'sortablejs';
  import { isNullAndUnDef } from '/@/utils/is';
  import { cloneDeep } from 'lodash-es';
  const visible = ref(false);
  const { t } = useI18n();
  const { changeApiOptions } = useApiRequest();
  const panelConfigColumns = [
    {
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: t('序号'),
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 80,
    },
    {
      key: 'label',
      align: 'center',
      title: t('字段标题'),
      dataIndex: 'label',
      width: 260,
    },
    {
      key: 'value',
      align: 'center',
      title: t('字段值'),
      width: 160,
      dataIndex: 'value',
    },
    {
      key: 'fontWeightBold',
      align: 'center',
      title: t('标题加粗'),
      dataIndex: 'fontWeightBold',
    },
    {
      key: 'fontAlign',
      align: 'center',
      title: t('对齐方式'),
      width: 120,
      dataIndex: 'fontAlign',
    },
    {
      key: 'hasFullRow',
      align: 'center',
      title: t('独占一行'),
      dataIndex: 'hasFullRow',
    },
    {
      key: 'action',
      align: 'center',
      title: t('操作'),
      dataIndex: 'action',
    },
  ];
  const arrangeTypeList = [
    { label: '一行一字段', value: PanelArrangeTypeEnum.ONE },
    { label: '一行两字段', value: PanelArrangeTypeEnum.TWO },
  ];
  const titleTypeList = [
    { label: '固定标题', value: PanelTitleTypeEnum.DEFAULT },
    { label: '字段标题', value: PanelTitleTypeEnum.API },
  ];
  const fontAlignList = [
    { label: '左对齐', value: PanelTableConfigFontAlignEnum.LEFT },
    { label: '居中对齐', value: PanelTableConfigFontAlignEnum.CENTER },
    { label: '右对齐', value: PanelTableConfigFontAlignEnum.RIGHT },
  ];
  const queryTableKey = ref<number>(0);
  const props = withDefaults(
    defineProps<{
      info: MapInfo;
    }>(),
    {
      info: () => {
        return mapInfo;
      },
    },
  );
  const data: {
    show: boolean;
    info: MapInfo;
    panelConfig: PanelConfig;
  } = reactive({
    show: false,
    info: mapInfo,
    panelConfig: {
      enabled: false, //是否启用
      arrangeType: PanelArrangeTypeEnum.ONE, //排列方式
      titleType: PanelTitleTypeEnum.DEFAULT, //标题类型
      title: '', //标题内容
      titleField: '', //标题字段
      clickShow: false,
      config: [] as Array<PanelTableConfig>, //面板字段
    },
  });
  watch(
    () => props.info,
    (val) => {
      if (val) {
        data.info = val;
      }
    },
    {
      deep: true,
    },
  );
  watch(
    () => data.panelConfig.config,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.search-config .ant-table-tbody');
          if (!tbody) return;
          Sortable.create(tbody, {
            handle: '.queryDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(data.panelConfig.config);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              data.panelConfig.config = cloneDeep(columns);
              queryTableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  const activeKey = ref(['1', '2']);
  onMounted(() => {
    data.info = props.info;
    data.show = true;
  });
  async function changeApiConfig(val) {
    if (val && val.path) {
      let res = await changeApiOptions(val);
      if (res && res.columns) data.info.config.apiColumns = res.columns;
    }
    await nextTick();
    resetDisplay();
  }
  function resetDisplay() {
    data.info.config.renderKey++;
  }
  const exampleStr = ` {
          code: 0,
          msg: 'success',
          data: {
            total:20,
            columns: [
              {prop:'name',label:'测试1'},
              {prop:'value',label:'测试2'}
            ],
            list: [
              {name:'demo1',lnglat:'112.70228 , 28.32243'},
              {name:'demo2',lnglat:'112.87763 , 28.19058'}
            ],
          },
        }`;
  function openModal() {
    if (data.info.config.panelConfig) data.panelConfig = cloneDeep(data.info.config.panelConfig);
    visible.value = true;
  }
  function submitModal() {
    data.info.config.panelConfig = cloneDeep(data.panelConfig);
    closeModal();
  }
  function closeModal() {
    visible.value = false;
  }
  const queryAdd = () => {
    const pushObj: PanelTableConfig = {
      label: '',
      value: '',
      fontWeightBold: false,
      fontAlign: PanelTableConfigFontAlignEnum.LEFT, //对齐方式
      hasFullRow: false, //独占一行
    };
    data.panelConfig.config.push(pushObj);
  };

  const queryRemove = (index) => {
    data.panelConfig.config.splice(index, 1);
  };
</script>

<style lang="less" scoped>
  .model-form-box {
    padding: 10px 0;
  }

  .form-box {
    display: flex;
    align-items: center;
    padding: 0 10px;

    .form-item {
      flex-basis: 48%;
      width: 100%;
      margin: 0 10px;

      .label {
        width: 100%;
        height: 30px;
      }

      .value {
        width: 100%;
        height: 30px;
      }
    }
  }

  .title-box {
    font-weight: 700;
    margin: 10px;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
  }

  .search-box .ant-spin-nested-loading {
    height: auto;
  }

  .delete-box {
    cursor: pointer;
    color: #ff8989;
  }

  :deep(.ant-table-container table > thead > tr:first-child th) {
    height: 50px;
    font-weight: bold;
    background: #f7fbff;
  }

  .node-head {
    padding-left: 20px;
    margin: 19px 0;
  }
</style>
