<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="700"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑应用' : '创建应用'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-descriptions :column="2">
        <a-descriptions-item>
          <a-form-item label="应用名称" name="appName">
            <a-input
              allow-clear
              placeholder="请输入应用名称"
              class="form-item"
              v-model:value="form.appName"
            />
          </a-form-item>
        </a-descriptions-item>
        <a-descriptions-item>
          <a-form-item label="项目类型" name="appType">
            <DictSelect
              dict-code="appType"
              class="form-item"
              placeholder="请选择项目类型"
              v-model:value="form.appType"
            />
          </a-form-item>
        </a-descriptions-item>
        <a-descriptions-item>
          <a-form-item label="应用标识" name="appCode">
            <a-input
              allow-clear
              placeholder="请输入应用标识(英文字母)"
              class="form-item"
              v-model:value="form.appCode"
              @input="changeAppCode"
            />
          </a-form-item>
        </a-descriptions-item>
        <a-descriptions-item>
          <a-form-item label="企业名称" name="companyName">
            <SelectCompany
              :placeholder="`所属企业`"
              class="form-item"
              v-model:value="form.companyName"
              @done="chooseCompanyName"
            />
          </a-form-item>
        </a-descriptions-item>
        <a-descriptions-item>
          <a-form-item label="关联租户" name="tenantCode">
            <a-input
              allow-clear
              placeholder="请输入关联的租户ID"
              class="form-item"
              v-model:value="form.tenantCode"
            />
          </a-form-item>
        </a-descriptions-item>
        <a-descriptions-item />
        <a-descriptions-item :span="2">
          <a-form-item label="应用描述" name="comments" class="ele-fluid">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入应用描述"
              v-model:value="form.comments"
            />
          </a-form-item>
        </a-descriptions-item>
      </a-descriptions>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, isChinese } from 'ele-admin-pro';
  import { addApp, updateApp } from '@/api/oa/app';
  import type { App } from '@/api/oa/app/model';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { Company } from '@/api/system/company/model';
  import { pageCompany } from '@/api/system/company';

  const useForm = Form.useForm;

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

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

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

  // 提交状态
  const loading = ref(false);
  // 是否是修改
  const isUpdate = ref(false);
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const form = reactive<App>({
    appId: undefined,
    appName: '',
    appCode: '',
    appType: undefined,
    companyName: '',
    tenantCode: '',
    comments: '',
    appStatus: '开发中'
  });

  // 表单验证规则
  const rules = reactive({
    appName: [
      {
        required: true,
        type: 'string',
        message: '请输入应用名称',
        trigger: 'blur'
      }
    ],
    // companyName: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择所属企业',
    //     trigger: 'blur'
    //   }
    // ],
    appCode: [
      {
        required: true,
        type: 'string',
        message: '请输入应用标识(英文字母)',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (isChinese(value)) {
            return Promise.reject('请输入正确的应用标识');
          }
          return Promise.resolve();
        }
      }
    ],
    appType: [
      {
        required: true,
        message: '请选择项目类型'
      }
    ]
  });

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

  const chooseCompanyName = (data: Company) => {
    form.appUrl = data.domain;
    form.companyName = data.companyName;
    form.companyId = data.companyId;
    form.tenantId = data.tenantId;
  };

  const changeAppCode = () => {
    form.packageName = `com.gxwebsoft.${form.appCode}`;
  };

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

  const reload = () => {
    loading.value = true;
    // 加载企业信息
    const companyId = props.data?.companyId;
    pageCompany({ companyId }).then((res) => {
      form.tenantId = undefined;
      const list = res?.list;
      if (list && list.length > 0) {
        form.tenantId = list[0].tenantId;
      }
    });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.search) {
            form.search = props.data.search == 1 ? true : 0;
          }
          isUpdate.value = true;
          reload();
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>

<style lang="less">
  .form-item {
    min-width: 300px;
  }
</style>
