<template>
  <a-modal
    v-model:visible="data.visible"
    :maskClosable="false"
    :width="1200"
    :title="title"
    @ok="submit"
    @cancel="close"
  >
    <div class="box" v-if="data.visible">
      <NodeHead class="mt-5 ml-4" :nodeName="t('基础信息')" />
      <a-row :gutter="16" class="!m-0">
        <a-col :span="12" class="!p-0">
          <div class="item">
            <label><em class="text-red-600">*</em>{{ t('被委托人') }}</label>
            <SelectUser
              style="width: calc(100% - 86px)"
              :selectedIds="data.delegateUserIds"
              :multiple="true"
              @change="
                (ids) => {
                  data.delegateUserIds = ids;
                }
              "
              @change-names="
                (names) => {
                  data.delegateUserNames = names;
                }
              "
            >
              <a-input-group compact style="width: 100%; text-align: left">
                <a-input
                  :value="data.delegateUserNames"
                  :placeholder="t('请选择委托人')"
                  style="width: calc(100% - 32px)"
                />
                <a-button
                  style="
                    background: #f8f8f8;
                    border-radius: 0 4px 4px 0;
                    border: 1px solid #ddd;
                    color: #c3c8cf;
                  "
                >
                  <template #icon><EllipsisOutlined /></template>
                </a-button>
              </a-input-group>
            </SelectUser>
          </div>
        </a-col>
        <a-col :span="12" class="!p-0">
          <div class="item">
            <label><em class="text-red-600">*</em>{{ t('时间区间') }}</label>
            <a-range-picker v-model:value="data.searchDate" style="width: calc(100% - 86px)" />
          </div>
        </a-col>
        <a-col :span="24" class="!p-0">
          <div class="item">
            <label>{{ t('委托说明') }}</label>
            <a-textarea
              v-model:value="data.remark"
              :placeholder="t('请填写委托说明')"
              :auto-size="{ minRows: 2, maxRows: 5 }"
              style="width: calc(100% - 86px)"
            />
          </div>
        </a-col>
      </a-row>
      <div class="mx-4 mt-30px flex justify-between">
        <NodeHead :nodeName="t('模板列表')" />
        <!-- <div class="flex items-center"> -->
        <SearchBox
          @search="
            (v) => {
              keyword = v;
              getList();
            }
          "
          @scroll-height="$emit('scrollHeight')"
        />
        <!-- <div class="pr-4 h-6" style="border-right: 1px solid #ddd"></div>
          <a-button class="w-74px !p-0 !rounded ml-4">全选</a-button>
        </div> -->
      </div>
      <template v-if="data.list.length > 0">
        <div class="list-page-box">
          <a-row :gutter="40" class="!-mx-5">
            <a-col :span="8" v-for="(item, index) in data.list" :key="index">
              <TemplateCard
                :class="data.checkSchemaIds.includes(item.id) ? 'picked' : ''"
                @click="check(item.id)"
                :item="item"
                ><template #pick>
                  <div class="dot"
                    ><a-checkbox
                      size="small"
                      :checked="data.checkSchemaIds && data.checkSchemaIds.includes(item.id)"
                  /></div>
                </template>
              </TemplateCard>
            </a-col>
          </a-row>
        </div>
        <div class="page-box">
          <a-pagination
            v-model:current="data.pagination.current"
            v-model:pageSize="data.pagination.pageSize"
            :total="data.pagination.total"
            show-less-items
            show-quick-jumper
            show-size-changer
            :show-total="(total) => t(`共 ${total} 条数据`)"
            @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';
  import { EllipsisOutlined } from '@ant-design/icons-vue';
  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: 12,
    },
  });
  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 {
    .item {
      display: flex;
      align-items: center;
      margin: 16px 16px 0;
      text-align: right;

      label {
        width: 86px;
        padding-right: 24px;
      }
    }

    .ant-input {
      border-radius: 4px;
    }
  }

  .list-page-box {
    overflow: hidden;
    padding: 16px;
    height: 394px;

    .ant-row {
      overflow-y: auto;
      height: 100%;
      align-content: baseline;
    }

    .list-item {
      width: 100%;
      height: 110px;
      background: #fff;
      border-radius: 16px;
      border: 1px solid #ddd;
      margin: 0 0 16px;

      &:hover {
        border: 1px solid @primary-color;
      }

      .dot {
        position: absolute;
        right: 20px;
        bottom: 25px;

        :deep(.ant-checkbox-inner) {
          width: 18px;
          height: 18px;
          border-radius: 50%;
        }

        :deep(.ant-checkbox) {
          &::after {
            border-color: transparent;
          }
        }
      }

      &.picked {
        border: 1px solid @primary-color;
      }

      :deep(.template-box) {
        padding-bottom: 8px;
      }
    }
  }

  .page-box {
    height: 52px;
    border-top: 1px solid rgb(238 238 238 / 93%);
    text-align: right;
    padding: 10px 16px;
  }
</style>
