<template>
  <common-drawer :width="drawerWidth()" mask :visible="visible" @close="onClose" title="绑定表单" :z-index="props.zIndex">
    <div class="describe">
      说明：流程表单贯穿流程执行的整个生命周期，表单分为应用设计表单和自定义开发表单，并且两者不能同时存在。<br />
      应用设计表单：通过在线拖拽方式生成的表单。<br />
      自定义开发表单：通过编写Vue界面实现的表单（只能有一个）。
    </div>
    <div class="add">
      <a-space>
        <a-button type="primary" class="border-radius" @click="formIdListClick"><plus-outlined />应用设计表单</a-button>
        <a-button type="primary" class="border-radius" @click="customForm"><plus-outlined />自定义开发表单</a-button>
      </a-space>
    </div>
    <a-table :dataSource="formDefinitionList" :columns="columns" :key="tabKey" bordered size="small" :pagination="false">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex == 'sort'">
          <menu-outlined class="menu-outlined" />
        </template>
        <template v-if="column.dataIndex == 'index'">
          {{ index + 1 }}
        </template>
        <!-- 表单类型 -->
        <template v-if="column.dataIndex == 'formType'">
          <span v-if="record.formType == 1">应用设计</span>
          <span v-if="record.formType == 2">自定义开发表单</span>
        </template>
        <!-- 表单名称 -->
        <template v-if="column.dataIndex == 'formName'">
          <template v-if="record.formType == 1">{{ record.formName }}</template>
          <template v-if="record.formType == 2">
            <a-input v-model:value="record.formName" placeholder="请输入" @blur="blurChange(record, index, 'formName')"></a-input>
          </template>
        </template>
        <!-- 表单编码 -->
        <template v-if="column.dataIndex == 'formCode'">
          <template v-if="record.formType == 1">{{ record.formCode }}</template>
          <template v-if="record.formType == 2">
            <a-input v-model:value="record.formCode" placeholder="请输入" @blur="blurChange(record, index, 'formName')"></a-input>
          </template>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <icon-font iconClass="icon-opt-shanchu" font-size="24px" title="删除" color="#60666b" @click="remove(index)"></icon-font>
        </template>
      </template>
    </a-table>
    <div class="add"><a-button type="primary" class="border-radius" @click="onSave">确定</a-button></div>

    <!-- 应用设计表单选择 -->
    <FormListSelect v-model:visible="showForm" v-if="showForm" @done="closeFormSelect" />
  </common-drawer>
</template>

<script setup name="FlowFormDrawer">
import { message, Modal } from 'ant-design-vue/es';
import { ref, computed, nextTick, inject } from 'vue';
import { useWorkflowStore } from '@/store/modules/workflow';
import FormListSelect from './form-list-select.vue';
import { deepClone, isMobile } from '@/utils/common/util';
import Sortable from 'sortablejs';

const props = defineProps({
  zIndex: {
    type: Number,
    default: 1000
  }
});

// 侧边显示隐藏
const visible = ref(false);

/**
 * 侧边宽度
 * @returns
 */
const drawerWidth = computed(() => {
  return width => {
    if (!width) {
      width = '40%';
    }
    return isMobile() ? '100%' : width;
  };
});

// Store
const flowStore = useWorkflowStore();

// 绑定表单列表
const formDefinitionList = ref([]);

// 表格配置
const columns = ref([
  {
    title: '',
    dataIndex: 'sort',
    key: 'sort',
    align: 'center',
    width: 50
  },
  {
    title: '序号',
    width: 60,
    align: 'center',
    dataIndex: 'index'
  },
  {
    title: '表单类型',
    width: 150,
    dataIndex: 'formType'
  },
  {
    title: '表单名称',
    width: 200,
    dataIndex: 'formName'
  },
  {
    title: '表单编码',
    width: 150,
    dataIndex: 'formCode'
  },
  {
    title: '版本号',
    width: 150,
    dataIndex: 'formVersion'
  },
  {
    title: '操作',
    width: 60,
    align: 'center',
    dataIndex: 'action'
  }
]);

const tabKey = ref(0);

// 画布
const graph = inject('getGraph');

// 显示侧边
const show = async () => {
  visible.value = true;
  formDefinitionList.value = deepClone(flowStore.flowGlobalConfig.formDefinitionList);
  enableDrag();
};

// 是否显示表单选择
const showForm = ref(false);

// 事件
const emit = defineEmits(['close']);

// 拖拽
const sortable = ref(null);

// 关闭侧边
const onClose = () => {
  visible.value = false;
  emit('close');
};

// 拖拽
const enableDrag = () => {
  nextTick(() => {
    const tableEl = document.querySelector('.ant-table-tbody');
    sortable.value = Sortable.create(tableEl, {
      animation: 150,
      handle: '.menu-outlined',
      onEnd: onDragEnd // 拖拽结束后更新数据源顺序
    });
  });
};

// 拖拽结束后更新数据源顺序
const onDragEnd = evt => {
  const { oldIndex, newIndex } = evt;
  let arr = deepClone(formDefinitionList.value);
  const record = arr.splice(oldIndex, 1)[0];
  arr.splice(newIndex, 0, record);
  formDefinitionList.value = [...arr];
  tabKey.value++;
  enableDrag();
};

// 应用设计表单
const formIdListClick = () => {
  if (formDefinitionList.value.find(item => item.formType == 2)) {
    return message.warn('已存在自定义开发表单');
  }
  showForm.value = true;
};

// 关闭选择弹框
const closeFormSelect = data => {
  if (data && data.length > 0) {
    data.forEach(item => {
      if (!formDefinitionList.value.find(fItem => fItem?.formDefinitionId == item.currentDefinitionId)) {
        item.formDefinitionId = item.currentDefinitionId;
        item.formName = item.formModelName;
        item.formType = 1;
        item.formCode = item.formModelCode;
        item.formVersion = item.currentVersion;
        formDefinitionList.value.push(item);
      }
    });
  }
};

// 自定义表单添加
const customForm = () => {
  if (formDefinitionList.value.find(item => item.formType == 1)) {
    return message.warn('已存在应用设计表单');
  } else if (formDefinitionList.value.find(item => item.formType == 2)) {
    return message.warn('自定义开发表单只能存在一个，请删除了在操作!');
  }
  let obj = {
    formDefinitionId: undefined,
    formName: '',
    formType: 2,
    formCode: '',
    formVersion: '无'
  };
  formDefinitionList.value.push(obj);
};

// 删除表单
const remove = index => {
  formDefinitionList.value.splice(index, 1);
};

// 失去焦点
const blurChange = (record, index, name) => {
  let arr = formDefinitionList.value.filter((item, fIndex) => {
    return fIndex != index;
  });
  if (name && arr.find(item => item[name] == record[name])) {
    let messageValue = name == 'formName' ? '表单名称' : '表单编码';
    message.warning('当前' + messageValue + '已存在，请重新输入!');
    record[name] = '';
  }
};

// 保存
const onSave = () => {
  Modal.confirm({
    title: '提示',
    zIndex: 99999,
    content: '保存会清空所有节点的表单权限，是否确定保存！',
    maskClosable: true,
    onOk: () => {
      flowStore.setFormDefinitionList(formDefinitionList.value);
      let cells = graph.value.toJSON()?.cells ?? [];
      cells.forEach(cItem => {
        if (cItem.shape != 'edge' && cItem.data) {
          let data = JSON.parse(cItem.data);
          if ([13, 30].includes(data.type)) {
            let node = graph.value.getCellById(cItem.id);
            let currentData = JSON.parse(node.getData());
            const valueData = deepClone(currentData);
            if (JSON.stringify(valueData.data.nodeData) != '{}') {
              currentData.data.nodeData.formPermission = [];
              node.setData(JSON.stringify(currentData), {
                // 必须覆盖，否则出错
                overwrite: true
              });
            }
          }
        }
      });
      visible.value = false;
      emit('close');
    }
  });
};

defineExpose({
  show
});
</script>

<style scoped lang="less">
.add-form {
  color: var(--primary-color);
  font-size: 18px;
  cursor: pointer;
}
.describe {
  color: #a6a6a6;
}
.add {
  margin: 15px 0;
}
.menu-outlined {
  cursor: move;
}
</style>
