<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 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="账期" required>
                <!-- <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-date-picker v-model="form.currentMonth" type="month" placeholder="Pick a month" format="YYYY-MM"
                  @change="changeMonthHandle" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传完成">
                {{ form.isFinished === 0 ? "否" : "是" }}
              </el-form-item>
            </el-col>
            <!-- <el-col v-if="form.isFinished === 0" :span="12"> -->
            <!-- <el-form-item label="" required> -->
            <!-- </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"
                  /> -->
                    <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">
                      <div class="bottom clearfix">
                        <el-form-item label="票据类型">
                          <dict-tag :options="ticket_type" :value="o.typeId" />
                        </el-form-item>
                      </div>
                    </div>
                  </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 props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
    width: {
      type: String,
      default: "800px",
    },
  });
  const { getList, width } = toRefs(props);
  const loading = ref(false);
  // 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);
  const srcList = ref([]);
  function open(arg) {
    visible.value = true;
    form.value = arg;
    loading.value = true
    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;
  }
  /**
   * 加载数据
   */
  const loadData = async () => {
    const res = await listFiles(form.value);
    files.value = res.data.files;
    srcList.value = files.value.map((v) => baseUrl.value + v.fileUrl);
    months.value = res.data.months;
    form.value.isFinished = res.data.finished.isFinished;
      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);
      }
    });
  }

  function changeMonthHandle(item) {

    // const date = proxy.moment(item).format('YYYY-MM'); // 使用 moment.js 或者其它日期处理库
    // const index = months.value.findIndex((v) => v.id === date);
    // 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 = proxy.moment(item).format("YYYY")
    //   moment != null ? proxy.moment(date).format("YYYY") : null;
    form.value.month = proxy.moment(item).format("MM")
    //   moment != null ? proxy.moment(date).format("MM") : null;
    // }
    loadData();
  }

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

  function handleSave() {
    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();
    });
  }
  function vbs(val) {
    // srcList.value = []
    // srcList.value.push(val)
  }
  defineExpose({
    open,
  });
</script>