<template>
  <a-modal
    v-model:visible="data.visible"
    :maskClosable="false"
    :width="900"
    :title="title"
    @ok="submit"
    @cancel="close"
  >
    <div class="box" v-if="data.visible">
      <NodeHead class="mb-3 mt-3" :nodeName="t('基础信息')" />
      <div class="item">
        <label><em class="text-red-600">*</em>{{ t('被委托人：') }}</label>
        <SelectUser
          :selectedIds="data.delegateUserIds"
          :multiple="true"
          @change="
            (ids) => {
              data.delegateUserIds = ids;
            }
          "
          @change-names="
            (names) => {
              data.delegateUserNames = names;
            }
          "
        >
          <a-input
            :value="data.delegateUserNames"
            :placeholder="t('请选择委托人')"
            style="width: 100%"
          />
        </SelectUser>
      </div>
      <div class="item">
        <label><em class="text-red-600">*</em>{{ t('时间区间：') }}</label>
        <a-range-picker v-model:value="data.searchDate" style="width: 100%" />
      </div>
      <div class="item">
        <label>{{ t('委托说明：') }}</label>
        <a-textarea
          v-model:value="data.remark"
          :placeholder="t('请填写委托说明')"
          :auto-size="{ minRows: 2, maxRows: 5 }"
          style="width: 100%"
        />
      </div>
      <NodeHead class="mb-3 mt-3" :nodeName="t('模板列表')" />
      <SearchBox
        :searchConfig="{
          field: 'keyword',
          label: t('模板名称'),
          type: 'input',
        }"
        @search="
          (v) => {
            keyword = v;
            getList();
          }
        "
        @scroll-height="$emit('scrollHeight')"
      />
      <template v-if="data.list.length > 0">
        <div class="list-page-box">
          <TemplateCard
            v-for="(item, index) in data.list"
            :class="data.checkSchemaIds.includes(item.id) ? 'picked' : ''"
            @click="check(item.id)"
            :key="index"
            :item="item"
          />
        </div>
        <div class="page-box">
          <a-pagination
            v-model:current="data.pagination.current"
            :pageSize="data.pagination.pageSize"
            :total="data.pagination.total"
            show-less-items
            @change="getList"
        /></div>
      </template>

      <div v-else>
        <EmptyBox />
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import TemplateCard from '/@bpmn/components/card/TemplateCard.vue';
  import { EmptyBox } from '/@/components/ModalPanel/index';
  import { getDesignPage } from '/@/api/workflow/design';
  import { postDelegate, putDelegate, getDelegateInfo } from '/@/api/workflow/delegate';
  import { notification } from 'ant-design-vue';
  import dayjs, { Dayjs } from 'dayjs';
  import { SearchBox } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  let props = defineProps({
    id: String,
  });
  let emits = defineEmits(['close']);
  const title = computed(() => {
    return props.id == '' ? t('新增流程委托') : t('编辑流程委托');
  });
  const keyword = ref('');
  const data: {
    visible: boolean;
    delegateUserNames: string;
    delegateUserIds: Array<string>;
    schemaIds: string;
    startTime: string;
    endTime: string;
    remark: string;
    searchDate: [Dayjs | null, Dayjs | null];
    pagination: { current: number; total: number; pageSize: number };
    list: Array<any>;
    checkSchemaIds: Array<string>;
  } = reactive({
    visible: false,
    delegateUserNames: '',
    delegateUserIds: [],
    schemaIds: '',
    startTime: '',
    endTime: '',
    remark: '',
    searchDate: [null, null],
    list: [],
    checkSchemaIds: [],
    pagination: {
      current: 1,
      total: 0,
      pageSize: 6,
    },
  });
  onMounted(() => {
    open();
  });
  async function open() {
    if (props.id) {
      try {
        let res = await getDelegateInfo(props.id);
        if (res.delegateUserIds) {
          data.delegateUserIds = res.delegateUserIds.split(',');
        }
        if (res.schemaIds) {
          data.checkSchemaIds = res.schemaIds.split(',');
        }
        if (res.remark) {
          data.remark = res.remark;
        }
        if (res.startTime && res.endTime) {
          data.searchDate = [dayjs(res.startTime), dayjs(res.endTime)];
        }
      } catch (error) {}
    }
    await getList();
    data.visible = true;
  }
  function close() {
    data.visible = false;
    emits('close');
  }
  function check(id: string) {
    if (data.checkSchemaIds.includes(id)) {
      data.checkSchemaIds.splice(
        data.checkSchemaIds.findIndex((itemId) => itemId === id),
        1,
      );
    } else {
      data.checkSchemaIds.push(id);
    }
  }
  async function getList() {
    const searchParams = {
      limit: data.pagination.current,
      size: data.pagination.pageSize,
      keyword: keyword.value,
      enabledMark: 1,
    };

    try {
      let res = await getDesignPage(searchParams);
      data.pagination.total = res.total;
      data.list = res.list;
    } catch (error) {}
  }
  async function submit() {
    if (data.delegateUserIds.length == 0) {
      notification.open({
        type: 'error',
        message: t('流程委托'),
        description: t('请选择被委托人'),
      });
      return false;
    }
    if (data.checkSchemaIds.length == 0) {
      notification.open({
        type: 'error',
        message: t('流程委托'),
        description: t('请选择模板'),
      });
      return false;
    }
    if (!data.searchDate[0] || !data.searchDate[1]) {
      notification.open({
        type: 'error',
        message: t('流程委托'),
        description: t('请选择时间区间'),
      });
      return false;
    }
    try {
      let res = false;
      let params = {
        delegateUserIds: data.delegateUserIds.join(','),
        schemaIds: data.checkSchemaIds.join(','),
        remark: data.remark,
        startTime: data.searchDate[0],
        endTime: data.searchDate[1],
      };
      if (props.id) {
        res = await putDelegate(props.id, params);
      } else {
        res = await postDelegate(params);
      }
      if (res) {
        notification.open({
          type: 'success',
          message: t('流程委托'),
          description: title.value + t('成功'),
        });
        close();
      } else {
        notification.open({
          type: 'error',
          message: t('流程委托'),
          description: title.value + t('失败'),
        });
      }
    } catch (error) {}
  }
</script>

<style lang="less" scoped>
  .box {
    position: relative;
    padding: 10px;
    height: 578px;

    .item {
      display: flex;
      align-items: center;
      margin: 8px;

      label {
        width: 90px;
      }
    }
  }

  .list-page-box {
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
    height: 240px;
  }

  .page-box {
    position: absolute;
    bottom: 20px;
    right: 20px;
  }

  .picked {
    border-width: 3px;
    border-style: dotted;
    border-color: #5332f5;
  }
</style>
