<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑项目' : '添加项目'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="项目名称" name="appName">
        <div class="flex w-full justify-between gap-2">
          <a-input
            allow-clear
            placeholder="内容管理系统"
            v-model:value="form.appName"
          />
          <a-tooltip :title="`关联云应用实例(${form.websiteId})`">
            <SelectCmsWebsite
              :placeholder="`关联租户`"
              class="form-item"
              v-model:value="form.appName"
              @done="chooseCmsWebsite"
            />
          </a-tooltip>
        </div>
      </a-form-item>
      <a-form-item label="项目标识" name="appCode">
        <a-input
          allow-clear
          placeholder="cms"
          :disabled="isUpdate"
          v-model:value="form.appCode"
        />
      </a-form-item>
      <a-form-item label="项目状态" name="appStatus">
        <DictSelect
          dict-code="appstoreStatus"
          placeholder="请选择应用状态"
          class="input-item"
          v-model:value="form.appStatus"
          @done="onDone"
        />
      </a-form-item>
      <a-form-item label="开发进度" name="progress" v-if="form.appStatus == '开发中'">
        <a-slider v-model:value="form.progress" />
      </a-form-item>
<!--      <a-form-item label="绑定超管账号" name="companyName">-->
<!--        <a-select-->
<!--          v-model:value="form.companyName"-->
<!--          show-search-->
<!--          :filter-option="false"-->
<!--          style="width: 350px"-->
<!--          placeholder="选择客户"-->
<!--          :options="state.data"-->
<!--          @search="fetchUser"-->
<!--          @change="onUser"-->
<!--        >-->
<!--          <template v-if="state.fetching" #notFoundContent>-->
<!--            <a-spin size="small"/>-->
<!--          </template>-->
<!--        </a-select>-->
<!--      </a-form-item>-->
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import {addProject, pageProject, updateProject} from '@/api/project/project';
  import { Project } from '@/api/project/project/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import {debounce} from 'lodash-es';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import {DictData} from "@/api/system/dict-data/model";
  import {CmsWebsite} from "@/api/cms/cmsWebsite/model";
  import {pageUserAll} from "@/api/system/user";
  import {User} from "@/api/system/user/model";

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Project | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const state = reactive<any>({
    data: [],
    value: undefined,
    fetching: false,
  });

  // 用户信息
  const form = reactive<Project>({
    appId: undefined,
    appName: undefined,
    appCode: undefined,
    appSecret: undefined,
    parentId: undefined,
    appType: undefined,
    appTypeMultiple: undefined,
    menuType: undefined,
    companyId: undefined,
    companyName: undefined,
    appIcon: undefined,
    appQrcode: undefined,
    appUrl: undefined,
    adminUrl: undefined,
    downUrl: undefined,
    serverUrl: undefined,
    fileUrl: undefined,
    callbackUrl: undefined,
    docsUrl: undefined,
    gitUrl: undefined,
    prototypeUrl: undefined,
    ipAddress: undefined,
    images: undefined,
    packageName: undefined,
    clicks: undefined,
    installs: undefined,
    comments: undefined,
    content: undefined,
    requirement: undefined,
    developer: undefined,
    director: undefined,
    projectDirector: undefined,
    salesman: undefined,
    price: undefined,
    linePrice: undefined,
    score: undefined,
    star: undefined,
    path: undefined,
    component: undefined,
    authority: undefined,
    target: undefined,
    hide: undefined,
    search: undefined,
    active: undefined,
    meta: undefined,
    edition: undefined,
    version: undefined,
    isUse: undefined,
    file1: undefined,
    file2: undefined,
    file3: undefined,
    showExpiration: undefined,
    showCase: undefined,
    showIndex: undefined,
    recommend: undefined,
    expirationTime: undefined,
    soon: undefined,
    renewMoney: undefined,
    appStatus: '开发中',
    progress: undefined,
    deleted: undefined,
    userId: undefined,
    websiteId: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    status: 0,
    sortNumber: 100
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    companyName: [
      {
        required: true,
        type: 'string',
        message: '请填写客户名称',
        trigger: 'blur'
      }
    ],
    appName: [
      {
        required: true,
        type: 'string',
        message: '请填写项目名称',
        trigger: 'blur'
      }
    ],
    progress: [
      {
        required: true,
        type: 'number',
        message: '请填写开发进度',
        trigger: 'blur'
      }
    ],
    appCode: [
      {
        required: true,
        type: 'string',
        message: '请填写项目标识',
        trigger: 'blur'
      }
    ],
    appStatus: [
      {
        required: true,
        type: 'string',
        message: '请选择项目状态',
        trigger: 'blur'
      }
    ]
  });

  const onDone = (item: DictData) => {
    form.appStatus = item.dictDataCode
  }

  const chooseCmsWebsite = (item: CmsWebsite) => {
    form.websiteId = item.websiteId;
    form.appName = item.websiteName;
    form.appIcon = item.websiteLogo;
    form.appUrl = item.domain;
    form.appType = item.websiteType;
    form.companyId = item.userId;
    form.adminUrl = item.adminUrl;
  }


  let lastFetchId = 0;

  const fetchUser = debounce(value => {
    lastFetchId += 1;
    const fetchId = lastFetchId;
    state.data = [];
    state.fetching = true;
    pageUserAll({isAdmin: true,keywords: value})
      .then(body => {
        if (fetchId !== lastFetchId) {
          return;
        }
        state.data = body?.map(d => {
          d.label = d.realName;
          d.value = d.userId;
          return d
        }) || [];
        state.fetching = false;
      });
  }, 300);

  const onUser = (item: User) => {
    form.companyId = item.userId;
    form.companyName = item.realName;
  }

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateProject : addProject;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
