<template>
  <w-dialog ref="dialogRef" title="选取变量" width="80%" height="80%" :buttons="dialog.buttons">
    <div class="h-full">
      <div class="h-[300px]">
        <w-grid
          ref="templateParamsGridRef"
          dense
          sort-no
          title="模板变量列表"
          :auto-fetch-data="false"
          :data-url="Environment.apiContextPath('api/excel/template/params')"
          :columns="templateParamsGrid.columns"
          :toolbar-actions="templateParamsGrid.toolbarActions"
          :config-button="false"
          :query-form-cols-num="3"
          :query-form-fields="templateParamsGrid.queryFormFields"
          :sort-by="['-lastModifyDate']"
          @row-click="templateParamsGridClick"
        ></w-grid>
      </div>
      <div style="height: calc(100% - 300px)">
        <w-grid
          v-show="state.showListFieldGrid"
          ref="templateParamsListFieldGridRef"
          dense
          sort-no
          :config-button="false"
          :hide-bottom="false"
          :pageable="false"
          title="字段列表"
          :auto-fetch-data="false"
          :fetch-data-url="Environment.apiContextPath('api/excel/template/params/list')"
          :columns="templateParamsListFieldGrid.columns"
        ></w-grid>
      </div>
    </div>
  </w-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue';
import { useQuasar } from 'quasar';
import { axios, Environment, NotifyManager, OperatorTypeEnum } from 'platform-core';

const $q = useQuasar();
const emit = defineEmits<{
  (
    e: 'setParams', // 设置模板变量
    paramsCode: string | Array<string>, // 变量编码（列表类型返回数组）
  ): void;
}>();

const dialogRef = ref();
const templateParamsGridRef = ref();
const templateParamsListFieldGridRef = ref();

const state = reactive({
  templateArray: [],
  tableSelectedTemplateId: null,
  showListFieldGrid: false,
});

const dialog = {
  buttons: [
    {
      icon: 'save',
      label: '确定',
      click: async () => {
        const paramsSelected = templateParamsGridRef.value.getSelectedRows();
        const listFieldSelected = templateParamsListFieldGridRef.value.getSelectedRows();
        if (paramsSelected && paramsSelected.length > 0) {
          if (paramsSelected[0].paramsType === 'LIST' && (!listFieldSelected || listFieldSelected.length === 0)) {
            const listFieldRows = templateParamsListFieldGridRef.value.getRows();
            const arr = <string[]>[];
            listFieldRows.forEach((item) => {
              arr.push('#{' + item.name + '}');
            });
            emit('setParams', arr);
            hide();
            return;
          } else if (paramsSelected[0].paramsType === 'LIST' && listFieldSelected && listFieldSelected.length > 0) {
            emit('setParams', '#{' + listFieldSelected[0].name + '}');
            hide();
            return;
          }
        } else {
          NotifyManager.warn('请选择要插入的变量');
          return;
        }
      },
    },
  ],
};

const templateParamsGrid = reactive({
  queryFormFields: [
    { label: '变量名称', name: 'paramsName', type: 'w-text' },
    {
      label: '变量类型',
      name: 'paramsType',
      type: 'w-select',
      queryOperator: 'equals',
      options: [
        { label: '单值', value: 'SING' },
        { label: '列表', value: 'LIST' },
      ],
    },
    {
      label: '所属模板',
      name: 'reportExcelTemplate',
      type: 'w-select',
      queryOperator: 'equals',
      clearable: true,
      colspan: 2,
      options: [],
    },
  ],
  toolbarActions: ['query', 'reset'],
  columns: [
    { name: 'paramsCode', label: '变量编码' },
    { name: 'paramsName', label: '变量名称' },
    {
      name: 'paramsType',
      label: '变量类型',
      format: (val) => {
        if (val === 'SING') {
          return '单值';
        } else if (val === 'LIST') {
          return '列表';
        } else {
          return val;
        }
      },
    },
    {
      name: 'paramsIsCommon',
      label: '变量是否通用',
      format: (val) => {
        if (val === true) {
          return '所有模板均可使用';
        } else if (val === false) {
          return '指定模板可使用';
        } else {
          return val;
        }
      },
    },
    { name: 'reportExcelTemplateName', label: '所属模板名称' },
    { name: 'lastModifier', label: '最后修改人' },
    { name: 'lastModifyDate', label: '最后修改时间' },
  ],
});

const templateParamsListFieldGrid = reactive({
  columns: [
    { name: 'name', label: '字段名' },
    { name: 'desc', label: '字段描述' },
    {
      name: 'formatType',
      label: '格式化类型',
      format: (val) => {
        if (val && OperatorTypeEnum[val]) {
          return OperatorTypeEnum[val];
        } else {
          return val;
        }
      },
    },
    { name: 'formatValue', label: '格式化值' },
  ],
});

const templateParamsGridClick = (args) => {
  const { evt, row, index } = args;
  if (row.paramsType === 'LIST') {
    state.showListFieldGrid = true;
    const urlSearchParams = new URLSearchParams();
    urlSearchParams.append('criteria', JSON.stringify({ fieldName: 'reportExcelTemplateParams', operator: 'equals', value: row.id }));
    axios
      .get(Environment.apiContextPath('api/excel/template/params/list?pageable=false&sortBy=sortNo'), { params: urlSearchParams })
      .then((resp) => {
        if (resp.data.content) {
          templateParamsListFieldGridRef.value.setLocalData(resp.data.content);
        }
      })
      .catch((error) => {
        console.info('error====', error);
      });
  } else {
    // 清空字段列表
    templateParamsListFieldGridRef.value.setLocalData([]);
    // 隐藏字段列表
    state.showListFieldGrid = false;
  }
};
const getTemplateListFun = async () => {
  const resp = await axios.get(Environment.apiContextPath('api/excel/template?pageable=false'));
  if (resp && resp.data?.content) {
    const options = <any>[];
    resp.data.content.forEach((item) => {
      options.push({ label: item.templateName, value: item.id });
    });
    state.templateArray = options;
    templateParamsGridRef.value.getQueryForm().getFields()['reportExcelTemplate'].options = options;

    setTimeout(() => {
      if (state.tableSelectedTemplateId) {
        templateParamsGridRef.value.getQueryForm().setFieldValue('reportExcelTemplate', state.tableSelectedTemplateId);
      }
      // 设置完所属模板后加载变量列表的数据
      templateParamsGridRef.value.refresh();
    }, 100);
  }
};
const show = (templateId) => {
  dialogRef.value.show();
  if (templateId) {
    state.tableSelectedTemplateId = templateId;
  } else {
    state.tableSelectedTemplateId = null;
  }
  nextTick(() => {
    getTemplateListFun();
  });
};
const hide = () => {
  dialogRef.value.hide();
};

defineExpose({
  show,
  hide,
});
</script>
