<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :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="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-descriptions title="基本信息" :column="2" bordered>
        <a-descriptions-item
          label="Logo"
          layout="vertical"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <SelectFile
            :placeholder="`请选择图片`"
            :limit="1"
            :data="logo"
            @done="chooseFile"
            @del="onDeleteItem"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="二维码"
          layout="vertical"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <SelectFile
            :placeholder="`请选择图片`"
            :limit="4"
            :data="appQrcode"
            @done="chooseFile2"
            @del="onDeleteItem2"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="名称"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-input
            allow-clear
            placeholder="请输入应用名称"
            class="input-item"
            v-model:value="form.appName"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="状态"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <DictSelect
            dict-code="appstoreStatus"
            placeholder="请选择应用状态"
            class="input-item"
            v-model:value="form.appStatus"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="TenantId"
          :labelStyle="{ width: '200px', color: '#808080' }"
          ><a-input-number
            allow-clear
            placeholder="请输入租户ID"
            class="input-item"
            :maxlength="5"
            v-model:value="form.tenantCode"
        /></a-descriptions-item>
        <a-descriptions-item
          label="标识"
          :labelStyle="{ width: '200px', color: '#808080' }"
          ><a-input
            allow-clear
            :maxlength="16"
            class="input-item"
            placeholder="请输入应用标识(英文字母)"
            v-model:value="form.appCode"
            @change="changeAppCode"
        /></a-descriptions-item>
        <a-descriptions-item
          label="AppSecret"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <span>****</span>
        </a-descriptions-item>
        <a-descriptions-item
          label="所属企业"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <SelectCompany
            :placeholder="`所属企业`"
            class="input-item"
            v-model:value="form.companyName"
            @done="chooseCompanyName"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="项目域名"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-input
            allow-clear
            class="input-item"
            placeholder="请输入项目地址"
            v-model:value="form.appUrl"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="Git仓库地址"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-input
            allow-clear
            class="input-item"
            placeholder="请输入Git仓库地址"
            v-model:value="form.gitUrl"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="项目类型"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <DictSelect
            dict-code="appType"
            class="input-item"
            placeholder="请选择项目类型"
            v-model:value="form.appType"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="开发者"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <SelectCompany
            :placeholder="`开发者单位`"
            class="input-item"
            v-model:value="form.developer"
            @done="chooseDeveloper"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="是否作为案例展示"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-switch
            size="small"
            :checked="form.showCase"
            @change="updatShowCase"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="是否推荐到首页"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-switch
            size="small"
            :checked="form.showIndex"
            @change="updatShowIndex"
          />
        </a-descriptions-item>
        <a-descriptions-item
          label="描述"
          layout="vertical"
          :span="2"
          :labelStyle="{ width: '200px', color: '#808080' }"
        >
          <a-textarea
            :rows="4"
            :maxlength="200"
            class="ele-fluid"
            placeholder="请输入应用描述"
            v-model:value="form.comments"
          />
        </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, ipReg, isChinese, uuid } 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 { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { TOKEN_STORE_NAME } from '@/config/setting';
  import { FileRecord } from '@/api/system/file/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 当期时间
  // 已上传数据
  const logo = ref<ItemType[]>([]);
  const appQrcode = ref<ItemType[]>([]);
  const images = ref<ItemType[]>([]);
  // 日期范围选择
  const content = ref('');

  const token = localStorage.getItem(TOKEN_STORE_NAME);
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<App>({
    // 应用id
    appId: undefined,
    // 应用秘钥
    appSecret: '',
    enName: '',
    // 应用名称
    appName: '',
    // 上级id, 0是顶级
    parentId: undefined,
    // 应用编号
    appCode: '',
    // 应用图标
    appIcon: '',
    appQrcode: '',
    // 应用截图
    images: '',
    appType: undefined,
    appTypeMultiple: undefined,
    // 菜单类型
    menuType: undefined,
    // 应用地址
    appUrl: '',
    gitUrl: '',
    // 后台管理地址
    adminUrl: undefined,
    // 下载地址
    downUrl: undefined,
    serverUrl: undefined,
    callbackUrl: undefined,
    docsUrl: undefined,
    prototypeUrl: undefined,
    ipAddress: undefined,
    fileUrl: undefined,
    // 应用包名
    packageName: '',
    // 点击次数
    clicks: '',
    // 安装次数
    installs: '',
    // 项目介绍
    content: '',
    // 开发者(个人)
    developer: '',
    director: '',
    projectDirector: '',
    salesman: '',
    // 软件定价
    price: '',
    // 评分
    score: '',
    // 星级
    star: '',
    // 菜单组件地址
    component: '',
    // 菜单路由地址
    path: '',
    // 权限标识
    authority: '',
    // 打开位置
    target: '',
    // 是否隐藏, 0否, 1是(仅注册路由不显示在左侧菜单)
    hide: undefined,
    // 菜单侧栏选中的path
    active: '',
    // 其它路由元信息
    meta: '',
    // 版本
    edition: '',
    // 版本号
    version: '',
    // 是否已安装
    isUse: undefined,
    // 排序
    sortNumber: undefined,
    // 备注
    comments: undefined,
    tenantName: '',
    companyName: '',
    // 租户编号
    tenantCode: '',
    // 租户id
    tenantId: undefined,
    // 创建时间
    createTime: '',
    appStatus: '开发中',
    // 状态
    status: undefined,
    // 发布者
    userId: '',
    // 发布者昵称
    nickname: '',
    // 子菜单
    children: [],
    // 权限树回显选中状态, 0未选中, 1选中
    checked: false,
    //
    key: undefined,
    //
    value: undefined,
    //
    parentIds: [],
    //
    openType: undefined,
    //
    search: undefined,
    showCase: undefined,
    showIndex: undefined,
    recommend: undefined
  });

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

  // 表单验证规则
  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: '请选择项目类型'
      }
    ],
    ipAddress: [
      {
        pattern: ipReg,
        message: 'IP地址不合法',
        type: 'string'
      }
    ],
    appStatus: [
      {
        required: true,
        type: 'string',
        message: '请选择应用状态',
        trigger: 'blur'
      }
    ]
  });

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

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

  const chooseDeveloper = (data: Company) => {
    form.developer = data.companyName;
  };

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

  const updatShowIndex = () => {
    form.showIndex = !form.showIndex;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value,
          search: form.search ? 1 : 0,
          images: JSON.stringify(images.value)
          // appTypeMultiple: JSON.stringify(form.appTypeMultiple)
        };
        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 chooseFile = (data: FileRecord) => {
    logo.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.appIcon = data.path;
  };

  const onDeleteItem = (index: number) => {
    logo.value.splice(index, 1);
    form.appIcon = '';
  };
  const chooseFile2 = (data: FileRecord) => {
    appQrcode.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    const arr = appQrcode.value.map((d) => d.url);
    form.appQrcode = arr.join('|||');
  };

  const onDeleteItem2 = (index: number) => {
    appQrcode.value.splice(index, 1);
    form.appQrcode = '';
  };

  const reload = () => {
    loading.value = true;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        content.value = '';
        logo.value = [];
        images.value = [];
        appQrcode.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.appIcon) {
            logo.value.push({
              uid: 0,
              url: props.data.appIcon,
              status: 'done'
            });
          }
          if (props.data.appQrcode) {
            const split = props.data.appQrcode.split('|||');
            split.map((url) => {
              appQrcode.value.push({
                uid: uuid(),
                url: url,
                status: 'done'
              });
            });
            // appQrcode.value.push({
            //   uid: 0,
            //   url: props.data.appQrcode,
            //   status: 'done'
            // });
          }
          if (props.data.companyId) {
            console.log(props.data);
          }
          if (props.data.images) {
            const arr = JSON.parse(props.data.images);
            arr.map((d) => {
              images.value.push({
                uid: d.uid,
                url: d.url,
                status: 'done'
              });
            });
          }
          if (props.data.search) {
            form.search = props.data.search == 1 ? true : 0;
          }
          if (props.data.content) {
            content.value = props.data.content;
          }
          isUpdate.value = true;
          reload();
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less" scoped>
  .input-item {
    width: 300px;
  }
</style>
