<template>
  <div @click.stop="open">
    <InputModel
      :value="props.ruleConfig.name"
      :placeholder="t('配置规则流程')"
      style="width: 100%; min-width: 100px"
    />
    <ModalPanel
      :visible="visible"
      :width="900"
      :title="t('规则流程配置')"
      @submit="submit"
      @close="close"
    >
      <NodeHead :nodeName="t('规则流程信息')" class="ml-4 my-4" />
      <SelectRuleProcessTemplate :config="data.config" @set-config="setConfig" />
      <!-- 参数配置 -->
      <a-table :columns="columns" :data-source="data.dataSource" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'"> {{ record.name }} </template>
          <template v-else-if="column.key === 'type'">
            {{ getTypeOptionName(record.type) }}
          </template>
          <template v-else-if="column.key === 'assignmentType'">
            <a-select
              v-model:value="record.assignmentType"
              style="width: 220px"
              :placeholder="t('请选择赋值类型')"
              :options="data.assignmentTypeList"
              allowClear
              @change="record.assignmentValue = null"
            />
          </template>
          <template v-else-if="column.key === 'assignmentValue'">
            <a-tree-select
              v-if="record.assignmentType == dataFromType.table"
              v-model:value="record.assignmentValue"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              tree-default-expand-all
              :tree-data="tableComp"
            />
            <a-tree-select
              v-else-if="record.assignmentType == dataFromType.search"
              v-model:value="record.assignmentValue"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              tree-default-expand-all
              :tree-data="searchComp"
            />
            <a-tree-select
              v-else-if="record.assignmentType == dataFromType.tree"
              v-model:value="record.assignmentValue"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              tree-default-expand-all
              :tree-data="treeComp"
            />
            <a-tree-select
              v-else-if="record.assignmentType == dataFromType.form"
              v-model:value="record.assignmentValue"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              tree-default-expand-all
              :tree-data="formsComp"
            />
            <a-tree-select
              v-else-if="record.assignmentType == dataFromType.info"
              v-model:value="record.assignmentValue"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              tree-default-expand-all
              :tree-data="infoMap"
            />
            <a-input
              style="width: 220px"
              v-model:value="record.assignmentValue"
              :disabled="record.assignmentType === AssignmentTypeToRuleType.VALUE ? false : true"
              :placeholder="
                record.assignmentType === AssignmentTypeToRuleType.VALUE
                  ? t('请填写值')
                  : t('请先选择赋值类型后再配置值')
              "
              v-else
            />
          </template>
        </template>
      </a-table>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { inject, reactive, ref } from 'vue';
  import { NodeHead, ModalPanel } from '/@/components/ModalPanel/index';
  import { InputModel } from '/@/components/ApiConfig';
  import { SelectRuleProcessTemplate } from '/@/components/RuleProcess';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    RuleProcessConfig,
    RuleProcessConfigListModel,
  } from '/@/components/RuleProcess/src/interface';
  import { OperationType } from '/@/enums/workflowEnum';

  import { AssignmentTypeToRuleType } from '/@/api/ruleProcess/model';
  import { infoMap } from '/@/components/Designer';
  import { dataFromType } from '../../types';
  import { getCurPageComponents, getTableComponents } from '../../types/tool';
  const { t } = useI18n();
  const widgetForm = inject('widgetForm') as any;
  const emit = defineEmits(['change']);
  let props = withDefaults(
    defineProps<{
      ruleConfig: RuleProcessConfig;
      exampleStr?: string;
    }>(),
    {
      ruleConfig: () => {
        return {
          id: '',
          name: '',
          processParamConfigs: [],
        };
      },
      exampleStr: `{
        code: 0,
        msg: 'success',
        data: 'value',
      }`,
    },
  );
  const tableComp = ref<TreeSelectProps['treeData']>([]);
  const searchComp = ref<TreeSelectProps['treeData']>([]);
  const formsComp = ref<TreeSelectProps['treeData']>([]);
  const treeComp = ref<TreeSelectProps['treeData']>([]);
  let typeOptions = [
    {
      id: OperationType.VALUE,
      name: t('值'),
    },
    {
      id: OperationType.VARIABLE,
      name: t('变量'),
    },
    {
      id: OperationType.API,
      name: 'API',
    },
  ];

  const columns = [
    {
      title: '参数名称',
      key: 'name',
    },
    {
      title: '参数类型',
      key: 'type',
    },
    {
      title: '赋值类型',
      key: 'assignmentType',
      width: 220,
    },
    {
      title: '赋值配置',
      key: 'assignmentValue',
      width: 220,
    },
  ];
  let data: {
    assignmentTypeList: any;
    dataSource: unknown;
    dataInfo: any[];
    config: RuleProcessConfig;
  } = reactive({
    config: cloneDeep(props.ruleConfig),
    dataSource: [],
    dataInfo: [],
    assignmentTypeList: [],
  });

  const visible = ref<boolean>(false);
  function open() {
    data.assignmentTypeList = [
      {
        label: t('默认值'),
        value: AssignmentTypeToRuleType.DEFAULT,
      },
      {
        label: t('值'),
        value: AssignmentTypeToRuleType.VALUE,
      },
      {
        value: dataFromType.table,
        label: '表格组件',
      },
      {
        value: dataFromType.search,
        label: '查询组件',
      },
      {
        value: dataFromType.tree,
        label: '树形组件',
      },
      {
        value: dataFromType.form,
        label: '表单组件',
      },
      {
        value: dataFromType.info,
        label: '当前信息',
      },
    ];

    data.config = cloneDeep(props.ruleConfig);
    data.dataSource = data.config.processParamConfigs;
    if (!!widgetForm?.value) {
      let formList = [];
      getTableComponents(widgetForm.value, formList);
      getCurPageComponents(
        formList,
        tableComp.value,
        searchComp.value,
        formsComp.value,
        treeComp.value,
        null,
        false,
      );
    }
    visible.value = true;
  }
  function close() {
    visible.value = false;
  }

  function submit() {
    let json = { ...data.config, processParamConfigs: data.dataSource };
    emit('change', cloneDeep(json));
    close();
  }
  function setConfig(config: RuleProcessConfigListModel) {
    if (config.id) data.config.id = config.id;
    if (config.name) data.config.name = config.name;
    if (config.jsonContent) {
      let jsonObj = JSON.parse(config.jsonContent);
      if (jsonObj.processParamConfigs && Array.isArray(jsonObj.processParamConfigs)) {
        data.dataSource = jsonObj.processParamConfigs.map((ele) => {
          return {
            ...ele,
            assignmentType: data.assignmentTypeList[0].value,
            assignmentValue: '',
          };
        });
      }
    }
  }

  function getTypeOptionName(type) {
    let arr = typeOptions.filter((ele) => {
      return ele.id == type;
    });
    if (arr.length > 0) {
      return arr[0].name;
    } else {
      return '';
    }
  }
</script>

<style lang="less" scoped>
  .padding {
    padding: 10px 20px;
  }

  .btn-item {
    position: absolute;
    bottom: 10px;
    left: 16px;
  }

  .editor-box {
    width: 300px;
    position: absolute;
    height: 350px;
    left: 140px;
    bottom: 13px;
    border: 1px solid #ccc;
    box-shadow: 0 0 6px 3px #ccc;

    .editor-close {
      position: absolute;
      top: -3px;
      right: 13px;
      font-size: 16px;
      cursor: pointer;
    }

    .editor-copy {
      position: absolute;
      bottom: 5px;
      right: 15px;
      cursor: pointer;
      z-index: 999;
      color: #5e95ff;
    }
  }
</style>
