<template>
  <div @click="show" class="slot-item">
    <slot></slot>
  </div>
  <ModalPanel
    :visible="visible"
    :title="t('表单设置')"
    :width="1200"
    @submit="submit"
    @close="close"
  >
    <template #left>
      <Category v-model="setting.checkFormType" @change="changeType" :isShowAdded="false" />
    </template>
    <div class="relative h-full">
      <SelectedList type="form" :list="setting.selectedList" @abolish="abolishChecked" />
      <div class="absolute top-2 right-105px flex items-center">
        <SearchBox @search="searchList" />
        <div class="h-6 pr-4" style="border-right: 1px solid #ddd"></div>
      </div>
      <div class="list-page-box" v-if="setting.list.length > 0">
        <FormCard
          v-for="(item, index) in setting.list"
          :key="index"
          :item="item"
          :class="setting.checkedFormId.includes(item.formId) ? 'picked' : 'notPicked'"
          @click="checked(item)"
        >
          <template #check>
            <a-checkbox
              size="small"
              :checked="!!setting.checkedFormId.includes(item.formId)"
              :disabled="item.enabledMark == 1 ? false : true"
            />
          </template>
        </FormCard>
        <div class="page-box">
          <a-pagination
            v-model:current="setting.page.current"
            v-model:pageSize="setting.page.pageSize"
            :total="setting.page.total"
            show-less-items
            showQuickJumper
            showSizeChanger
            @change="getList"
          />
        </div>
      </div>
      <EmptyBox v-else />
    </div>
  </ModalPanel>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue';
  import { message } from 'ant-design-vue';
  import { ModalPanel, SearchBox, EmptyBox } from '/@/components/ModalPanel/index';
  import Category from '/@bpmn/components/formSettings/Category.vue';
  import SelectedList from '/@bpmn/components/formSettings/SelectedList.vue';
  import FormCard from '/@bpmn/components/card/FormCard.vue';
  import { FormType } from '/@/enums/workflowEnum';
  import { FormSettingItem } from '/@/model/workflow/formSetting';
  import { getFormTemplateEnabledPage } from '/@/api/form/design';
  import { randomFormNameStr, randomTime } from '/@bpmn/util/random';
  import { getUsedFormIds } from '/@bpmn/config/info';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  let props = withDefaults(defineProps<{ isSingle: Boolean; list: Array<FormSettingItem> }>(), {
    isSingle: () => {
      return false;
    },
    list: () => {
      return [];
    },
  });
  let emits = defineEmits(['submit', 'close']);

  const visible = ref(false);
  let setting: {
    checkFormType: FormType;
    selectedList: Array<FormSettingItem>;
    list: Array<FormSettingItem>;
    searchKeyword: string;
    page: { current: number; total: number; pageSize: number };
    formKeyList: Object;
    checkedFormId: Array<string>;
    usedRepeatedList: Object;
    usedNotRepeatedList: Array<string>;
    operationCloneItem: FormSettingItem;
  } = reactive({
    checkFormType: FormType.CUSTOM,
    selectedList: [],
    list: [],
    searchKeyword: '',
    page: { current: 1, total: 0, pageSize: 9 },
    formKeyList: {},
    checkedFormId: [],
    usedRepeatedList: {},
    usedNotRepeatedList: [],
    operationCloneItem: {
      key: '', //formId_key
      formType: FormType.CUSTOM, //表单类型
      formId: '', //表单ID   系统表单为文件夹名
      formName: '', //表单名称
    },
  });

  let selectKeys = computed(() => {
    if (setting.selectedList && setting.selectedList.length > 0) {
      return setting.selectedList.map((ele: FormSettingItem) => {
        return ele.formId;
      });
    }
    return [];
  });
  function show() {
    setting.checkFormType = FormType.CUSTOM;
    setting.list = [];
    setting.page.total = 0;
    setting.selectedList = cloneDeep(props.list);
    if (setting.selectedList.length) {
      setting.checkedFormId = setting.selectedList.map((x) => x.formId);
    }
    getList();
    visible.value = true;
  }
  function changeType() {
    setting.list = [];
    setting.page.total = 0;
    getList();
  }
  async function getList() {
    await getTemplateList();
  }

  async function getTemplateList() {
    let params = {
      limit: setting.page.current,
      size: setting.page.pageSize,
      type: setting.checkFormType,
      keyword: setting.searchKeyword,
      status: 1,
    };
    let res = await getFormTemplateEnabledPage(params);
    if (res.total) {
      setting.page.total = res.total;
    }
    setting.list = [];
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        if (setting.checkFormType == FormType.CUSTOM) {
          setting.list.push({
            key: 'form_' + ele.id + '_' + randomTime(),
            formType: FormType.CUSTOM,
            formName: ele.name ? ele.name : ele.id,
            formId: ele.id,
            enabledMark: ele.enabledMark,
          });
        } else {
          setting.list.push({
            key: 'form_' + ele.id + '_' + randomTime(),
            formType: FormType.SYSTEM,
            formName: ele.name,
            formId: ele.id,
            enabledMark: ele.enabledMark,
            functionName: ele.functionName,
            functionalModule: ele.functionalModule,
          });
        }
      });
    }
  }

  async function submit() {
    if (setting.selectedList.length === 0) {
      message.error(t('请至少选择一个表单'));
      return false;
    }
    emits('submit', setting.selectedList);
    close();
  }
  function close() {
    visible.value = false;
    emits('close');
  }
  function searchList(keyword: string) {
    setting.searchKeyword = keyword;
    setting.page.current = 1;
    getList();
  }
  function checked(item: FormSettingItem) {
    if (item.enabledMark != 1) return;
    let cloneItem: FormSettingItem = cloneDeep(item);
    cloneItem.formName = hasFormIdFromSelectedList(cloneItem.formId)
      ? cloneItem.formName + '_' + randomFormNameStr()
      : cloneItem.formName;
    cloneItem.key = 'form_' + cloneItem.formId + '_' + randomTime();
    setting.operationCloneItem = cloneItem;
    if (props.isSingle) {
      // 单选
      setting.selectedList = [];
      setting.checkedFormId = [];
      if (!setting.checkedFormId.includes(item.formId)) {
        submitOperation();
      }
    } else {
      // 多选
      if (setting.checkedFormId.includes(item.formId)) {
        // 取消选中
        if (selectKeys.value.includes(item.formId)) {
          let index = setting.selectedList.findIndex((ele) => {
            return ele.formId === item.formId;
          });

          setting.selectedList.splice(index, 1);
        }
        setting.checkedFormId = setting.checkedFormId.filter((x) => x !== item.formId);
      } else {
        submitOperation();
      }
    }
  }

  function hasFormIdFromSelectedList(formId) {
    let usedIds = [
      ...getUsedFormIds(),
      ...setting.selectedList.map((ele) => {
        return ele.formId;
      }),
    ];
    return usedIds.includes(formId);
  }
  function submitOperation() {
    let cloneItem: FormSettingItem = setting.operationCloneItem;
    setting.checkedFormId.push(cloneItem.formId);
    setting.selectedList.push(cloneItem);
  }

  function abolishChecked(item: FormSettingItem) {
    setting.selectedList = setting.selectedList.filter((ele) => {
      return ele.key != item.key;
    });
    setting.checkedFormId = setting.checkedFormId.filter((x) => x !== item.formId);
  }
</script>
<style lang="less" scoped>
  .list-box {
    display: flex;
    flex-wrap: wrap;
    padding: 10px 0;
  }

  .picked {
    border-width: 1px;
    border-style: dotted;
  }

  .notPicked {
    border-width: 1px;
    border-style: dotted;
    border-color: transparent;
  }

  .flow-used {
    height: calc(100% - 100px);
    overflow: auto;
  }

  :deep(.ant-collapse-ghost > .ant-collapse-item) {
    border-bottom: 1px solid #f5f5f5;
  }

  :deep(.ant-collapse-icon-position-right > .ant-collapse-item > .ant-collapse-header) {
    padding: 10px 16px;
  }

  :deep(.ant-collapse-content-box .ant-form-item) {
    margin-bottom: 12px;
  }

  :deep(.ant-collapse-content-box) {
    padding-left: 30px;
  }

  :deep(.ant-input-number) {
    width: 100%;
  }

  .opr-box {
    display: flex;
    padding: 30px 20px;

    .opr-icon {
      margin-right: 10px;
    }

    .opr-content {
      .title {
        font-weight: 700;
      }

      .desc {
        color: #a0a0a0;
      }
    }
  }
</style>
