<!-- 开始节点配置 -->
<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"
                @change="custmerformVerisonChange"
                :options="data.formVerisons"
                :fieldNames="{ value: 'id', label: 'createDate' }"
                placeholder="请选择表单版本"
              />
            </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-compact block>
              <a-input v-model:value="node.formTitle" placeholder="请输入表单标题" />
            </a-space-compact>
            <a-space-compact block>
              <a-input v-model:value="data.issueName" placeholder="请选择发布表单" readonly />
              <a-button @click="handleIssueShow">选择</a-button>
            </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.formTitle" placeholder="请输入PC端表单标题" />
            </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 #headerCell="{ column }">
          <template v-if="column.dataIndex === 'required'">
            <a-checkbox v-model:checked="requiredCheck" @change="handleChangeCheck('required',$event)">{{column.title}}</a-checkbox>
          </template>
          <template v-if="column.dataIndex === 'disabled'">
            <a-checkbox v-model:checked="disabledCheck" @change="handleChangeCheck('disabled',$event)">{{column.title}}</a-checkbox>
          </template>
          <template v-if="column.dataIndex === 'ifShow'">
            <a-checkbox v-model:checked="ifShowCheck" @change="handleChangeCheck('ifShow',$event)">{{column.title}}</a-checkbox>
          </template>
        </template>
        <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>
    <a-modal
      width="60%"
      wrap-class-name="full-modal"
      v-model:open="data.issueOpen"
      title="选择发布表单"
      @ok="issueHandleOk"
      :destroyOnClose="true"
    >
      <SelectIssueForm ref="issueRef" />
    </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 { SelectIssueForm } from '@/components/SelectIssueForm/index';
  import { functionGetSchemePageList, functionLoadFormPage } from '@/api/demo/formScheme';
  import { cardNestStructure } from '@/views/demo/onlineform/util.ts';
  import { fun_GetPageList } from '@/api/demo/formModule';
  import { getRFields } from '@/views/demo/workflow/scheme/util.ts'

  const flowWfDataStore = flowStore();
  const labelCol = { span: 7 };
  const wrapperCol = { span: 17 };
  const requiredCheck = ref(false)
  const disabledCheck = ref(false)
  const ifShowCheck = ref(false)
  // 表单选择声明
  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;
    issueOpen: boolean;
    issueName: string;
    mapConfig:string;
  }
  const data: dataType = reactive({
    columns: [
      {
        title: '名称',
        dataIndex: 'label',
        width: 100,
      },
      {
        title: '字段',
        dataIndex: 'fieldName',
        ellipsis: true,
      },
      {
        title: '必填',
        dataIndex: 'required',
        width: 85,
      },
      {
        title: '编辑',
        dataIndex: 'disabled',
        width: 85,
      },
      {
        title: '查看',
        dataIndex: 'ifShow',
        width: 85,
      },
    ],
    formRelations: [],
    elementData: props.element,
    componentDisabled: props.pageType == 'detail' ? true : false,
    formOpen: false,
    formVerisons: [],
    formName: '',
    issueName: '',
    issueOpen: false,
  });
  let node: any = ref({});
  watch(
    () => node.value.formCode,
    (newVal) => {
      if (newVal) {
        getFormList();
        getIssueFormList();
        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.formTitle = '';
    node.value.formVerison = undefined;
    node.value.formRelationId = undefined;
    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 = undefined;
    node.value.formRelationId = undefined;
    node.value.formUrl = '';
    node.value.formAppUrl = '';
    node.value.authFields = [];
    node.value.formRelations = [];
    getVersions(true);
    data.formOpen = false;
  }
  // 发布表单
  function handleIssueShow() {
    data.issueOpen = true;
  }
  const issueRef = ref<any>();
  async function issueHandleOk() {
    let obj = issueRef.value.getRow();
    let formPublishInfo = JSON.parse(obj[0].scheme)
    let mapConfig = formPublishInfo.table.maps;
    node.value.issueId = obj[0].id;
    node.value.mapConfig = mapConfig
    data.issueName = obj[0].name;
    data.issueOpen = false;
    data.mapConfig = mapConfig;
  }
  // 编辑时获取发布表单名称
  async function getIssueFormList() {
    const list = await fun_GetPageList({
      page: 1,
      limit: 1000,
    });
    list.items.forEach((element) => {
      if (element.id == node.value.issueId) {
        data.issueName = element.name;
      }
    });
  }

  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;
    data.formVerisons.forEach((element) => {
      if (element.id == val) {
        obj = element;
      }
    });
    loadFormScheme(obj.scheme, isChange);
  }
  function loadFormScheme(strScheme, isChange) {
    const scheme = JSON.parse(strScheme);
    let fields: any[] = [];
    let rfields: {
      label?: string;
      value?: string;
    }[] = [];
    scheme.formInfo.tabList = cardNestStructure(scheme.formInfo.tabList);
    scheme.formInfo.tabList.forEach((tabElement) => {
      const {rFieldList, fieldList} = getRFields(tabElement.schemas,rfields,fields)
      rfields = rFieldList
      fields = fieldList
    });
    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);
  }
  const handleChangeCheck = (type: string, data) => {
    let checked = data.target.checked
    node.value.authFields.forEach(item => {
      switch (type) {
        case 'required':
          item.required = checked
          break
        case 'disabled':
          item.disabled = checked
          break
        case 'ifShow':
          item.ifShow = checked
          break
      }
    })
  }
</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%;
      }
    }
  }
  :deep(.ant-checkbox+span){
    padding-inline-end: 0px;
  }
  .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>
