<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>
        <!-- <el-icon @click="close">
          <Close />
        </el-icon> -->
      </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">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="客户名称">
                <div>{{ form.companyName }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账期">
                <el-select v-model="form.currentMonth" style="width: 100%" @change="changeMonthHandle">
                  <el-option v-for="item in months" :key="item.id" :label="`${item.year}-${item.month}`"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传完成">
                <el-checkbox v-model="form.isFinished" :true-label="1" :false-label="0" />
              </el-form-item>
            </el-col>
            <el-col v-if="form.isFinished === 0" :span="12">
              <!-- <el-form-item label="" required> -->
              <el-upload action="#" :http-request="upload" :before-upload="handleBeforeUpload" :with-credentials="true"
                :show-file-list="false" accept=".png, .jpg, .jpeg, .gif" multiple>
                <el-button size="small" type="primary" icon="Upload">上传文件</el-button>
              </el-upload>
              <!-- </el-form-item> -->
            </el-col>
            <el-col :span="24">
              <el-row :gutter="10">
                <el-col v-if="files.length === 0">
                  <el-empty description="没有数据" />
                </el-col>
                <el-col v-for="(o, index) in files" :key="o.UUID" :span="8"
                  style="margin-bottom: 10px; position: relative">
                  <el-card :body-style="{ padding: '0px' }">
                    <!-- <img :src="`${baseUrl}${o.fileUrl}`" class="image" style="max-width: 100%; height: 200px" @click="handleImageView(o.fileUrl)" /> -->
                    <el-image :src="`${baseUrl}${o.fileUrl}`" class="image" style="max-width: 100%; height: 200px"
                      :preview-teleported="true" fit="contain" :preview-src-list="srcList" :initial-index="index"
                      @click="vbs(baseUrl + o.fileUrl)" />
                    <div style="padding: 14px">
                      <!-- <span>好吃的汉堡</span> -->
                      <div class="bottom clearfix">
                        <el-form-item label="票据类型" prop="typeId">
                          <el-select v-model="o.typeId">
                            <el-option v-for="i in ticket_type" :key="i.value" :value="i.value" :label="i.label" />
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                    <el-button v-if="form.isFinished === 0" circle size="small" type="danger" icon="Close"
                      style="position: absolute; top: 5px; right: 10px" @click="deleteHandle(index)" />
                  </el-card>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
  import { reactive } from "vue";
  import {
    listFiles,
    saveTickets,
  } from "@/api/business/production/archiveTicket";
  import { uploadFile } from "@/api/tool/file";
  const { proxy } = getCurrentInstance();
  const { ticket_type } = proxy.useDict("ticket_type");
  const loading = ref(false);
  const formRules = ref({
    typeId: [
      { required: true, message: '请选择票据类型', trigger: 'change' }
    ]
  });
  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
    width: {
      type: String,
      default: "800px",
    },
  });
  const { getList, width } = toRefs(props);
  const srcList = ref([]);
  // import api from '@/api/biz/fileStorage'
  const data = reactive({
    visible: false,
    list: [],
    total: 0,
    query: {
      name: "",
      total: 0,
      pageSize: 15,
      pageNum: 1,
    },
    files: [],
    months: [],
    form: {},
    selection: [],
    baseUrl: import.meta.env.VITE_APP_BASE_API,
    options: {},
  });
  const {
    visible,
    list,
    query,
    selection,
    baseUrl,
    options,
    total,
    files,
    form,
    months,
  } = toRefs(data);

  function open(arg) {
    visible.value = true;
    loading.value = true;
    form.value = arg;
    form.value.month = proxy.moment().subtract(1, "month").format("MM")
    form.value.currentMonth = `${form.value.year}-${form.value.month}`;
    options.value = arg;
    loadData();
  }
  /**
   * 对话框关闭 事件
   */
  function close() {
    visible.value = false;
  }
  function handleImageView(fileUrl) {
    window.open(`${baseUrl.value}${fileUrl}`);
    // currentFileList.value = [`${baseUrl.value}${fileUrl}`];
    // showViewer.value = true;
  }
  /**
   * 加载数据
   */
  const loadData = async () => {
    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.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        files.value.push(file);
        srcList.value = files.value.map((v) => baseUrl.value + v.fileUrl);
        console.log(srcList.value, 2222);
      }
    });
  }

  function changeMonthHandle(item) {
    loading.value = true;
    const index = months.value.findIndex((v) => v.id === item);
    if (index >= 0) {
      const moment =
        months.value.length > 0
          ? proxy.moment(
            `${months.value[index].year}-${months.value[index].month}`,
            "YYYY-MM"
          )
          : null;
      // console.log(months.value)
      form.value.year =
        moment != null ? proxy.moment(moment).format("YYYY") : null;
      form.value.month =
        moment != null ? proxy.moment(moment).format("MM") : null;
    } else {
      form.value.checkoutId = months.value.length > 0 ? months.value[0].id : 0;
      const moment =
        months.value.length > 0
          ? proxy.moment(
            `${months.value[0].year}-${months.value[0].month}`,
            "YYYY-MM"
          )
          : null;
      // console.log(months.value)
      form.value.year =
        moment != null ? proxy.moment(moment).format("YYYY") : null;
      form.value.month =
        moment != null ? proxy.moment(moment).format("MM") : null;
    }
    loadData();
  }
  function vbs(val) {
    // srcList.value = []
    // srcList.value.push(val)
  }

  function handleBeforeUpload(file) {

    if (file.type !== "image/bmp" && file.type !== "image/gif" && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/png' && file.type != 'image/tiff') {
      proxy.$modal.msgError("请选择图片文件");
      return false;
    }
    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() {
    console.log(1111, files.value);
    for (let i = 0; i < files.value.length; i++) {
      const item = files.value[i];
      if (item.typeId == null) {
        proxy.$modal.msgError("票据类型不能为空");
        return;
      }
    }
    const file = {
      companyId: form.value.companyId,
      year: form.value.year,
      month: form.value.month,
      isFinished: form.value.isFinished,
      files: files.value,
    };
    saveTickets(file).then((res) => {
      getList.value();
      close();
    });
  }

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