<template>
  <DesignPropertiesBox v-if="data.show" style="margin-top: 10px">
    <a-form-item :label="t('绑定API')" :colon="false">
      <ApiSelect
        v-model:value="data.info.config.apiConfig"
        :exampleStr="exampleStr"
        @save="saveApiConfig"
      />
    </a-form-item>
    <BasicTable @register="registerTable" class="dataAuthDrag">
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="['name', 'field'].includes(column.dataIndex)">
          <div>
            <a-input
              v-if="column.dataIndex == 'name'"
              v-model:value="record[column.dataIndex]"
              @change="changeData"
              :placeholder="t('请填写名称')"
            />
            <a-select
              class="w-full"
              :placeholder="t('请选择')"
              v-else-if="column.dataIndex == 'field'"
              v-model:value="record[column.dataIndex]"
              @change="changeData"
              :options="fieldOptions"
            />
          </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 @click="handleCreate" class="w-full mb-3" type="dashed">
        <plus-outlined />{{ t('新增（同一组件最大仅支持两个指标）') }}
      </a-button>
    </div>
    <a-form-item :label="t('标签颜色')" :colon="false">
      <SelectColor v-model:value="data.info.config.labelColor" />
    </a-form-item>
    <a-form-item :label="t('数据颜色')" :colon="false">
      <SelectColor v-model:value="data.info.config.numColor" />
    </a-form-item>
  </DesignPropertiesBox>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch, nextTick } from 'vue';
  import { DesignPropertiesBox } from '/@/components/Desktop';
  import ApiSelect from './ApiSelect.vue';
  import SelectColor from './SelectColor.vue';
  import type { SelectProps } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { dashboardInfo } from '../config/info';
  import { uploadSrc } from '/@/api/sys/upload';

  import { DashboardInfo, dashboardItem } from '/@/model/mobileDesign/designer';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import useApiRequest from '/@/hooks/event/useApiRequest';
  const { changeApiOptions } = useApiRequest();
  import { getAppEnvConfig } from '/@/utils/env';
  import { getToken } from '/@/utils/auth';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const props = withDefaults(
    defineProps<{
      info: DashboardInfo;
    }>(),
    {
      info: () => {
        return dashboardInfo;
      },
    },
  );
  const data: {
    show: boolean;
    info: DashboardInfo;
    action: string;
    headers: { Authorization: string };
  } = reactive({
    show: false,
    info: dashboardInfo,
    action: getAppEnvConfig().VITE_GLOB_API_URL + uploadSrc,
    headers: { Authorization: `Bearer ${getToken()}` },
  });
  const tableData = ref<dashboardItem[]>([]);
  watch(
    () => props.info,
    (val) => {
      if (val) data.info = val;
    },
    {
      deep: true,
    },
  );

  const fieldOptions = ref<SelectProps['options']>([]);
  const columns: BasicColumn[] = [
    {
      title: t('指标名称'),
      dataIndex: 'name',
      width: 100,
    },
    {
      title: t('绑定API字段'),
      dataIndex: 'field',
      width: 100,
    },
  ];
  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.dashboard;
      setTableData(data.info.config.dashboard);
      if (data.info.config.apiConfig?.path) {
        saveApiConfig(data.info.config.apiConfig, true);
      }
    });
    data.show = true;
  });
  async function saveApiConfig(val, isInit = false) {
    if (!isInit) resetApiData();
    let res = await changeApiOptions(val);
    fieldOptions.value = [];
    for (let key in res) {
      fieldOptions.value?.push({
        label: key,
        value: key,
      });
    }
    resetDisplay();
  }
  function resetApiData() {
    data.info.config.apiData = {};
    data.info.config.apiColumns = [];
    tableData.value = [];
    data.info.config.dashboard = [];
    setTableData([]);
  }
  function handleCreate() {
    let dataSource: dashboardItem[] = getDataSource();
    if (dataSource.length >= 2) return;
    let obj = {
      name: '',
      field: null,
    };
    dataSource.push(obj);
    tableData.value = dataSource;
    resetDisplay();
  }
  function handleDelete(index) {
    tableData.value.splice(index, 1);
    setTableData(tableData.value);
  }

  function resetDisplay() {
    if (data.info.config.renderKey >= 0) {
      data.info.config.renderKey++;
    }
  }
  function changeData() {
    data.info.config.dashboard = getDataSource();
  }
  const exampleStr = ` {
      code: 0,
      msg: 'success',
      data: {
        filed1: 0,
        filed2: 0,
        filed3: 0,
      },
    }`;
</script>

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

  .ant-btn-dashed {
    border-color: #ddd;

    &:hover {
      border-color: @primary-color;
    }
  }
</style>
