<template>
  <div @click="show" v-if="isShow">
    <FormItemRest>
      <a-input
        readonly
        :disabled="disabled"
        :placeholder="placeholder"
        v-model:value="formName"
        :size="size"
        :bordered="bordered"
      >
        <template #prefix v-if="prefix">
          <Icon :icon="prefix" />
        </template>
        <template #suffix v-if="suffix">
          <Icon :icon="suffix" />
        </template>
      </a-input>

      <ModalPanel
        :visible="visible"
        :width="1200"
        :title="t('表单设置')"
        @submit="submit"
        @close="close"
      >
        <template #left>
          <div class="form-category">
            <NodeHead :nodeName="t('表单分类')" class="node-title" v-if="formType == 1" />
            <BasicTree
              v-if="formType == 1"
              :clickRowToExpand="true"
              :treeData="treeData"
              :fieldNames="{ key: 'id', title: 'name' }"
              @select="handleSelect"
            />

            <div class="tree-box" v-else>
              <NodeHead class="node-title" :node-name="t('代码模板分类')" />
              <div class="item" :class="modelValue === 0 ? 'checked' : ''" @click="change(0)">
                <IconFontSymbol class="item-icon" icon="xitong" />
                <span class="item-text">{{ t('数据优先模板') }}</span>
              </div>
              <div class="item" :class="modelValue == 1 ? 'checked' : ''" @click="change(1)">
                <IconFontSymbol class="item-icon" icon="zidingyi" />
                <span class="item-text">{{ t('界面优先模板') }}</span>
              </div>
              <div class="item" :class="modelValue == 2 ? 'checked' : ''" @click="change(2)">
                <IconFontSymbol class="item-icon" icon="xitong" />
                <span class="item-text">{{ t('简易模板') }}</span>
              </div>
            </div>
          </div>
        </template>
        <div class="relative h-full">
          <div class="flex items-center node-title justify-between pr-4"
            ><NodeHead :nodeName="t('表单列表')" /> <SearchBox @search="searchList" />
          </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="selectKeys.includes(item.key) ? 'picked' : 'notPicked'"
              @click="checked(item)"
            >
              <template #check>
                <a-checkbox
                  size="small"
                  :checked="selectKeys.includes(item.key) ? true : false"
                  :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
                show-size-changer
                show-quick-jumper
                :show-total="(total) => t(`共 ${total} 条数据`)"
                @change="getTemplateList"
              />
            </div>
          </div>
          <EmptyBox v-else />
        </div>
      </ModalPanel>
    </FormItemRest>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { ModalPanel, SearchBox, EmptyBox } from '/@/components/ModalPanel/index';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import FormCard from '/@bpmn/components/card/FormCard.vue';
  import { FormType } from '/@/enums/workflowEnum';
  import { FormSettingItem } from '/@/model/workflow/formSetting';
  import { getFormTemplateEnabledPage, getFormTemplatePage } from '/@/api/form/design';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Form } from 'ant-design-vue';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { Icon } from '/@/components/Icon';

  import { getDicDetailList } from '/@/api/system/dic';

  // 用于包裹弹窗的form组件 因为一个FormItem 只能收集一个表单组件  所以弹窗的form 必须排除
  const FormItemRest = Form.ItemRest;

  const props = defineProps({
    value: Object,
    prefix: String,
    suffix: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    size: String,
    isSingle: Boolean,
    isShow: {
      type: Boolean,
      default: () => true,
    },
    formType: {
      type: Number,
      default: () => 1,
    },
    list: {
      type: Array,
      default: () => [],
    },
    bordered: {
      type: Boolean,
      default: true,
    },
  });
  const { t } = useI18n();
  const treeData = ref<TreeItem[]>([]);
  let emits = defineEmits(['update:value', 'change']);
  const modelValue = ref(0);
  const category = ref();
  const formName = ref(props.value?.formName);

  watch(
    () => props.value,
    (val) => {
      if (val?.formName) {
        formName.value = val.formName;
        setting.selectedList.push({
          key: val.key,
          formType: val.formType,
          formId: val.formId,
          formName: val.formName,
        });
      } else {
        formName.value = '';
      }
    },
    { deep: true },
  );
  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: Object;
    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.key;
      });
    }
    return [];
  });
  async function show() {
    setting.list = [];
    setting.page.total = 0;
    await getTemplateList();
    visible.value = true;
  }

  async function getTemplateList() {
    let res: any = {};
    if (props.formType == 1) {
      treeData.value = (await getDicDetailList({
        itemId: '1419276800524424444',
      })) as unknown as TreeItem[];
      let params = {
        limit: setting.page.current,
        size: setting.page.pageSize,
        type: props.formType,
        category: category.value,
        keyword: setting.searchKeyword,
        enabledMark: 1,
        status: 1,
      };
      res = await getFormTemplatePage(params);
    } else {
      let params = {
        limit: setting.page.current,
        size: setting.page.pageSize,
        type: 0,
        formDesignType: modelValue.value,
        keyword: setting.searchKeyword,
      };
      res = await getFormTemplateEnabledPage(params);
    }
    if (res.total) {
      setting.page.total = res.total;
    }
    setting.list = [];
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        setting.list.push({
          key: ele.id,
          formType: props.formType,
          formName: props.formType == 1 ? ele.name : ele.functionName ? ele.functionName : ele.id,
          formId: ele.id,
          enabledMark: ele.status || 1,
        });
      });
    }
  }
  function change(type) {
    modelValue.value = type;
    getTemplateList();
  }
  function handleSelect(selectIds) {
    category.value = selectIds[0];
    getTemplateList();
  }
  async function submit() {
    if (setting.selectedList.length === 0) {
      message.error(t('请至少选择一个表单'));
      return false;
    }
    //formName.value = setting.selectedList[0].formName;
    emits('change', setting.selectedList[0]);
    emits('update:value', setting.selectedList[0]);
    close();
  }
  function close() {
    visible.value = false;
  }
  async function searchList(keyword: string) {
    setting.searchKeyword = keyword;
    setting.page.current = 1;
    await getTemplateList();
  }
  function checked(item: FormSettingItem) {
    if (item.enabledMark != 1) return;

    if (props.isSingle) {
      // 单选

      setting.selectedList = [item];
    } else {
      // 多选
      let index = setting.selectedList.findIndex((ele) => {
        return ele.key === item.key;
      });
      if (index >= 0) {
        setting.selectedList.splice(index, 1);
      } else {
        setting.selectedList.push(item);
      }
    }
  }
</script>

<style lang="less" scoped>
  .node-title {
    height: 50px;
    border-bottom: 1px solid #eee;
    padding-left: 16px;
  }

  .form-category {
    .tree-box {
      .item {
        display: flex;
        align-items: center;
        height: 40px;
        font-size: 14px;
        color: #606266;
        padding: 10px;

        .item-icon {
          font-size: 14px;
          color: #606266;
        }

        .item-text {
          margin-left: 20px;
        }
      }

      .checked {
        background-color: #f7fbff;
        border-right: 4px solid @primary-color;
      }
    }
  }
</style>
