<!-- 开始节点配置 -->
<template>
  <div class="start-event">
    <a-form
      ref="formRef"
      :model="node"
      labelAlign="left"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :disabled="data.componentDisabled"
    >
      <a-form-item label="节点标识">
        <a-input v-model:value="node.id" placeholder="请输入" readonly />
      </a-form-item>
      <a-form-item label="下一审核人">
        <a-switch v-model:checked="node.isNextAuditor" @change="updateWfData('isNextAuditor')" />
      </a-form-item>
      <a-form-item label="自定义标题">
        <a-switch v-model:checked="node.isCustmerTitle" @change="updateWfData('isCustmerTitle')" />
      </a-form-item>
      <a-form-item label="通知策略" name="f_Color">
        <a-checkbox-group
          v-model:value="node.messageType"
          name="checkboxgroup"
          @change="updateWfData('messageType')"
          :options="[
            { value: '1', label: '短信' },
            { value: '2', label: '邮箱' },
            { value: '3', label: '微信' },
            { value: '4', label: '站内消息' },
          ]"
        />
      </a-form-item>
      <a-divider plain="true">表单添加</a-divider>
      <a-tabs
        v-model:activeKey="node.formType"
        type="card"
        size="small"
        centered="true"
        @change="tabsChange"
      >
        <a-tab-pane key="1" tab="自定义表单">
          <a-space direction="vertical" size="middle" class="site-space-compact-wrapper">
            <a-space-compact block>
              <a-input v-model:value="data.formName" placeholder="请选择表单" readonly />
              <a-button @click="handleShow">选择</a-button>
            </a-space-compact>
            <a-space-compact block>
              <a-select
                v-model:value="node.formVerison"
                placeholder="请选择表单版本"
                @change="custmerformVerisonChange"
                :options="data.formVerisons"
                :fieldNames="{ value: 'id', label: 'createDate' }"
              />
            </a-space-compact>
            <a-space-compact block>
              <a-select
                v-model:value="node.formRelationId"
                placeholder="请选择流程关联字段"
                @change="updateWfData('formRelationId')"
                :options="data.formRelations"
              />
            </a-space-compact>
          </a-space>
        </a-tab-pane>
        <a-tab-pane key="2" tab="系统表单">
          <a-space direction="vertical" size="middle" class="site-space-compact-wrapper">
            <a-space-compact block>
              <a-input
                v-model:value="node.formUrl"
                placeholder="请输入PC端表单地址"
                @change="updateWfData('formUrl')"
              />
            </a-space-compact>
            <a-space-compact block>
              <a-input
                v-model:value="node.formAppUrl"
                placeholder="请输入APP端表单地址"
                @change="updateWfData('formAppUrl')"
              />
            </a-space-compact>
          </a-space>
        </a-tab-pane>
      </a-tabs>

      <a-divider plain="true">表单字段权限</a-divider>
      <a-table
        :columns="data.columns"
        :data-source="node.authFields"
        bordered
        :pagination="false"
        v-if="node.formType == 1"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="['label', 'field'].includes(column.dataIndex)">
            <div>
              {{ text }}
            </div>
          </template>
          <template v-else-if="['required', 'disabled', 'ifShow'].includes(column.dataIndex)">
            <div>
              <a-switch v-model:checked="record[column.dataIndex]" size="small" />
            </div>
          </template>
        </template>
      </a-table>
      <a-table
        :columns="data.columns"
        :data-source="node.authFields"
        bordered
        :pagination="false"
        v-else
      >
        <template #bodyCell="{ column, record }">
          <template v-if="['label', 'fieldName'].includes(column.dataIndex)">
            <div>
              <a-input v-model:value="record[column.dataIndex]" placeholder="请输入" />
            </div>
          </template>
          <template v-else-if="['required', 'disabled', 'ifShow'].includes(column.dataIndex)">
            <div>
              <a-switch v-model:checked="record[column.dataIndex]" size="small" />
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <delete-outlined
              two-tone-color="#eb2f96"
              @click="handleDeleteAuthField(record.field)"
            />
          </template>
        </template>
      </a-table>

      <a-divider plain="true" />
      <a-space v-if="node.formType != 1">
        <a-button
          @click="handleAddAuthField"
          width="100%"
          type="dashed"
          danger
          :icon="h(PlusOutlined)"
          >添加字段</a-button
        >
      </a-space>
    </a-form>
    <a-modal
      width="60%"
      wrap-class-name="full-modal"
      v-model:open="data.formOpen"
      title="选择表单"
      @ok="formHandleOk"
      :destroyOnClose="true"
    >
      <SelectForm ref="formRef" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, defineProps, ref, watch, h, onMounted } from 'vue';
  import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { flowStore } from '@/store/modules/flow';
  import { SelectForm } from '@/components/SelectForm/index';
  import { functionGetSchemePageList, functionLoadFormPage } from '@/api/demo/formScheme';

  const flowWfDataStore = flowStore();
  const labelCol = { span: 7 };
  const wrapperCol = { span: 17 };
  // 表单选择声明
  const props = defineProps({
    disabled: {
      type: Boolean,
      default: false,
    },
    element: {
      type: Object,
      default: () => {
        return {};
      },
    },
    schemeCode: String,
    pageType: String,
    pageView: String,
  });
  interface dataType {
    columns: any;
    formRelations: any;
    elementData: any;
    componentDisabled: boolean;
    formOpen: boolean;
    formVerisons: any;
    formName: string;
  }
  const data: dataType = reactive({
    columns: [
      {
        title: '名称',
        dataIndex: 'label',
      },
      {
        title: '字段',
        dataIndex: 'fieldName',
      },
      {
        title: '必填',
        dataIndex: 'required',
      },
      {
        title: '编辑',
        dataIndex: 'disabled',
      },
      {
        title: '查看',
        dataIndex: 'ifShow',
      },
    ],
    formRelations: [],
    elementData: props.element,
    componentDisabled: props.pageType == 'detail' ? true : false,
    formOpen: false,
    formVerisons: [],
    formName: '',
  });
  let node: any = ref({});
  watch(
    () => node.value.formCode,
    (newVal) => {
      if (newVal) {
        getFormList();
        getVersions(false);
      }
    },
  );
  watch(
    () => props.element,
    (newVal) => {
      if (newVal.type == 'bpmn:StartEvent') {
        const currentNode = flowWfDataStore.getWfDataNode(newVal.id);
        if (currentNode) {
          node.value = currentNode;
        } else {
          node.value = newVal;
        }
      }
    },
  );
  watch(
    () => node.value.formType,
    (newVal) => {
      if (newVal == 1) {
        data.columns = data.columns.filter((item) => item.dataIndex !== 'operation');
      } else {
        data.columns.push({
          title: '',
          dataIndex: 'operation',
        });
      }
    },
  );
  onMounted(() => {
    if (props.element.type == 'bpmn:StartEvent') {
      const currentNode = flowWfDataStore.getWfDataNode(props.element.id);
      if (currentNode) {
        node.value = currentNode;
      } else {
        node.value = props.element;
      }
    }
  });
  // 编辑时获取表单名称，表单版本
  async function getFormList() {
    const list = await functionLoadFormPage({
      page: 1,
      limit: 1000,
    });
    list.items.forEach((element) => {
      if (element.id == node.value.formCode) {
        data.formName = element.name;
      }
    });
  }
  // 切换自定义表单和系统表单
  function tabsChange() {
    data.formName = '';
    node.value.formCode = '';
    node.value.formVerison = '';
    node.value.formRelationId = '';
    node.value.formUrl = '';
    node.value.formAppUrl = '';
    node.value.authFields = [];
    node.value.formRelations = [];
  }
  // 表单选择打开
  function handleShow() {
    data.formOpen = true;
  }
  // 表单选择
  const formRef = ref<any>();
  async function formHandleOk() {
    let obj = formRef.value.getRow();
    node.value.formCode = obj[0].id;
    data.formName = obj[0].name;
    node.value.formVerison = '';
    node.value.formRelationId = '';
    node.value.formUrl = '';
    node.value.formAppUrl = '';
    node.value.authFields = [];
    node.value.formRelations = [];
    getVersions(true);
    data.formOpen = false;
  }
  async function getVersions(isChange) {
    const list = await functionGetSchemePageList({
      schemeInfoId: node.value.formCode,
    });
    data.formVerisons = list.items;
    if (node.value.formVerison) {
      custmerformVerisonChange(node.value.formVerison, isChange);
    }
  }
  // 表单版本更改
  async function custmerformVerisonChange(val, isChange) {
    let obj;
    console.log(val);
    console.log(data.formVerisons);
    data.formVerisons.forEach((element) => {
      if (element.id == val) {
        obj = element;
      }
    });
    loadFormScheme(obj.scheme, isChange);
  }
  function loadFormScheme(strScheme, isChange) {
    const scheme = JSON.parse(strScheme);
    console.log(scheme);
    const fields: any[] = [];
    const rfields: {
      label?: string;
      value?: string;
    }[] = [];
    scheme.formInfo.tabList.forEach((tabElement) => {
      tabElement.schemas.forEach(
        (element: { label?: string; field?: string; component: any; itemProps: any }) => {
          console.log(element);
          if (['InputGuid'].includes(element.component)) {
            rfields.push({
              label: element.label,
              // value:element.prop
              value: element.field,
            });
          }

          if (
            ![
              'Divider',
              'Grid',
              'Card',
              'CreateUser',
              'CreateTime',
              'ModifyUser',
              'ModifyTime',
            ].includes(element.component) &&
            !element.itemProps.hidden
          ) {
            let obj: any = element;
            obj.required = element.itemProps.required;
            // obj.componentProps.disabled = false;
            obj.disabled = true;
            obj.ifShow = true;
            obj.fieldName = element.componentProps.fieldName;
            fields.push(obj);
          } else if (['Grid'].includes(element.component) || element.type == 'subTable') {
            console.log('gridtable');
            fields.push({
              field: `${element.field}_add`,
              label: `${element.label || '表格'}-添加按钮`,
              required: false,
              disabled: true,
              ifShow: false,
              type: 'grid',
            });
            fields.push({
              field: `${element.field}_remove`,
              label: `${element.label || '表格'}-删除按钮`,
              required: false,
              disabled: true,
              ifShow: false,
              type: 'grid',
            });

            fields.push({
              field: `${element.field}_required`,
              label: `${element.label || '表格'}-数据`,
              required: element.itemProps.required,
              disabled: false,
              ifShow: false,
              type: 'gridrequired',
            });
            element.columns.forEach((child) => {
              child.children.forEach((t) => {
                fields.push({
                  gridprop: element.field,
                  field: t.field,
                  label: `${element.label || '表格'}-${t.label}`,
                  required: t.itemProps.required,
                  disabled: true,
                  ifShow: true,
                  fieldName: t.componentProps.fieldName,
                  ...t,
                });
              });
            });
          } else if (['Card'].includes(element.component)) {
            element.columns.forEach((child) => {
              child.children.forEach((t) => {
                fields.push({
                  gridprop: element.field,
                  field: t.field,
                  required: t.itemProps.required,
                  disabled: true,
                  ifShow: true,
                  fieldName: t.componentProps.fieldName,
                  ...t,
                });
              });
            });
          } else if (
            ['CreateUser', 'CreateTime', 'ModifyUser', 'ModifyTime'].includes(element.component) &&
            element.display
          ) {
            let obj: any = element;
            obj.required = element.itemProps.required;
            // obj.componentProps.disabled = false;
            obj.disabled = true;
            obj.ifShow = true;
            obj.fieldName = element.componentProps.fieldName;
            fields.push(obj);
          }
        },
      );
    });
    console.log(fields);
    data.formRelations = rfields;
    if (isChange) {
      node.value.authFields = fields;
    }
  }
  function updateWfData(key) {
    // flowWfDataStore.updataWfDataNode(node.value.id, key, node.value[key]);
  }
  function handleAddAuthField() {
    node.value.authFields.push({
      field: '',
      label: '',
      required: true,
      disabled: true,
      ifShow: true,
    });
  }
  function handleDeleteAuthField(key) {
    node.value.authFields = node.value.authFields.filter((item) => item.field !== key);
  }
</script>
<style lang="less" scoped>
  .site-space-compact-wrapper {
    width: 100%;

    .ant-select {
      width: 100%;
    }
  }

  ::v-deep .ant-tabs {
    padding: 0 !important;
  }

  ::v-deep .ant-space {
    width: 90%;
    margin-left: 5%;

    .ant-space-item {
      width: 100%;

      button {
        width: 20%;
      }
      .ant-btn-dangerous {
        width: 100%;
      }
    }
  }
  .l-rblock {
    width: 100%;
    height: 100%;
    background: #f0f2f5;
  }
  .l-page-pane {
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: 100%;
    max-width: 794px;
    overflow: hidden auto;
    background: #fff;
    border-radius: 4px;
    margin: auto;
    padding: 24px;
  }
  .addDataBaseTableBox {
    border: 1px dashed #f0f0f0;
    text-align: center;
    cursor: pointer;
    margin-top: -20px;
    &:hover {
      border-color: #409eff;
    }
  }
  .connectTableTitle {
    padding-top: 20px;
  }
  .formLine {
    height: 50px;
  }
</style>
