<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-dropdown trigger="click">
        <el-button type="primary" size="small">
          其它<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Download" @click="handleExport" v-hasPermi="['business:deposit:export']">
              导出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="68px">
      <el-form-item label="客户名称：" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表区 -->
    <el-table v-loading="loading" :data="orderList" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
      <el-table-column label="日期" align="center" prop="depositDate" width="200" />
      <el-table-column label="金额" align="center" prop="amount" width="120" />
      <el-table-column label="附件" align="center" prop="files">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="showFileList(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" width="80" prop="remark">
        <template #default="scope">
          <dict-tag :options="verify_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="verifyStatus" width="200">
        <template #default="scope">
          <el-button v-show="scope.row.status === 0" link type="primary" size="small" @click="handleInfo(scope.row)"
            v-hasPermi="['business:deposit:info']">修改</el-button>
          <el-button v-show="scope.row.status === 0" link type="primary" size="small" @click="handleDelete(scope.row)"
            v-hasPermi="['business:deposit:remove']">删除</el-button>
          <el-button v-show="scope.row.status !== 0" link type="primary" size="small" @click="handleInfo(scope.row)"
            v-hasPermi="['business:deposit:info']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <Deposit-form ref="DepositRef" :get-list="getList" /> -->
    <el-dialog title="新增存款" v-model="formOpen" width="500px" append-to-body draggable @close="formCancel"
      :close-on-click-modal="false">
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="存款金额：">
              <el-input-number v-if="form.status !== 1" v-model="form.amount" :precision="2" :step="0.1" :min="0"
                :controls="false" />
              <div v-else>{{ form.amount }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="凭证附件：">
              <div class="details-btns-container" style="display: flex">
                <el-upload v-if="form.status !== 1" action="#" :http-request="upload" :with-credentials="true"
                  :show-file-list="false" multiple>
                  <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
                </el-upload>
              </div>
              <el-table ref="filesTable" :data="form.files" size="small" height="200px" border
                header-row-class-name="list-header-row">
                <el-table-column v-if="form.status !== 1" label="操作" width="47" align="center">
                  <template #default="scope">
                    <el-button icon="Minus" size="small" circle type="danger" @click="handleDelFile(scope.$index)" />
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="47" align="center" />
                <el-table-column label="文件名" prop="originalFileName" align="center">
                  <template #default="scope">
                    <el-link :href="`${baseUrl}${scope.row.fileUrl}`" :underline="false" target="_blank" type="primary">
                      {{ scope.row.originalFileName }}
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveHandler">确 定</el-button>
          <el-button @click="formCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
  </div>
</template>

<script setup name="Company">
  // import contractForm from "./form";
  import {
    listDeposit,
    delDeposit,
    exportDeposit,
    addDeposit,
    getDeposit,
    updateDeposit,
  } from "@/api/business/entrust/deposit";
  // import ElImageViewer from 'element-plus/lib/components/image-viewer';
  import { uploadFile } from "@/api/tool/file";
  import { listCompany } from "@/api/business/crm/company";
  import { ref } from "vue";
  // import DepositForm from "./form"
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const orderList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const prev = ref([]);
  const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
  const showViewer = ref(false);
  const currentFileList = ref([]);
  const showIndex = ref(0);

  const formOpen = ref(false);

  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 1,
    files: [],
  });

  const emptyForm = {
    id: null,
    companyName: "",
    companyId: null,
    type: 1,
    remark: "",
    files: [],
  };

  const { verify_status } = proxy.useDict("verify_status");
  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    companyName: "",
    noContract: 1,
  });

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listDeposit(queryParams.value).then((response) => {
      orderList.value = response.rows.map((l) => ({ ...l }));
      prev.value = proxy.deepClone(response.rows);
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    // proxy.$refs.DepositRef.open();
    formOpen.value = true;
  }

  function formCancel() {
    formOpen.value = false;
    reset();
  }

  function reset() {
    form.value = proxy.deepClone(emptyForm);
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    // const id = row.id || ids.value;
    // proxy.$refs.DepositRef.open(id);
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delDeposit(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 导出按钮操作 */
  function handleExport() {
    // proxy.download(
    //   "business/archive/order/export",
    //   {
    //     ...queryParams.value,
    //   },
    //   `合同导出_${new Date().getTime()}.xlsx`
    // );
    exportDeposit(queryParams.value);
  }

  function startDateChangeHandler(row, startDate) {
    if (startDate) {
      // console.log(startDate)
      row.endMonth = proxy
        .moment(startDate)
        .add(row.monthNum - 1, "M")
        .format("YYYY-MM-DD");
    } else row.endMonth = null;
    console.log(row);
  }

  function saveHandler() {
    if (form.value.amount == null || form.value.amount === 0) {
      proxy.$modal.msgError("请输入存款金额");
      return;
    }
    if (form.value.files.length === 0) {
      proxy.$modal.msgError("请上传凭证附件");
      return;
    }
    if (form.value.id == null) {
      addDeposit(form.value).then((res) => {
        formCancel();
        getList();
      });
    } else {
      updateDeposit(form.value).then((res) => {
        formCancel();
        getList();
      });
    }
  }

  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;
        form.value.files.push(file);
      }
    });
  }

  function openFollowFile(arg) {
    // console.log(arg)
    const attach = arg;
    window.open(`${arg.url}`, arg.fileName);
  }

  function showFileList(row) {
    currentFileList.value = row.files.map((l) => `${baseUrl.value}${l.fileUrl}`);
    showViewer.value = true;
  }

  function closeImages() {
    showViewer.value = false;
  }

  function handleInfo(row) {
    formOpen.value = true;
    getForm(row.id);
  }

  function getForm(id) {
    getDeposit(id).then((res) => {
      form.value = res.data;
      if (form.value == null) {
        reset();
      }
    });
  }

  function handleDelFile(index) {
    form.value.files.splice(index, 1);
  }

  getList();
</script>