<template>
  <div @click.stop="open">
    <InputModel
      :value="props.modelValue.name"
      :placeholder="t('')"
      style="width: 100%; min-width: 100px"
    />
    <ModalPanel
      :visible="visible"
      :width="1100"
      :title="t('推送消息配置')"
      @submit="submit"
      @close="close"
    >
      <NodeHead :nodeName="t('模板信息')" class="title" />
      <SelectMessageTemplate :config="data.config" @set-config="setConfig" />
      <a-table
        :dataSource="data.config.configs"
        :columns="configColumns"
        :pagination="false"
        :scroll="{ y: '400px' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'assignmentType'">
            <a-select
              v-model:value="record.assignmentType"
              style="width: 100%"
              :placeholder="t('请选择赋值类型')"
              allowClear
              @change="
                () => {
                  record.value = '';
                }
              "
            >
              <a-select-option :value="bind.value" v-for="bind in paramTree" :key="bind.value">
                {{ bind.label }}
              </a-select-option>
            </a-select>
          </template>
          <template v-else-if="column.key === 'value'">
            <!-- 表单数据 -->
            <a-tree-select
              v-model:value="record.value"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :placeholder="t('点击选择表单数据')"
              allow-clear
              tree-default-expand-all
              :tree-data="data.dataInfo"
              @select="(_, node) => handleSelect(node, record)"
              v-if="record.assignmentType === 'formData'"
            />
            <a-input
              v-else
              v-model:value="record.value"
              :placeholder="record.type ? t('请填写值') : t('请先选择赋值类型后再配置值')"
            />
          </template>
        </template>
      </a-table>
      <div style="margin: 10px"></div>
      <NodeHead :nodeName="t('接收人配置')" class="title" />
      <div class="button-box">
        <div v-for="(item, index) in allComponentList" :key="index">
          <component
            v-if="item.show"
            :is="item.component"
            :memberList="data.config.receiverConfiguration"
            @change="changeList"
          >
            <a-button type="primary">{{ item.name }}</a-button>
          </component>
        </div>
        <a-button type="primary" @click="addFormCreator">添加表单创建人</a-button>
        <FormFields :memberList="data.config.receiverConfiguration" @change="changeList"
          ><a-button type="primary">表单字段</a-button></FormFields
        >
      </div>
      <a-table
        :dataSource="data.config.receiverConfiguration"
        :columns="memberTypeConfigColumns"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'memberType'">
            {{ getMemberType(record.memberType) }}
          </template>
          <template v-if="column.key === 'operation'">
            <Icon
              icon="ant-design:delete-outlined"
              class="delete-icon"
              @click="deleteItem(index)"
            />
          </template>
        </template>
      </a-table>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { computed, inject, reactive, ref } from 'vue';
  import { NodeHead, ModalPanel } from '/@/components/ModalPanel/index';
  import { InputModel } from '/@/components/ApiConfig';
  import { SelectMessageTemplate } from '/@/components/PushMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { MessageType } from '/@/enums/messageTemplate';
  import { cloneDeep } from 'lodash-es';
  import Icon from '/@/components/Icon/index';
  import { MessageConfigure } from '/@/components/PushMessage/src/interface';
  import Posts from '/@bpmn/components/member/Posts.vue';
  import Roles from '/@bpmn/components/member/Roles.vue';
  import Users from '/@bpmn/components/member/Users.vue';
  import FormFields from './FormFields.vue';
  import { MemberType } from '/@/enums/workflowEnum';
  import { isValidJSON } from '/@/utils/event/design';
  import message from 'ant-design-vue/lib/message';
  import { getMemberType } from '/@bpmn/config/info';

  const { t } = useI18n();
  const emit = defineEmits(['update:modelValue']);
  const widgetForm = inject('widgetForm') as any;
  const defaultParams = {
    id: '',
    name: '',
    type: MessageType.EMAIL,
    configs: [],
    receiverConfiguration: [],
  };
  const props = withDefaults(defineProps<{ modelValue: MessageConfigure }>(), {
    modelValue: () => {
      return {
        id: '',
        name: '',
        type: MessageType.EMAIL,
        configs: [],
        receiverConfiguration: [],
      };
    },
  });
  const visible = ref<boolean>(false);
  let data = reactive({
    config: defaultParams as MessageConfigure,
    dataSource: [],
    dataInfo: [
      {
        title: t('表单数据'),
        value: 'formData',
        disabled: true,
        children: [],
      },
      {
        title: '隐藏组件',
        value: 'hiddenComponents',
        disabled: true,
        children: [],
      },
      {
        title: '当前信息',
        value: 'currentInfo',
        disabled: true,
        children: [
          {
            title: t('当前人员名称'),
            value: '3-name',
          },
          {
            title: t('当前人员ID'),
            value: '3-id',
          },
          {
            title: t('当前人员编码'),
            value: '3-code',
          },
          {
            title: t('当前人员手机号'),
            value: '3-mobile',
          },
          {
            title: t('当前人员所属组织架构名称'),
            value: '3-departmentName',
          },
          {
            title: t('当前人员所属组织架构ID'),
            value: '3-departmentId',
          },
          {
            title: t('当前人员岗位ID'),
            value: '3-postId',
          },
          {
            title: t('当前人员角色ID'),
            value: '3-roles.id',
          },
        ],
      },
    ] as any[],
  });
  const allComponentList = computed(() => {
    return [
      { name: t('添加岗位'), component: Posts, show: true },
      { name: t('添加角色'), component: Roles, show: true },
      { name: t('添加人员'), component: Users, show: true },
    ];
  });

  function open() {
    if (props.modelValue.id) data.config = cloneDeep(props.modelValue);
    if (!!widgetForm?.value) {
      initFormData();
    }
    visible.value = true;
  }
  function close() {
    visible.value = false;
  }

  function submit() {
    emit('update:modelValue', cloneDeep(data.config));
    close();
  }
  function setConfig(config) {
    if (config.id) data.config.id = config.id;
    if (config.name) data.config.name = config.name;
    if (config.messageType) data.config.type = config.messageType;
    let jsonObj = JSON.parse(config.messageConfig);
    if (jsonObj.configureData && jsonObj.configureData.length > 0) {
      data.config.configs = jsonObj.configureData.map((ele) => {
        ele.assignmentType = 'value';
        ele.value = '';
        return ele;
      });
    }
  }
  function deleteItem(index) {
    let list = data.config.receiverConfiguration;
    list.splice(index, 1);
  }

  function changeList(list) {
    data.config.receiverConfiguration = list;
  }
  function initFormData() {
    data.dataInfo[0].children = [];
    widgetForm?.value?.hiddenComponent?.map((com) => {
      let obj = {
        bindField: com.bindField,
        bindTable: '',
        tableKey: '',
        fieldKey: com.key,
      };
      data.dataInfo[1].children.push({
        title: com.label,
        value: JSON.stringify(obj),
      });
    });
    if (widgetForm?.value?.list.length) {
      getSelectedList(widgetForm.value.list);
    }
  }
  const filterComps = [
    'divider',
    'upload',
    'image',
    'qrcode',
    'button',
    'map',
    'opinion',
    'title',
'ai-answer',
    //'form-view',
  ];
  const getSelectedList = (list, bindTable?, key?) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getSelectedList(child.list);
        }
      } else if (item.type == 'table-layout') {
        for (const child of item.layout!) {
          for (const chilLi of child.list) {
            getSelectedList(chilLi.children);
          }
        }
      } else if (item.type == 'one-for-one') {
        getSelectedList(item.children, item.bindTable, item.key);
      } else if (item.type !== 'form' && !filterComps.includes(item.type)) {
        let params: string[] = [];
        if (item.options.datasourceType == 'api' && item.options.apiConfig.apiParams) {
          item.options.apiConfig.apiParams.forEach((p) => {
            p.tableInfo &&
              p.tableInfo.forEach((o) => {
                const value = isValidJSON(o.value);
                if (value) params.push(value.fieldKey);
              });
          });
        }
        // if (item.key !== props.formItem?.key && !params.includes(props.formItem?.key)) {
        let bindField = item.bindField;
        if (item.type == 'time-range' || item.type == 'date-range') {
          bindField = item.bindStartTime + ',' + item.bindEndTime;
        }
        let obj = {
          bindField: bindField,
          bindTable: bindTable,
          tableKey: key,
          fieldKey: item.key,
        };
        data.dataInfo[0].children.push({
          title:
            item.label +
            (item.type == 'user' || (item.type == 'info' && item.options.infoType === 0)
              ? '-ID'
              : ''),
          value: JSON.stringify(obj),
        });
        if (item.type == 'user' || (item.type == 'info' && item.options.infoType === 0)) {
          let obj = {
            bindField: bindField,
            bindTable: bindTable,
            tableKey: key,
            fieldKey: item.key,
            options: {
              type: item.type,
              showName: true,
            },
          };
          data.dataInfo[0].children.push({
            title: item.label + '-名称',
            value: JSON.stringify(obj),
          });
        }
        // }
      }
    });
  };
  const handleSelect = ({ value }, record) => {
    if (!value) {
      message.error(t('请先选择该组件的绑定表及绑定字段'));
      record.value = null;
    }
  };
  function addFormCreator() {
    let index = data.config.receiverConfiguration.length;
    data.config.receiverConfiguration.push({
      memberType: MemberType.FORM_CREATOR,
      id: 'form_creator' + index, //存储所选值Id
      name: '表单创建人', //存储所选值name
    });
  }
  const paramTree = [
    {
      label: t('值'),
      value: 'value',
    },
    {
      label: t('表单数据'),
      value: 'formData',
    },
  ];
  let configColumns = [
    {
      title: t('参数名称'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('参数说明'),
      dataIndex: 'description',
      key: 'description',
      align: 'center',
    },
    {
      title: t('赋值类型'),
      dataIndex: 'assignmentType',
      key: 'assignmentType',
      align: 'center',
    },
    {
      title: t('赋值配置'),
      dataIndex: 'value',
      key: 'value',
      align: 'center',
    },
  ];
  const memberTypeConfigColumns = [
    {
      title: t('类型'),
      dataIndex: 'memberType',
      key: 'memberType',
      align: 'center',
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'operation',
      key: 'operation',
      align: 'center',
    },
  ];
</script>

<style lang="less" scoped>
  .title {
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
  }

  .padding {
    padding: 10px 20px;
  }

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

  .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;
    }
  }

  :deep(.ant-spin-nested-loading) {
    height: auto;
    max-height: 480px;
  }

  :deep(.ant-btn-primary) {
    margin: 0 4px;
  }

  .button-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .delete-icon {
    color: @clear-color;
  }
</style>
