<template>
  <DesignPropertiesBox v-if="data.show">
    <a-collapse v-model:activeKey="activeKey" ghost expandIconPosition="right">
      <a-collapse-panel key="1" :header="t('数据配置')">
        <BasicTable @register="registerTable" class="BannerDrag">
          <template #bodyCell="{ column, text, record, index }">
            <template v-if="['index', 'url'].includes(column.dataIndex)">
              <Icon
                class="mover"
                icon="ant-design:drag-outlined"
                v-if="column.dataIndex == 'index'"
              />
              <div v-if="column.dataIndex == 'url'">
                <a-input readonly v-model:value="record[column.dataIndex]" style="width: 100%">
                  <template #suffix>
                    <a-upload
                      action=""
                      :customRequest="submitUpload"
                      accept=""
                      :max-count="1"
                      :show-upload-list="false"
                    >
                      <IconFontSymbol
                        icon="upload"
                        :size="14"
                        @click="
                          () => {
                            colIndex = index;
                          }
                        "
                      />
                    </a-upload>
                  </template>
                </a-input>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'action'">
              <TableAction
                :actions="[
                  {
                    color: 'error',
                    label: t('删除'),
                    popConfirm: {
                      title: t('是否确认删除'),
                      confirm: handleDelete.bind(null, index),
                    },
                  },
                ]"
              />
            </template>
            <template v-else> {{ text }} </template>
          </template>
        </BasicTable>
        <div class="mx-2 mt-10px">
          <a-button type="dashed" @click="handleCreate" class="w-full mb-3">
            <plus-outlined />{{ t('新增（最大不超过8张图片）') }}
          </a-button>
        </div>
      </a-collapse-panel>
      <a-collapse-panel key="2" :header="t('大小定位')">
        <Location v-model:info="data.info.h" />
      </a-collapse-panel>
    </a-collapse>
  </DesignPropertiesBox>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch, nextTick } from 'vue';
  import { DesignPropertiesBox } from '/@/components/Desktop';
  import Sortable from 'sortablejs';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { bannerInfo } from '../config/info';
  import { Icon } from '/@/components/Icon';
  import { BannerInfo, bannerItem } from '/@/model/mobileDesign/designer';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import Location from './collapse/Location.vue';
  import { getAppEnvConfig } from '/@/utils/env';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { isNullAndUnDef } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  const { notification } = useMessage();
  const { t } = useI18n();
  const props = withDefaults(
    defineProps<{
      info: BannerInfo;
    }>(),
    {
      info: () => {
        return bannerInfo;
      },
    },
  );
  const activeKey = ref(['1', '2']);
  const data: {
    show: boolean;
    info: BannerInfo;
  } = reactive({
    show: false,
    info: bannerInfo,
  });
  const tableData = ref<bannerItem[]>([]);
  const colIndex = ref();
  const userStore = useUserStore();
  watch(
    () => props.info,
    (val) => {
      if (val) data.info = val;
    },
    {
      deep: true,
    },
  );

  const columns: BasicColumn[] = [
    {
      title: t('排序'),
      dataIndex: 'index',
      width: 40,
    },
    {
      title: t('上传图片'),
      dataIndex: 'url',
      width: 160,
    },
  ];
  const [registerTable, { getDataSource, setTableData }] = useTable({
    title: '',
    dataSource: tableData.value,
    columns,
    pagination: false,
    striped: false,
    useSearchForm: false,
    showIndexColumn: false,
    canResize: false,
    actionColumn: {
      width: 50,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  onMounted(() => {
    data.info = props.info;
    nextTick(() => {
      tableData.value = data.info.config.imgs;
      setTableData(data.info.config.imgs);
    });
    data.show = true;
  });
  watch(
    () => tableData.value,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.BannerDrag .ant-table-tbody');
          const tr: any = tbody.querySelector('tr.ant-table-row[draggable="false"]');
          if (tr) tr.remove();
          Sortable.create(tbody, {
            handle: '.mover',

            onEnd: (evt) => {
              const { oldIndex, newIndex } = evt;
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
                return;
              }

              let columns: bannerItem[] = getDataSource();

              setTableData([]);

              tableData.value = [];
              nextTick(() => {
                let old = columns[oldIndex - 1];
                columns.splice(oldIndex - 1, 1);
                columns.splice(newIndex - 1, 0, old);
                columns.forEach((o, i) => {
                  o.index = i + 1;
                });
                tableData.value = columns;
                setTableData(tableData.value);
              });
            },
          });
        });
        resetDisplay();
      }
    },
    {
      deep: true,
    },
  );
  function handleCreate() {
    let dataSource: bannerItem[] = getDataSource();
    if (dataSource.length >= 8) return;
    let obj = {
      index: dataSource.length,
      url: null,
    };
    dataSource.push(obj);
    tableData.value = dataSource;
    resetDisplay();
  }
  function handleDelete(index) {
    if (tableData.value.length <= 1) {
      notification.warning({
        message: t('提示'),
        description: t('轮播图至少需留一张'),
      });
      return;
    }
    tableData.value.splice(index, 1);
    setTableData(tableData.value);
  }

  function resetDisplay() {
    data.info.config.imgs = tableData.value;
  }

  const submitUpload = (file) => {
    let action = getAppEnvConfig().VITE_GLOB_API_URL + '/system/file';
    const formData = new FormData();
    formData.append('file', file.file);
    formData.append('remark', '上传');
    const xhr = new XMLHttpRequest();
    xhr.open('post', action, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userStore.getToken);
    xhr.onload = () => {
      const response = JSON.parse(xhr.response);
      let dataSource: bannerItem[] = getDataSource();
      dataSource[colIndex.value].url = response.data;

      tableData.value = dataSource;
    };
    xhr.onerror = () => {
      console.log(t('上传失败'));
    };
    xhr.ontimeout = function timeout() {
      console.log(t('上传超时'));
    };
    xhr.send(formData);
  };
</script>

<style lang="less" scoped>
  :deep(.ant-form-item-control) {
    overflow: auto;
  }

  :deep(.ant-input-suffix) {
    width: 32px;
    height: 30px;
    background: #f8f8f8;
    border-radius: 0 4px 4px 0;
    border-left: 1px solid #ddd;
    position: absolute;
    right: 0;
    top: 0;
    display: block !important;
    line-height: 30px;
  }
</style>
