<template>
  <div @click.stop="open">
    <InputModel
      :value="props.modelValue.name"
      :placeholder="t('配置推送消息')"
      style="width: 100%; min-width: 100px"
    />
    <ModalPanel
      :visible="visible"
      :width="1200"
      :title="t('推送消息配置')"
      @submit="submit"
      @close="close"
    >
      <NodeHead :nodeName="t('模板信息')" class="ml-4 my-4" />
      <SelectMessageTemplate :config="data.config" @set-config="setConfig" />
      <div :class="[prefixCls, 'px-4', '!h-50']">
        <a-table
          size="middle"
          :dataSource="data.config.configs"
          :columns="configColumns"
          :pagination="false"
          :scroll="{ y: '400px' }"
          ><template #headerCell="{ column }">
            <div class="header-cell__custom-title">{{ column.title }}</div>
          </template>
          <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.config = null;
                  }
                "
              >
                <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-select
                v-if="record.assignmentType === 'approvalResult'"
                v-model:value="record.config"
                style="width: 100%"
                :placeholder="t('请选择节点')"
                allowClear
              >
                <a-select-option :value="it.id" v-for="it in data.nodeList" :key="it.id">
                  {{ it.name }}
                </a-select-option>
              </a-select>

              <!-- 流程参数 -->
              <a-select
                v-else-if="record.assignmentType === 'processParameter'"
                v-model:value="record.config"
                style="width: 100%"
                :placeholder="t('请选择流程参数')"
                allowClear
              >
                <a-select-option
                  :value="it.id"
                  v-for="it in data.processParameterTree"
                  :key="it.id"
                >
                  {{ it.name }}
                </a-select-option>
              </a-select>

              <!-- 发起人信息 -->
              <a-tree-select
                v-else-if="record.assignmentType === 'originator'"
                v-model:value="record.config"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :placeholder="t('请选择发起人信息')"
                allow-clear
                tree-default-expand-all
                :tree-data="data.originatorTree"
                :field-names="{
                  children: 'children',
                  label: 'title',
                  value: 'key',
                }"
              />
              <!-- 表单数据 -->
              <a-tree-select
                v-else-if="record.assignmentType === 'formData'"
                v-model:value="record.config"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :placeholder="t('请选择表单数据')"
                allow-clear
                tree-default-expand-all
                :tree-data="data.formDataTree"
                :field-names="{
                  children: 'children',
                  label: 'title',
                  value: 'key',
                }"
              />
              <!-- 流程数据 -->
              <a-tree-select
                v-else-if="record.assignmentType === 'data'"
                v-model:value="record.config"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :placeholder="t('请选择流程数据')"
                allow-clear
                tree-default-expand-all
                :tree-data="data.paramTree"
                :field-names="{
                  children: 'children',
                  label: 'title',
                  value: 'key',
                }"
              />
              <a-input
                v-else
                v-model:value="record.value"
                :placeholder="record.type ? t('请填写值') : t('请先选择赋值类型后再配置值')"
              />
            </template>
          </template>
        </a-table>
      </div>

      <NodeHead :nodeName="t('接收人配置')" class="ml-4" />
      <div class="button-box">
        <a-button type="primary" @click.stop="addItem">添加当前节点候选审批人</a-button>
        <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>
      </div>
      <div :class="[prefixCls, 'px-4', '!h-50']">
        <a-table
          size="middle"
          :dataSource="data.config.receiverConfiguration"
          :columns="memberTypeConfigColumns"
          :pagination="false"
          :scroll="{ y: '400px' }"
          ><template #headerCell="{ column }">
            <div class="header-cell__custom-title">{{ column.title }}</div>
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'memberType'">
              {{ getMemberType(record.memberType) }}
            </template>
            <template v-if="column.key === 'operation'">
              <div class="delete-icon" @click="deleteItem(index)">{{ t('删除') }}</div>
            </template>
          </template>
        </a-table>
      </div>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { computed, 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 { TreeProps } from 'ant-design-vue';
  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 NodeApprover from '/@bpmn/components/member/NodeApprover.vue';
  import FormFields from '/@bpmn/components/member/FormFields.vue';
  import { BpmnNodeKey, MemberType } from '/@/enums/workflowEnum';
  import {
    getMemberType,
    getNodeList,
    getProcessParamConfigs,
    getVariablesTree,
  } from '../../config/info';
  import { useBpmnStore } from '../../store/bpmn';
  import { ProcessDataVariable } from '/@bpmn/config/rules';
  import { InfoItem } from '/@/model/workflow/bpmnConfig';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();
  const emit = defineEmits(['update:modelValue']);
  const store = useBpmnStore();
  const { infoId } = store;
  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: [],
    formDataTree: [] as TreeProps['treeData'],
    processParameterTree: [] as Array<{ id: string; name: string }>,
    originatorTree: [
      {
        title: t('发起人ID'),
        key: '#{initiator_id}#',
      },
      {
        title: t('发起人所属组织架构名称'),
        key: '#{initiator_dept_name}#',
      },
    ],
    paramTree: ProcessDataVariable,
    nodeList: [] as Array<InfoItem>,
  });

  const allComponentList = computed(() => {
    return [
      { name: t('添加岗位'), component: Posts, show: true },
      { name: t('添加角色'), component: Roles, show: true },
      { name: t('添加人员'), component: Users, show: true },
      { name: t('节点审批人'), component: NodeApprover, show: true },
      { name: t('表单字段'), component: FormFields, show: true },
    ];
  });

  function open() {
    if (props.modelValue.id) data.config = cloneDeep(props.modelValue);
    data.processParameterTree = getProcessParamConfigs();
    data.formDataTree = getVariablesTree({ needHideComponents: true, valueReprocessing: true });
    data.nodeList = getNodeList([BpmnNodeKey.USER]);
    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 addItem() {
    data.config.receiverConfiguration.push({
      memberType: MemberType.CURRENT_NODE_CANDIDATE,
      id: infoId, //存储所选值Id
      name: '当前节点候选审批人', //存储所选值name
    });
  }
  const paramTree = [
    {
      label: t('值'),
      value: 'value',
    },
    {
      label: t('流程数据'),
      value: 'data',
    },
    {
      label: t('流程参数'),
      value: 'processParameter',
    },
    {
      label: t('发起人信息'),
      value: 'originator',
    },
    {
      label: t('表单数据'),
      value: 'formData',
    },
    {
      label: t('节点审批结果'),
      value: 'approvalResult',
    },
  ];
  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>
  :deep(.ant-btn-primary) {
    margin: 0 0 0 10px;
    border-radius: 4px;
  }

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

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