<template>
  <el-dialog v-model="visible" :width="width" append-to-body draggable show-close :close-on-click-modal="false">
    <template #header>
      <div class="dialog-title-container">
        <span class="title-label" style="color: #fff">
          <el-icon>
            <Document />
          </el-icon>
          文件</span>
      </div>
    </template>
    <div class="form-btns-container">
      <el-button type="primary" size="small" icon="Finished" @click="handleSave">
        保存</el-button>
    </div>
    <div v-loading="loading">
      <div style="padding: 8px 24px 16px 24px">
        <el-form size="small" label-width="80px" :model="form" :rules="formRules" ref="uploadForm">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="文件类型" prop="type">
                <el-select v-model="form.type" style="width: 100%">
                  <el-option v-for="item in fileTypes" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="companyId">
                <el-select v-model="form.companyId" style="width: 100%" @focus="focusCompanySelect">
                  <el-option v-for="item in companyList" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择文件" prop="files">
                <el-upload v-if="visible" action="#" :http-request="upload" :before-upload="handleBeforeUpload" :with-credentials="true"
                  :before-remove="removeFile" v-model:file-list="fileList" :on-exceed="onExceed" :on-error="onUploadError" :accept="acceptType"
                  :show-file-list="true" multiple :limit="5" drag style="width: 100%;">
                  <!-- <el-button size="small" type="primary" icon="Upload">上传文件</el-button> -->
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    上传文件
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">
                      单次最多上传5个文件，每个文件最大15M
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog v-model="visibleCompany" width="660px" append-to-body draggable show-close :close-on-click-modal="false">
      <template #header>
        <div class="dialog-title-container">
          <span class="title-label" style="color: #fff">
            <el-icon>
              <Document />
            </el-icon>
            企业</span>
        </div>
      </template>
      <!-- <div class="form-btns-container">
        <el-button type="primary" size="small" icon="Finished" @click="handleSave">
          保存</el-button>
      </div> -->
      <div v-loading="loadingCompany">
        <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="客户名称：">
            <el-input v-model.trim="queryParams.name" size="small" type="text" placeholder="客户名称" :clearable="true"
              style="width: 130px" />
          </el-form-item>
          <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" size="small">搜索</el-button>
        </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%">
          <el-table-column prop="name" label="名称" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleSelect(scope.row)">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getCompanyList" />
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script setup>
  import { reactive } from "vue";
  import { UploadFilled } from '@element-plus/icons-vue'

  import {
    addFileInfos,
  } from "@/api/business/fileUpload";
  import { uploadFile } from "@/api/tool/file";
  import { listCompany } from "@/api/business/crm/company";
  const { proxy } = getCurrentInstance();
  const loading = ref(false);
  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
    width: {
      type: String,
      default: "800px",
    },
    fileTypes: {
      type: Array,
      default: () => []
    }
  });
  const { getList, width, fileTypes } = toRefs(props);
  const srcList = ref([]);
  const visibleCompany = ref(false);
  const loadingCompany = ref(false);
    /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time",
    // principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
    name: ''
  });
  const companyList = ref([])
  const data = reactive({
    visible: false,
    list: [],
    total: 0,
    query: {
      name: "",
      total: 0,
      pageSize: 15,
      pageNum: 1,
    },
    // files: [],
    months: [],
    form: {
      files: []
    },
    selection: [],
    baseUrl: import.meta.env.VITE_APP_BASE_API,
    options: {},
    formRules: {
      type: [
        { required: true, message: '请选择文件类型', trigger: 'change' }
      ],
      companyId: [
        { required: true, message: '请选择公司', trigger: 'change' }
      ],
      files: [
        { required: true, message: '请上传文件', validator: validateFiles }
      ],
    },
    fileMap: {},
    fileList: [],
    acceptType: ".bmp,.gif,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.html,.htm,.txt,.rar,.zip,.gz,.bz2,.mp4,.avi,.rmvb,.pdf"
  });
  const {
    visible,
    list,
    query,
    selection,
    baseUrl,
    options,
    total,
    // files,
    form,
    months,
    formRules,
    fileMap,
    fileList,
    acceptType
  } = toRefs(data);

  function onUploadError(err) {
    console.log('onUploadError', err)
  }

  function onExceed(files) {
    console.log( fileList.value)
    if(files.length + fileList.value.length> 5) {
      proxy.$modal.msgError("单次最多上传5个文件")
      return  false
    }
    return true
  }

  function validateFiles(rule, value, callback) {
    if (!form.value.files || form.value.files.length == 0) {
      callback(new Error('请上传文件'))
    } else {
      callback()
    }
  } 

  function handleSelect(row) {
    form.value.companyId = row.id
    companyList.value.push(row)
    visibleCompany.value = false
  }

  function open(arg) {
    visible.value = true;
    form.value = {
      files: []
    }
    fileMap.value = {}
    fileList.value = []
    getCompanyList()
  }
    /** 查询company列表 */
  function getCompanyList() {
    loadingCompany.value = true;
    listCompany(queryParams.value).then((response) => {
      list.value = response.rows.map((l) => ({ ...l }));
      // prev.value = proxy.deepClone(response.rows);
      total.value = response.total;
      loadingCompany.value = false;
    });
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getCompanyList();
  }
  /**
   * 对话框关闭 事件
   */
  function close() {
    visible.value = false;
  }
  function handleImageView(fileUrl) {
    window.open(`${baseUrl.value}${fileUrl}`);
  }
  /**
   * 加载数据
   */
  const loadData = async () => {
    // getCompanyList()
    const res = await listFiles(form.value);
    // files.value = res.data.files;
    months.value = res.data.months;
    form.value.isFinished = res.data.finished.isFinished;
    srcList.value = files.value.map((v) => baseUrl.value + v.fileUrl);
    loading.value = false;
 
  };
  /**
   * 列表checkbox列选择 事件
   */
  function handleSelectionChange(selection) {
    selection.value = selection;
  }
  /**
   * 搜索 事件
   */
  function handleSearch() {
    loadData();
  }
  function openFile(attach) {
    window.open(`${baseUrl.value}/${attach.fileUrl}`, attach.fileName);
  }

  function upload(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.originalFilename;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;

        form.value.files.push(file)
        fileMap.value[param.file.uid] = file.fileUrl
        if(fileList.value.findIndex(f => f.uid == param.file.uid) < 0) {
          console.log('fileList', fileList)
          console.log('param.file.uid', param.file.uid)
          fileList.value.push(param.file)
        }
      } else {
        const index = fileList.value.findIndex(f => f.uid == param.file.uid)
        fileList.value.splice(index, 1);
      }
    }).catch(e => {
      const index = fileList.value.findIndex(f => f.uid == param.file.uid)
      fileList.value.splice(index, 1);
    });
  }

  const types = acceptType.value.split(',')
  function handleBeforeUpload(file) {
    const fileExtension = file.name.split('.').pop().toLowerCase();
    if(!types.includes('.'+fileExtension)) {
      proxy.$modal.msgError("文件格式不正确");
      return false;
    }
    
    console.log('handleBeforeUpload',file)
    if(file.size > 15 * 1024 * 1024) {
      proxy.$modal.msgError("文件大小不能超过15M");
      return false;
    }
    return true;
  }

  function removeFile(file) {
    const fileUrl = fileMap.value[file.uid]
    form.value.files = form.value.files.filter(f => f.fileUrl != fileUrl)
    // fileMap.value.value.delete(file.uid)
    delete fileMap[file.uid]
    return true
  }

  function deleteHandle(index) {
    proxy.$modal
      .confirm("确定删除?")
      .then(() => {
        files.value.splice(index, 1);
        srcList.value = files.value.map((v) => baseUrl.value + v.fileUrl);
      })
      .catch(() => {
        proxy.$modal.msg("已取消删除");
      });
  }

  function handleSave() {
    proxy.$refs["uploadForm"].validate((valid) => {
      if (valid) {
        const file = {
          companyId: form.value.companyId,
          type: form.value.type,
          files: form.value.files,
        };
        addFileInfos(file).then((res) => {
          getList.value();
          close();
        });
      }
    });
    
  }
  function focusCompanySelect() {
    visibleCompany.value = true
  }

  defineExpose({
    open,
  });
</script>