<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑企业' : '添加企业'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <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-card title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <div class="upload-image">
                <ele-image-upload
                  v-model:value="images"
                  :item-style="{ width: '120px', height: '120px' }"
                  :limit="1"
                  @upload="onUpload"
                />
              </div>
              <a-form-item label="企业ID" name="companyId">
                {{ form.companyId }}
              </a-form-item>
              <a-form-item label="企业名称">
                {{ form.companyName }}
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="企业名称" name="companyName">
                <a-input
                  allow-clear
                  placeholder="请输入企业名称"
                  v-model:value="form.companyName"
                />
              </a-form-item>
              <a-form-item label="客户标识" name="companyCode">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入社会统一信用代码"
                  v-model:value="form.companyCode"
                />
              </a-form-item>
              <a-form-item label="所属区域" name="region">
                <regions-select
                  v-model:value="city"
                  valueField="label"
                  placeholder="请选择省市区"
                  class="ele-fluid"
                />
              </a-form-item>
              <a-form-item label="企业域名" name="domain">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请填写企业域名"
                  v-model:value="form.domain"
                />
              </a-form-item>
              <a-form-item label="联系电话" name="phone">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请填写联系电话"
                  v-model:value="form.phone"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="企业简称" name="shortName">
                <a-input
                  allow-clear
                  placeholder="请输入企业简称"
                  v-model:value="form.shortName"
                />
              </a-form-item>
              <a-form-item label="企业类型" name="companyType">
                <DictSelect
                  dict-code="CompanyType"
                  placeholder="请选择企业类型"
                  v-model:value="form.companyType"
                />
              </a-form-item>
              <a-form-item label="所属区域" name="region">
                <a-input-group compact>
                  <a-input
                    disabled
                    style="width: calc(100% - 32px)"
                    v-model:value="form.region"
                    placeholder="所属区域"
                    @search="onSearch"
                  />
                  <a-tooltip title="选择位置">
                    <a-button @click="openMapPicker">
                      <template #icon><EnvironmentOutlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-input-group>
              </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-col>
          </a-row>
        </a-card>
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="开发设置" :bordered="false">-->
<!--          <a-row :gutter="16">-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="企业标识" name="appCode">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入企业标识(英文字母)"-->
<!--                  v-model:value="form.appCode"-->
<!--                  @change="changeAppCode"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="企业包名" name="packageName">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入企业包名"-->
<!--                  v-model:value="form.packageName"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="IP白名单" name="ipAddress">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入IP白名单"-->
<!--                  v-model:value="form.ipAddress"-->
<!--                />-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="接口地址" name="serverUrl">-->
<!--                <DictSelect-->
<!--                  dict-code="ServerApi"-->
<!--                  placeholder="请选择管理地址"-->
<!--                  v-model:value="form.serverUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="文件服务器" name="fileUrl">-->
<!--                <DictSelect-->
<!--                  dict-code="FileUrl"-->
<!--                  placeholder="请选择文件服务器地址"-->
<!--                  v-model:value="form.fileUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="授权回调地址" name="callbackUrl">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入授权回调地址"-->
<!--                  v-model:value="form.callbackUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="代码仓库" name="gitUrl">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入git仓库地址"-->
<!--                  v-model:value="form.gitUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="允许被搜索" name="gitUrl">-->
<!--                <a-switch v-model:checked="form.search" />-->
<!--              </a-form-item>-->

<!--            </a-col>-->
<!--          </a-row>-->
<!--        </a-card>-->
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="成员管理" :bordered="false">-->
<!--          <div class="content">-->
<!--            <a-space-->
<!--              style="margin-bottom: 15px"-->
<!--            >-->
<!--              <SelectUser-->
<!--                :placeholder="`添加开发成员`"-->
<!--                @done="addAppDevUser"-->
<!--              />-->
<!--              <SelectUser-->
<!--                :placeholder="`添加体验成员`"-->
<!--                @done="addAppExpUser"-->
<!--              />-->
<!--            </a-space>-->
<!--            <table-->
<!--              class="ele-table ele-table-border ele-table-stripe ele-table-medium"-->
<!--            >-->
<!--              <thead>-->
<!--              <tr>-->
<!--                <th>角色</th>-->
<!--                <th>用户</th>-->
<!--                <th>邮箱</th>-->
<!--                <th>手机号码</th>-->
<!--                <th>加入时间</th>-->
<!--                <th>操作</th>-->
<!--              </tr>-->
<!--              </thead>-->
<!--              <tbody>-->
<!--              <tr v-for="user in appUsers">-->
<!--                <td>-->
<!--                  <a-tag color="green" v-if="user.role === 10">体验成员</a-tag>-->
<!--                  <a-tag color="orange" v-if="user.role === 20">开发成员</a-tag>-->
<!--                  <a-tag color="red" v-if="user.role === 30">管理员</a-tag>-->
<!--                </td>-->
<!--                <td>-->
<!--                  <a-avatar :src="user.avatar">-->
<!--                    <template #icon>-->
<!--                      <user-outlined />-->
<!--                    </template>-->
<!--                  </a-avatar>-->
<!--                  <span style="padding-left: 5px">{{ user.nickname }}</span>-->
<!--                </td>-->
<!--                <td>{{ user.email }}</td>-->
<!--                <td>{{ user.phone }}</td>-->
<!--                <td>{{ user.createTime }}</td>-->
<!--                <td>-->
<!--                  <div v-if="user.role !== 30">-->
<!--                    <a-->
<!--                      @click="removeUser(user)"-->
<!--                      v-if="user.status === 0"-->
<!--                    >-->
<!--                      移除-->
<!--                    </a>-->
<!--                    <a v-else>待确认</a>-->
<!--                  </div>-->
<!--                  <div v-else>-->
<!--                    <a>转让</a>-->
<!--                  </div>-->

<!--                </td>-->
<!--              </tr>-->
<!--              </tbody>-->
<!--            </table>-->
<!--          </div>-->
<!--        </a-card>-->
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="附件信息" :bordered="false">-->
<!--          <a-row :gutter="16">-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="原型图地址" name="prototypeUrl">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入原型图地址"-->
<!--                  v-model:value="form.prototypeUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="合同文件" name="parentId">-->
<!--                <a-upload-->
<!--                  v-model:file-list="file1"-->
<!--                  name="file"-->
<!--                  action="https://file.wsdns.cn/api/file/image"-->
<!--                  :headers="{ Authorization: token }"-->
<!--                  @change="onFile1"-->
<!--                >-->
<!--                  <a-button>-->
<!--                    <upload-outlined />-->
<!--                    上传-->
<!--                  </a-button>-->
<!--                </a-upload>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="项目需求文档" name="docsUrl">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入腾讯文档地址"-->
<!--                  v-model:value="form.docsUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="报价单" name="parentId">-->
<!--                <a-upload-->
<!--                  v-model:file-list="file2"-->
<!--                  name="file"-->
<!--                  action="https://file.wsdns.cn/api/file/image"-->
<!--                  :headers="{ Authorization: token }"-->
<!--                  @change="onFile2"-->
<!--                >-->
<!--                  <a-button>-->
<!--                    <upload-outlined />-->
<!--                    上传-->
<!--                  </a-button>-->
<!--                </a-upload>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col-->
<!--              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"-->
<!--            >-->
<!--              <a-form-item label="维护文档" name="docsUrl">-->
<!--                <a-input-->
<!--                  allow-clear-->
<!--                  placeholder="请输入腾讯文档地址"-->
<!--                  v-model:value="form.docsUrl"-->
<!--                />-->
<!--              </a-form-item>-->
<!--              <a-form-item label="其他" name="parentId">-->
<!--                <a-upload-->
<!--                  v-model:file-list="file3"-->
<!--                  name="file"-->
<!--                  action="https://file.wsdns.cn/api/file/image"-->
<!--                  :headers="{ Authorization: token }"-->
<!--                  @change="onFile3"-->
<!--                >-->
<!--                  <a-button>-->
<!--                    <upload-outlined />-->
<!--                    上传-->
<!--                  </a-button>-->
<!--                </a-upload>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--          </a-row>-->
<!--        </a-card>-->
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="开发资料" :bordered="false">-->
<!--          <template #extra><a-button type="link" @click="handleEditStatus">编辑</a-button></template>-->
<!--          &lt;!&ndash; 编辑器 &ndash;&gt;-->
<!--          <byte-md-editor-->
<!--            v-if="editStatus"-->
<!--            v-model:value="requirement"-->
<!--            placeholder="请输入您的内容，图片请直接粘贴"-->
<!--            :locale="zh_Hans"-->
<!--            mode="split"-->
<!--            :plugins="plugins"-->
<!--            height="500px"-->
<!--            :editorConfig="{ lineNumbers: true }"-->
<!--            @paste="onPaste"-->
<!--          />-->
<!--          &lt;!&ndash; 编辑器 &ndash;&gt;-->
<!--          <byte-md-viewer v-else :value="requirement" :plugins="plugins" />-->
<!--        </a-card>-->
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="企业介绍" :bordered="false">-->
<!--          <template #extra><a-button type="link" @click="handleEditStatus">编辑</a-button></template>-->
<!--          &lt;!&ndash; 编辑器 &ndash;&gt;-->
<!--          <byte-md-editor-->
<!--            v-if="editStatus"-->
<!--            v-model:value="content"-->
<!--            placeholder="请输入您的内容，图片请直接粘贴"-->
<!--            :locale="zh_Hans"-->
<!--            mode="split"-->
<!--            :plugins="plugins"-->
<!--            height="500px"-->
<!--            :editorConfig="{ lineNumbers: true }"-->
<!--            @paste="onPaste"-->
<!--          />-->
<!--          &lt;!&ndash; 编辑器 &ndash;&gt;-->
<!--          <byte-md-viewer v-else :value="content" :plugins="plugins" />-->
<!--        </a-card>-->
<!--        <a-divider style="height: 8px" />-->
<!--        <a-card title="企业截图" :bordered="false">-->
<!--          <template #extra><a-button type="link" @click="handleEditStatus">上传</a-button></template>-->
<!--        </a-card>-->
      </a-form>
      <!-- 地图位置选择弹窗 -->
      <ele-map-picker
        :need-city="true"
        :dark-mode="darkMode"
        v-model:visible="showMap"
        :center="[108.374959, 22.767024]"
        :search-type="1"
        :zoom="12"
        @done="onDone"
      />
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, createVNode, computed } from 'vue';
import { Form, message } from 'ant-design-vue';
import { assignObject, ipReg, toDateString } from "ele-admin-pro";
import { useUserStore } from '@/store/modules/user';
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';
// 中文语言文件
import zh_Hans from 'bytemd/locales/zh_Hans.json';
// 链接、删除线、复选框、表格等的插件
// 插件的中文语言文件
import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
import 'bytemd/dist/index.min.css';
import 'github-markdown-css/github-markdown-light.css';
import { Modal } from 'ant-design-vue';
// import TinymceEditor from '@/components/TinymceEditor/index.vue';
import highlight from '@bytemd/plugin-highlight';
// 中文语言文件
import gfm from '@bytemd/plugin-gfm';
// // 预览界面的样式，这里用的 github 的 markdown 主题
import 'github-markdown-css/github-markdown-light.css';
import {
  EyeOutlined,
  EyeInvisibleOutlined,
  EnvironmentOutlined
} from '@ant-design/icons-vue';
import { UploadOutlined } from '@/layout/menu-icons';
import { FormInstance } 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 DictSelect from '@/views/search/components/dict-select.vue';
import { User } from '@/api/system/user/model';
import { uploadFile } from "@/api/system/file";
import { FILE_SERVER, FILE_THUMBNAIL, TOKEN_STORE_NAME } from "@/config/setting";
import { listAppUser, addAppUser, removeAppUser } from "@/api/oa/app/user";
import { AppUser } from '@/api/oa/app/user/model'
import { updateCompany, addCompany } from "@/api/system/company";
import { CenterPoint } from "ele-admin-pro/es/ele-map-picker/types";

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
const { darkMode } = storeToRefs(themeStore);
const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Company | null;
}>();

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

// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 当期时间
const dayTime = toDateString(new Date());
// 已上传数据
const images = ref<ItemType[]>([]);
const appUsers = ref<AppUser[]>([]);
const selectUser = ref<string>();
const editStatus = ref(false);
// 类型 single|multiple
// const type = ref<string>('single');
// 日期范围选择
const dateRange = ref<[string, string]>(['', '']);
const content = ref('');
const requirement = ref('');
// 插件
const plugins = ref([
  gfm({
    locale: zh_HansGfm
  }),
  highlight()
]);

// 穿梭框数据
const breakfast = ref<any[]>();
const targetKeys1 = ref<any[]>([]);
const selectedKeys1 = ref<any[]>();
const lunch = ref<any[]>();
const targetKeys2 = ref<any[]>([]);
const selectedKeys2 = ref<any[]>();
const dinner = ref<any[]>();
const targetKeys3 = ref<any[]>([]);
const selectedKeys3 = ref<any[]>();
const selectedGoodsIds = ref<any[]>([]);
const showAddUserForm = ref(false);
// 是否显示地图选择弹窗
const showMap = ref(false);
// 省市区
const city = ref<string[]>([]);
const token = localStorage.getItem(TOKEN_STORE_NAME);
const formRef = ref<FormInstance | null>(null);

// 文件模型
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: Response;
  thumbUrl?: string;
  downloadUrl?: string;
  url: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}
// 文件上传
const file1 = ref<FileItem[]>();
const file2 = ref<FileItem[]>();
const file3 = ref<FileItem[]>();

// 用户信息
const form = reactive<Company>({
  companyId: undefined,
  companyName: '',
  companyCode: '',
  shortName: '',
  phone: '',
  companyLogo: undefined,
  domain: '',
  sortNumber: undefined,
  comments: '',
  tenantName: '',
  tenantId: undefined,
  createTime: '',
  status: undefined,
  userId: undefined
});

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

// 表单验证规则
const rules = reactive({
  companyName: [
    {
      required: true,
      type: 'string',
      message: '请输入企业名称',
      trigger: 'blur'
    }
  ],
  // appCode: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请输入企业标识(英文字母)',
  //     trigger: 'blur'
  //   }
  // ],
  // progress: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请选择跟进状态',
  //     trigger: 'blur'
  //   }
  // ],
  // securityStatus: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请选择安全状态',
  //     trigger: 'blur'
  //   }
  // ],
  // companyName: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请选择租赁单位',
  //     trigger: 'blur'
  //   }
  // ],
  // appRegion: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请输入企业地址',
  //     trigger: 'blur'
  //   }
  // ]
});

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

const addUser = () => {
  showAddUserForm.value = true;
};

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

// 添加开发成员
const addAppDevUser = (data: User) => {
  addAppUser({
    userId: data.userId,
    appId: props.data?.appId,
    role: 20
  }).then((msg) => {
    message.success(msg);
    reload();
  })
    .catch((e) => {
      message.error(e.message);
    });
}

// 添加体验成员
const addAppExpUser = (data: User) => {
  addAppUser({
    userId: data.userId,
    appId: props.data?.appId,
    role: 10
  }).then((msg) => {
    message.success(msg);
    reload();
  })
    .catch((e) => {
      message.error(e.message);
    });
}

// 移除成员
const removeUser = (data: AppUser) => {
  removeAppUser(data.appUserId)
    .then((msg) => {
      message.success(msg);
      reload();
    })
    .catch((e) => {
      message.error(e.message);
    });
};


// 选择地区
const onChangeRegion = (value) => {
  form.province = value[0];
  form.city = value[1];
  form.region = value[2];
};

/* 地图选择后回调 */
const onDone = (location: CenterPoint) => {
  console.log(location);
  city.value = [
    `${location.city?.province}`,
    `${location.city?.city}`,
    `${location.city?.district}`
  ];
  form.province = `${location.city?.province}`;
  form.city = `${location.city?.city}`;
  form.region = `${location.city?.district}`;
  form.address = `${location.address}`;
  form.latitude = `${location.lat}`;
  form.longitude = `${location.lng}`;
  showMap.value = false;
};

const handleEditStatus = () => {
  editStatus.value = !editStatus.value;
}

// const chooseCompanyName = (data: Company) => {
//   form.companyName = data.companyName;
// };

const chooseDismantlingCompany = (data: Company) => {
  form.dismantlingCompany = data.companyName;
};

const chooseDirector = (data: User) => {
  form.director = data.nickname;
};

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

const chooseSalesman = (data: User) => {
  form.salesman = data.nickname;
};

const changeAppCode = (e) => {
  form.packageName = `com.gxwebsoft.${form.appCode}`;
  form.appUrl = `https://apps.gxwebsoft.com/${form.appCode}`;
}

/* 打开位置选择 */
const openMapPicker = () => {
  showMap.value = true;
};

const onFile1 = (info: FileInfo) => {
  let resFileList = [...info.fileList];
  file1.value = resFileList.map((file) => {
    if (file.response) {
      file.url = file.response.url;
    }
    return file;
  });
  form.file1 = JSON.stringify(file1.value);
};
const onFile2 = (info: FileInfo) => {
  let resFileList = [...info.fileList];
  file2.value = resFileList.map((file) => {
    if (file.response) {
      file.url = file.response.url;
    }
    return file;
  });
  form.file2 = JSON.stringify(file2.value);
};
const onFile3 = (info: FileInfo) => {
  let resFileList = [...info.fileList];
  file3.value = resFileList.map((file) => {
    if (file.response) {
      file.url = file.response.url;
    }
    return file;
  });
  form.file3 = JSON.stringify(file3.value);
};

const config = ref({
  height: 500,
  images_upload_handler: (blobInfo, success, error) => {
    const file = blobInfo.blob();
    // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
    const formData = new FormData();
    formData.append('file', file, file.name);
    uploadFile(<File>file)
      .then((result) => {
        if (result.length) {
          if (file.size / 1024 / 1024 > 2) {
            error('图片大小不能超过 2MB');
          }
          success(FILE_SERVER + result.path);
        } else {
          error('上传失败');
        }
      })
      .catch((e) => {
        message.error(e.message);
      });
  }
});

// 上传文件
const onUpload = (item) => {
  const { file } = item;
  images.value = [];
  uploadFile(file)
    .then((data) => {
      images.value.push({
        uid: data.id,
        url: FILE_THUMBNAIL + data.path,
        status: 'done'
      });
      form.companyLogo = data.path;
      message.success('上传成功');
    })
    .catch((e) => {
      message.error(e.message);
    });
};

/* 粘贴图片上传服务器并插入编辑器 */
const onPaste = (e) => {
  console.log(e);
  const items = (e.clipboardData || e.originalEvent.clipboardData).items;
  console.log(items);
  let hasFile = false;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      let file = items[i].getAsFile();
      const item: ItemType = {
        file,
        uid: (file as any).lastModified,
        name: file.name
      };
      uploadFile(<File>item.file)
        .then((result) => {
          const addPath = '!['+result.name+']('+FILE_SERVER + result.path+')\n\r';
          content.value = content.value + addPath
        })
        .catch((e) => {
          message.error(e.message);
        });
      hasFile = true;
    }
  }
  if (hasFile) {
    e.preventDefault();
  }
}

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      const formData = {
        ...form,
        content: content.value
      };
      const saveOrUpdate = isUpdate.value ? updateCompany : addCompany;
      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;
  listAppUser({appId:props.data?.appId}).then(data => {
    appUsers.value = data
  })
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      content.value = '';
      requirement.value = '';
      if (props.data) {
        assignObject(form, props.data);
        images.value = [];
        if(props.data.companyLogo){
          images.value.push({
            uid: 0,
            url: FILE_THUMBNAIL + props.data.companyLogo,
            status: 'done'
          });
        }

        if (props.data.content) {
          content.value = props.data.content;
        }
        if (props.data.requirement){
          requirement.value = props.data.requirement;
        }
        if (props.data.file1) {
          file1.value = JSON.parse(props.data.file1);
        }
        if (props.data.file2) {
          file2.value = JSON.parse(props.data.file2);
        }
        if (props.data.file3) {
          file3.value = JSON.parse(props.data.file3);
        }
        isUpdate.value = true;
        reload();
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  }
);
</script>
<style lang="less"></style>

<style lang="less">
.tab-pane {
  min-height: 300px;
}

.ml-10 {
  margin-left: 5px;
}

.upload-text {
  margin-right: 70px;
}

.upload-image {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}
</style>
