<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="60%"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑企业' : '添加企业'"
    :body-style="{ paddingBottom: '28px', backgroundColor: '#F0F2F5FF' }"
    @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: 20 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-card title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 11, 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="companyType">
                <DictSelect
                  dict-code="CompanyType"
                  placeholder="请选择企业类型"
                  v-model:value="form.companyType"
                />
              </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="legal">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请填写法定代表人"
                  v-model:value="form.businessEntity"
                />
              </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-form-item label="座机电话" name="tel">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请填写座机电话"
                  v-model:value="form.tel"
                />
              </a-form-item>
              <a-form-item label="电子邮箱" name="email">
                <a-input
                  allow-clear
                  placeholder="请填写电子邮箱"
                  v-model:value="form.email"
                />
              </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="LOGO" name="logo">
                <SelectFile
                  :placeholder="`请选择图片`"
                  :limit="1"
                  :data="images"
                  @done="chooseFile"
                  @del="onDeleteItem"
                />
<!--                  <ele-image-upload-->
<!--                    v-model:value="images"-->
<!--                    :accept="'image/png,image/jpeg,image/webp'"-->
<!--                    :item-style="{ width: '120px', height: '120px' }"-->
<!--                    :limit="1"-->
<!--                    @upload="onUpload"-->
<!--                  />-->
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 11, 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="industry">
                <industry-select
                  v-model:value="industry"
                  valueField="label"
                  placeholder="请选择所属行业"
                  class="ele-fluid"
                />
              </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="所属区域"
                  />
                  <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="region">
                <regions-select
                  v-model:value="city"
                  valueField="label"
                  placeholder="请选择省市区"
                  class="ele-fluid"
                />
              </a-form-item>
              <a-form-item label="办公地址" name="address">
                <a-input
                  allow-clear
                  placeholder="请输入企业办公地址"
                  v-model:value="form.address"
                />
              </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-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"
      />
  </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/oa/company/model';
import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
import { User } from '@/api/system/user/model';
import { uploadFile, uploadOss } 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/oa/company";
import { CenterPoint } from "ele-admin-pro/es/ele-map-picker/types";
import {FileRecord} from "@/api/system/file/model";

// 是否是修改
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: '',
  businessEntity: '',
  companyType: undefined,
  industryParent: '',
  industryChild: '',
  shortName: '',
  tel: '',
  phone: '',
  email: '',
  companyLogo: undefined,
  domain: '',
  sortNumber: undefined,
  comments: '',
  tenantName: '',
  province: '',
  city: '',
  region: '',
  latitude: '',
  longitude: '',
  address: '',
  nickname: '',
  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'
    }
  ],
  companyType: [
    {
      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 chooseUser = (data: User) => {
  form.nickname = data.nickname
  form.userId = data.userId
}

// 移除成员
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 = [];
  uploadOss(file)
    .then((data) => {
      images.value.push({
        uid: data.id,
        url: data.url,
        status: 'done'
      });
      form.companyLogo = data.url;
      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 chooseFile = (data: FileRecord) => {
  images.value.push({
    uid: data.id,
    url: data.path,
    status: 'done'
  });
  form.companyLogo = data.path;
}

const onDeleteItem = (index: number) => {
  images.value.splice(index,1)
  form.companyLogo = '';
}

/* 保存编辑 */
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 industry = ref<string[]>([
  String(form.industryParent),
  String(form.industryChild)
]);

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: props.data.companyLogo,
            status: 'done'
          });
        }
        industry.value[0] = String(props.data.industryParent);
        industry.value[1] = String(props.data.industryChild);

        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);
        }
        // 所在地区
        if(props.data.province){
          city.value.push(props.data.province)
        }
        if(props.data.city){
          city.value.push(props.data.city)
        }
        if(props.data.region){
          city.value.push(props.data.region)
        }
        isUpdate.value = true;
        reload();
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  }
);
</script>
<style lang="less">
.upload-image {
  display: flex;
  justify-content: center;
}
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
</style>
