<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="800"
        :title="t(title || '请选择')"
        @submit="submit"
        @close="close"
      >
        <div class="relative h-full">
          <SearchBox @search="searchList" class="p-10px" />

          <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.code) ? 'picked' : 'notPicked'"
              @click="checked(item)"
            >
              <template #check>
                <a-checkbox size="small" :checked="selectKeys.includes(item.code) ? true : false" />
              </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 FormCard from '/@/layouts/page/imageCard.vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { Form } from 'ant-design-vue';

  import { Icon } from '/@/components/Icon';

  import { AppDataType } from '/@/enums/appEnum';
  import { AppDataItem } from '/@/model/generator/listConfig';
  import { getPageList } from '/@/api/desktop';
  import { getBiListPage } from '/@/api/bi';

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

  const props = defineProps({
    title: String,
    value: Object,
    prefix: String,
    suffix: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    size: String,
    isSingle: Boolean,
    isShow: Boolean,
    formType: {
      type: Number,
      default: () => AppDataType.DESKTOP,
    },
    list: {
      type: Array,
      default: () => [],
    },
    bordered: {
      type: Boolean,
      default: true,
    },
  });
  const { t } = useI18n();

  let emits = defineEmits(['update:value', 'change']);

  const formName = ref(props.value?.name);

  watch(
    () => props.value,
    (val) => {
      if (val?.name) {
        formName.value = val.name;
        setting.selectedList.push({
          code: val.code,
          name: val.name,
          formType: val.formType,
        });
      } else {
        formName.value = '';
      }
    },
    { deep: true },
  );
  const visible = ref(false);
  let setting: {
    checkFormType: AppDataType;
    selectedList: Array<AppDataItem>;
    list: Array<AppDataItem>;
    searchKeyword: string;
    page: { current: number; total: number; pageSize: number };
    formKeyList: Object;
    checkedFormId: Object;
    usedRepeatedList: Object;
    usedNotRepeatedList: Array<string>;

    operationCloneItem: AppDataItem;
  } = reactive({
    checkFormType: AppDataType.DESKTOP,
    selectedList: [],
    list: [],
    searchKeyword: '',
    page: { current: 1, total: 0, pageSize: 12 },
    formKeyList: {},
    checkedFormId: {},
    usedRepeatedList: {},
    usedNotRepeatedList: [],

    operationCloneItem: {
      formType: AppDataType.DESKTOP, //数据类型
      code: '', //数据id
      name: '', //数据名称
      img: '',
    },
  });

  let selectKeys = computed(() => {
    if (setting.selectedList && setting.selectedList.length > 0) {
      return setting.selectedList.map((ele: AppDataItem) => {
        return ele.code;
      });
    }
    return [];
  });
  async function show() {
    setting.list = [];
    setting.page.total = 0;
    await getTemplateList();
    visible.value = true;
  }

  async function getTemplateList() {
    let res: any = {};
    if (props.formType == AppDataType.DESKTOP) {
      let params = {
        limit: setting.page.current,
        size: setting.page.pageSize,
        keyword: setting.searchKeyword,
      };
      res = await getPageList(params);
    } else if (props.formType == AppDataType.BI) {
      let params = {
        current: setting.page.current,
        size: setting.page.pageSize,
        title: setting.searchKeyword,
      };
      res = await getBiListPage(params);
      res.list = res.records;
    }
    if (res.total) {
      setting.page.total = res.total;
    }
    setting.list = [];
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        setting.list.push({
          formType: props.formType,
          name: ele.name ? ele.name : ele.title ? ele.title : ele.id,
          code: ele.id,
          img: ele.backgroundUrl,
        });
      });
    }
  }

  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: AppDataItem) {
    if (props.isSingle) {
      // 单选

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

<style lang="less" scoped>
  .list-page-box {
    padding: 0 5px;
  }
</style>
