<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditCompanyInfo"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="CompanyInfo.companyName">
              <el-input
                class="input-item"
                v-model="formData.CompanyInfo.companyName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址" prop="CompanyInfo.address">
              <el-input
                class="input-item"
                v-model="formData.CompanyInfo.address"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成立日期" prop="CompanyInfo.establishDate">
              <el-date-picker
                class="input-item"
                v-model="formData.CompanyInfo.establishDate"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="CompanyInfo.telephone">
              <el-input
                class="input-item"
                v-model="formData.CompanyInfo.telephone"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司网站链接" prop="CompanyInfo.website">
              <el-input
                class="input-item"
                v-model="formData.CompanyInfo.website"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司类型" prop="CompanyInfo.companyType">
              <el-select
                class="input-item"
                v-model="formData.CompanyInfo.companyType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="companyTypeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in companyTypeWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司邮箱" prop="CompanyInfo.email">
              <el-input
                class="input-item"
                v-model="formData.CompanyInfo.email"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司图片" prop="CompanyInfo.companyUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/companyInfo/upload')"
                :data="{fieldName: 'companyUrl', asImage: true}"
                :on-success="onCompanyUrlUploadSuccess"
                :on-remove="onCompanyUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="companyUrlWidgetFileList && companyUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="companyUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onCompanyUrlRemoveFile(null, null)" />
              </div>
              <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="富文本内容" class="rich-input" prop="CompanyInfo.companyContent.content">
              <rich-editor
                ref="content"
                class="input-item"
                v-model="formData.CompanyInfo.companyContent.content"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onSubmitCompanyInfoClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditCompanyInfo',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode } from '@/common/utils';
import { CompanyContentData } from '@/api/generated/companyContentController';
import { CompanyInfoData } from '@/api/generated/companyInfoController';
import { CompanyContentController, CompanyInfoController } from '@/api/generated';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const formEditCompanyInfo = ref();
// 表单数据定义
type FormEditCompanyInfoData = {
  CompanyInfo: CompanyInfoData;
};
// 表单数据
const formData = reactive<FormEditCompanyInfoData>({
  CompanyInfo: {
    // 主键id
    id: undefined,
    // 公司名称
    companyName: undefined,
    // 公司地址
    address: undefined,
    // 成立日期
    establishDate: undefined,
    // 联系电话
    telephone: undefined,
    // 公司网站链接
    website: undefined,
    // 公司类型
    companyType: undefined,
    // 公司邮箱
    email: undefined,
    // 公司图片上传地址
    companyUrl: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    companyContent: {
      // 主键id
      id: undefined,
      // 富文本内容
      content: undefined,
      // 关联表id
      associationId: undefined,
      // 创建用户
      createUserId: undefined,
      // 创建时间
      createTime: undefined,
      // 更新用户
      updateUserId: undefined,
      // 更新时间
      updateTime: undefined,
      // 删除标记(1: 正常 -1: 已删除)
      dataState: undefined,
    },
  },
},
);
// 表单验证规则
const rules = reactive({
  'CompanyInfo.email': [
    {required: true, message: '请输入公司邮箱', trigger: 'blur'}
  ],
  'CompanyInfo.companyUrl': [
  ],
  'CompanyInfo.website': [
  ],
  'CompanyInfo.companyType': [
    {required: true, message: '请输入公司类型', trigger: 'blur'}
  ],
  'CompanyInfo.establishDate': [
  ],
  'CompanyInfo.telephone': [
    {required: true, message: '请输入联系电话', trigger: 'blur'}
  ],
  'CompanyInfo.companyName': [
    {required: true, message: '请输入公司名称', trigger: 'blur'}
  ],
  'CompanyInfo.address': [
    {required: true, message: '请输入公司地址', trigger: 'blur'}
  ],
  'CompanyInfo.companyContent.content': [
  ],
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadCompanyInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.CompanyInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    CompanyInfoController.view(params).then(res => {
      formData.CompanyInfo = { ...res.data };
      if (formData.CompanyInfo.companyContent == null) {
        formData.CompanyInfo.companyContent = {
          id: undefined,
          content: undefined,
          associationId: undefined,
          createUserId: undefined,
          createTime: undefined,
          updateUserId: undefined,
          updateTime: undefined,
          dataState: undefined
        };
      }
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 公司类型下拉数据获取函数
 */
const loadCompanyTypeDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.CompanyType.getList(),
  });
};
// 公司类型配置参数
const companyTypeOptions: DropdownOptions<DictData> = {
  loadData: loadCompanyTypeDropdownList,
  isTree: false,
};
// 公司类型下拉组件
const companyTypeWidget = useDropdown(companyTypeOptions);
const { dropdownList: companyTypeWidgetDropdownList } = companyTypeWidget
/**
 * 公司图片上传成功
 */
const onCompanyUrlUploadSuccess = (
  response: ANY_OBJECT,
  file: UploadFile,
  fileList: UploadFile[],
) => {
  if (response.success) {
    file.downloadUri = response.data.downloadUri;
    file.filename = response.data.filename;
    file.uploadPath = response.data.uploadPath;
    file.url = URL.createObjectURL(file.raw);
    companyUrlWidget.onFileChange(file, fileList);
    formData.CompanyInfo.companyUrl = fileListToJson(companyUrlWidgetFileList);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除公司图片
 */
const onCompanyUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  companyUrlWidget.onFileChange(file, fileList);
  formData.CompanyInfo.companyUrl = fileListToJson(companyUrlWidgetFileList);
};
// 公司图片上传文件组件
const companyUrlWidget = useUploadWidget(1);
const { fileList: companyUrlWidgetFileList, maxCount: companyUrlWidgetMaxCount } = companyUrlWidget;
const content = ref();
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditCompanyInfo = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditCompanyInfo = () => {
  refreshFormEditCompanyInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditCompanyInfo();
};
/**
 * 保存
 */
const onSubmitCompanyInfoClick = () => {
  // 更新富文本字段值
  formData.CompanyInfo.companyContent.content = content.value?.getHtml();
  formEditCompanyInfo.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.CompanyInfo
      };
    formData.companyTypeDictMap = findItemFromList(companyTypeWidgetDropdownList, formData.companyType, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      companyContentDto: formData.CompanyInfo.companyContent,
      companyInfoDto: {
        id: formData.CompanyInfo.id,
        companyName: formData.CompanyInfo.companyName,
        address: formData.CompanyInfo.address,
        establishDate: formData.CompanyInfo.establishDate,
        telephone: formData.CompanyInfo.telephone,
        website: formData.CompanyInfo.website,
        companyType: formData.CompanyInfo.companyType,
        email: formData.CompanyInfo.email,
        companyUrl: formData.CompanyInfo.companyUrl,
        createUserId: formData.CompanyInfo.createUserId,
        createTime: formData.CompanyInfo.createTime,
        updateUserId: formData.CompanyInfo.updateUserId,
        updateTime: formData.CompanyInfo.updateTime,
      }
    };

    let httpCall = isEdit.value ? CompanyInfoController.update : CompanyInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadCompanyInfoData().then(res => {
    companyTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let companyUrlDownloadParams = {
      id: formData.CompanyInfo.id,
      fieldName: 'companyUrl',
      asImage: true
    };
    companyUrlWidgetFileList.value = parseUploadData(formData.CompanyInfo.companyUrl, companyUrlDownloadParams);
    if (isEdit.value) refreshFormEditCompanyInfo();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

onMounted(() => {
  formInit();
});
</script>
