<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="success" size="small" icon="Refresh" @click="getList"
        v-hasPermi="['business:entrustOrder:remove']">刷新</el-button>
      <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-if="viewAdviser('business:deposit:export')">
              导出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 列表区 -->
    <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="formNo" width="120" />
      <el-table-column label="预存单位" align="center" prop="contactCompany" width="120" />
      <el-table-column label="签约主体" align="center" prop="signingSubject" width="120" />
      <el-table-column label="金额" align="center" prop="amount" width="120">
        <template #default="scope">
          <span>{{ rowNum(scope.row.amount) }}</span>
        </template>
      </el-table-column>
      <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="warning" size="small"
            @click="handleVerify(scope.row, 1)" v-hasPermi="['business:deposit:verify']">审核通过</el-button>
          <el-button v-show="scope.row.status === 0" link type="danger" size="small" @click="handleVerify(scope.row, 4)"
            v-hasPermi="['business:deposit:verify']">驳回</el-button>
          <el-button v-show="scope.row.status !== 0" link type="success" 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-autocomplete v-if="form.status !== 1" :fetch-suggestions="querySearchEntrustOrderAsync"
                :trigger-on-focus="true" v-model="form.formNo" placeholder="请输入客户名称" popper-class="my-autocomplete"
                @select="handleSelectEntrustOrder">
                <template #default="{ item }">
                  <div style="
                      display: flex;
                      flex-direction: row;
                      justify-content: space-between;
                    ">
                    <div class="name" style="font-size: 12px">
                      {{ item.formNo }}-{{ item.signingSubject }}
                    </div>
                  </div>
                </template>
              </el-autocomplete>
              <div v-else>{{ form.formNo }}</div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="签约主体：">
              <div>{{ form.signingSubject }}</div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="往来单位：">
              <div>{{ form.contactCompany }}</div>
            </el-form-item>
          </el-col>
          <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" />
    <free-amount-dialog ref="freeAmountDialogRef" :get-list="getList" />
    <el-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
  </div>
</template>

<script setup name="PrevDeposit">
  // import contractForm from "./form";
  import {
    listDeposit,
    delDeposit,
    exportDeposit,
    addDeposit,
    getDeposit,
    updateDeposit,
    listEntrustOrder,
    verifyDeposit,
  } from "@/api/business/entrust/deposit";
  // import ElImageViewer from 'element-plus/lib/components/image-viewer';
  import freeAmountDialog from "./freeAmountDialog.vue";
  import { uploadFile } from "@/api/tool/file";
  import { rowNum } from "@/utils/index";
  import { listCompany } from "@/api/business/crm/company";
  import useUserStore from "@/store/modules/user";
  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 permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  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 freeAmountDialogRef = ref(null);

  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 viewAdviser(quer) {
    return permissions.includes(all_permission) || permissions.includes(quer);
  }

  /** 重置按钮操作 */
  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 handleSelectCompany(item) {
    form.value.companyName = item.name;
    form.value.companyId = item.id;
  }

  function saveHandler() {
    if (
      form.value.entrustOrderId == null ||
      form.value.entrustOrderId === 0 ||
      form.value.entrustOrderId === ""
    ) {
      proxy.$modal.msgError("请选择存款委托合同");
      return;
    }
    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) => {
        console.log("新增", form.value);

        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.originalFilename;
        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 querySearchEntrustOrderAsync(queryString, cb) {
    const query =
      queryString.length > 0
        ? { keyword: queryString, pageSize: 20, pageNum: 1, status: 1 }
        : { pageSize: 20, pageNum: 1, status: 1 };
    listEntrustOrder(query).then((res) => {
      cb(res.rows);
    });
  }

  function handleSelectEntrustOrder(item) {
    form.value.formNo = item.formNo;
    form.value.tenantId = item.tenantId;
    form.value.fromTenantId = item.fromTenantId;
    form.value.entrustOrderId = item.id;
    form.value.signingSubject = item.signingSubject;
    form.value.contactCompany = item.contactCompany;
  }

  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 handleVerify(row, status) {
    if (status === 1) {
      freeAmountDialogRef.value.open(row);
    } else {
      proxy.$modal
        .confirm(`确认${status === 1 ? "审核通过" : "驳回"}么？`)
        .then((_) => {
          const saveValue = proxy.deepClone(row);
          saveValue.status = status;
          return verifyDeposit(saveValue);
        })
        .then((res) => {
          getList();
        });
    }
  }

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

  getList();
</script>