<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <!-- <el-dropdown>
        <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" :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="客户名称：">
        <el-input v-model.trim="queryParams.companyName" size="small" type="text" placeholder="客户名称" :clearable="true"
          style="width: 130px" />
      </el-form-item>
      <el-form-item label="客户标签：">
        <el-select v-model="queryParams.customerLabelId" style="width: 130px" clearable size="small">
          <el-option v-for="item in options" :key="item.id" :label="item.lable" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属月：">
        <el-date-picker v-model="currentMonth" type="month" format="YYYY年MM月" size="small" :clearable="false"
          style="width: 130px" value-format="YYYY-MM-01" @change="currentMonthChange"
          :disabled-date="disabledDateHandler" />
      </el-form-item>
      <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:" v-hasPermi="['business:upload:person']">
        <el-switch v-model="oneself" @change="handleOneself" />
      </el-form-item> -->
      <el-form-item label="上传人：" prop="finishUserName">
        <el-input size="small" v-model="queryParams.finishUserName" placeholder="请输入上传人" clearable style="width: 130px"
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item prop="dateFilter" label="上传时间：">
        <el-date-picker size="small" v-model="queryParams.dateFilterFinish" type="daterange" clearable
          format="YYYY - MM - DD " value-format="YYYY-MM-DD" range-separator="至" start-placeholder="业务日期"
          end-placeholder="业务日期" style="width: 70%;"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" size="small">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery" size="small">重置</el-button>
      </el-form-item>
    </el-form>
    <div v-if="flag && flag2 && tenant.versionId !== '4'">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="全部" name="first">

        </el-tab-pane>
        <el-tab-pane label="我的" name="second">

        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 列表区 -->
    <el-table v-loading="loading" :data="list" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column label="客户名称" align="center" prop="companyName">
        <template #default="scope">
          <div style="display: flex; align-items: center; ">
            <template v-if="scope.row.customerLabelName ">
              <el-tooltip :content="scope.row.customerLabelName" placement="top">
                <el-icon :size="15">
                  <CollectionTag />
                </el-icon>
              </el-tooltip>
              <span style="padding-left:5px;">{{ scope.row.companyName }}</span>
            </template>
            <template v-else>
              <div style="width: 20px; height: 15px;"></div>
              <span>{{ scope.row.companyName }}</span>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="fromCompanyName" min-width="100"
        v-if="tenant.versionId === '4'" />
      <el-table-column label="受委托方" align="center" prop="toTenantName" v-if="tenant.versionId !== '4'" />
      <el-table-column label="纳税性质" prop="taxType" min-width="110" align="center" />
      <el-table-column label="上传人" align="center" prop="finishUserName" min-width="100" />
      <el-table-column label="上传时间" align="center" prop="finishTime" min-width="100" />
      <el-table-column label="操作" width="130" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" link type="primary" v-hasPermi="['business:archiveReceiveTicket:upload']" circle
            @click="uploadHandle(scope.row)">上传</el-button>
          <el-button link size="small" type="primary" v-hasPermi="['business:archiveReceiveTicket:query']" circle
            @click="viewHandle(scope.row)">查看</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="扣款金额：">
              <div>{{ 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 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 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" />
    <form-dialog ref="formDialogRef" :getList="getList" />
    <view-dialog ref="viewDialogRef" :getList="getList" />
  </div>
</template>

<script setup name="ArchiveReceiveTicket">
  import { listLableNoPage } from "@/api/business/lable"
  import { listArchiveTicket } from "@/api/business/production/archiveTicket";
  import { uploadFile } from "@/api/tool/file";
  import { listCompany } from "@/api/business/crm/company";
  import useUserStore from "@/store/modules/user";
  import { getTenant } from "@/utils/auth";
  import { ref } from "vue";
  import formDialog from "./form.vue";
  import viewDialog from "./view.vue";
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant
  const list = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const oneself = ref(false);
  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 queryRadio = ref("全部");
  const permissions = useUserStore().permissions;

  const currentMonth = ref(
    proxy.moment().subtract(1, "month").format("YYYY-MM-01")
  );

  const formOpen = ref(false);
  const formDialogRef = ref(null);
  const viewDialogRef = ref(null);
  const flag = ref(checkPermission(['business:upload:person']))
  const flag2 = ref(checkPermission(['business:upload:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const options = ref([]);
  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,
    orderByColumn: "create_time",
    year: proxy.moment().format("YYYY"),
    month: proxy.moment().format("MM"),
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
  });

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

  /** 是否为自己负责 */
  function handleOneself() {
    if (oneself.value) {
      queryParams.value.principal = useUserStore().user.userId;
    } else {
      queryParams.value.principal = null;
    }
    getList();
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  function checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }
  /** 重置按钮操作 */
  function resetQuery() {
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      year: proxy.moment().format("YYYY"),
      month: proxy.moment().format("MM"),
      orderByColumn: "create_time",
    };
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  function getOption() {
    listLableNoPage().then(res => {
      options.value = res.data
    })
  }
  /** 新增按钮操作 */
  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;
    }
    form.value.status = 2;
    saveDeduction(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;
        file.masterId = form.value.id;
        file.masterTableName = "biz_deduction";
        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);
  }

  function amountDetail(row) {
    const item = {
      year: proxy.moment().format("YYYY"),
      month: proxy.moment().subtract(1, "months").format("MM"),
    };
    switch (row.sourceName) {
      case "税款":
        proxy.$refs.mergeTaxViewDialog.open(row);
        break;
      case "社保":
        proxy.$refs.socialSecurityViewDialog.open(row);
        break;
      case "公积金":
        proxy.$refs.housingFundViewDialog.open(row);
        break;
    }
  }

  function showFiles(row) {
    proxy.$refs.fileDialog.open({
      masterTableName: "biz_deduction",
      masterId: row.id,
    });
  }

  function checkConfirm(row) {
    // console.log(row.tenantId)
    if (row.tenantId === getTenant()) {
      return true;
    } else {
      return false;
    }
  }

  function showConfirm(row) {
    proxy.$modal.confirm("确认扣款么？").then((res) => {
      row.confirmId = useUserStore().user.userId;
      row.confirmDate = proxy.moment().format("YYYY-MM-DD HH:mm:ss");
      row.status = 1;
      saveDeduction(row).then((res) => {
        getList();
      });
    });
  }

  function applySuccess(row, status) {
    proxy.$modal
      .confirm("确认公积金申报成功么？")
      .then((_) => {
        const value = proxy.deepClone(row);
        value.status = status;
        saveDeduction(row).then((res) => {
          getList();
        });
      })
      .catch((_) => {
        proxy.$modal.msg("取消申报");
      });
  }

  function showFeedbackDialog(row) {
    const value = proxy.deepClone(row);
    value.status = 4;
    proxy.$refs.feedbackDialogRef.open(value);
  }

  function verifyDeduction(value) {
    saveDeduction(value).then((res) => {
      getList();
    });
  }

  function openUpload(row) {
    formOpen.value = true;
    form.value = proxy.deepClone(row);
  }

  function currentMonthChange(arg) {
    const year = proxy.moment(arg).format("YYYY");
    const month = proxy.moment(arg).format("MM");
    queryParams.value.year = year;
    queryParams.value.month = month;
    handleQuery();
  }

  function disabledDateHandler(date) {
    if (date <= proxy.moment().subtract(1, "month")) {
      return false;
    } else {
      return true;
    }
  }

  function uploadHandle(row) {
    formDialogRef.value.open({
      companyId: row.companyId,
      companyName: row.companyName,
      year: queryParams.value.year,
      month: queryParams.value.month,
    });
  }
  function viewHandle(row) {
    viewDialogRef.value.open({
      companyId: row.companyId,
      companyName: row.companyName,
      year: queryParams.value.year,
      month: queryParams.value.month,
    });
  }
  getList();
  getOption();
</script>