<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-dropdown style="margin-top: 2px">
        <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>
      <el-radio-group v-model="queryRadio" style="margin-left: 20px; height: 100%" size="small"
        @change="radioChangeHandler">
        <el-radio-button label="全部" />
        <el-radio-button label="待确认扣款" />
        <el-radio-button label="可扣款" />
        <el-radio-button label="已申报" />
        <el-radio-button label="已扣款" />
        <el-radio-button label="扣款失败" />
      </el-radio-group>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="78px">
      <el-form-item label="来源名：">
        <el-select v-model="queryParams.sourceNames" placeholder="请选择来源名" multiple>
          <el-option v-for="item in sources" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称：">
        <el-input v-model.trim="queryParams.companyName" size="small" type="text" placeholder="客户名称" :clearable="true"
          style="width: 140px" />
      </el-form-item>
      <el-form-item label="所属期：">
        <el-date-picker v-model="queryParams.currentMonth" type="month" format="YYYY年MM月" value-format="YYYY-MM"
          style="width: 130px" />
      </el-form-item>
      <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:">
        <el-switch v-model="oneself" @change="handleOneself" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="operation" @click="moreSearch = true">更多</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</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 type="selection" width="55" align="center" />
      <el-table-column label="客户名" prop="companyName" min-width="250" align="center" fixed="left" />
      <el-table-column label="来源" align="center" prop="fromCompanyName" v-if="tenant.versionId === '4'" />
      <el-table-column label="受委托方" align="center" prop="toTenantName" min-width="130"
        v-if="tenant.versionId !== '4'" />
      <el-table-column label="纳税性质" prop="taxType" width="100" align="center" />
      <el-table-column label="扣款期" prop="currentMonth" min-width="100" align="center">
        <template #default="scope">
          {{ scope.row.year }}年{{ scope.row.month }}月
        </template>
      </el-table-column>
      <el-table-column label="来源名" prop="sourceName" width="150" align="center" />
      <el-table-column label="金额" prop="amount" width="130" header-align="center" align="right">
        <template #default="scope">
          <el-button v-if="scope.row.deductible === 1" type="primary" link size="small"
            @click="amountDetail(scope.row)">{{ rowNum(scope.row.amount) }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="确认人" prop="confirmName" width="110" align="center" />
      <el-table-column label="确认时间" prop="confirmDate" min-width="140" align="center" />
      <el-table-column label="操作人" prop="operationName" width="100" align="center" />
      <el-table-column label="操作时间" min-width="140" prop="operationDate" align="center" />
      <el-table-column label="文件查看" align="center" width="100">
        <template #default="scope">
          <el-button v-if="scope.row.status === 2" size="small" type="primary" link
            @click="showFiles(scope.row)">查看文件</el-button>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.status === 0">待确认扣款</span>
          <span v-if="scope.row.status === 1">可扣款</span>
          <span v-if="scope.row.status === 2">已扣款</span>
          <el-tooltip v-if="scope.row.status === 4" :content="scope.row.failureType === 1 ? scope.row.failureResult : '余额不足'
              " placement="top">
            <span>扣款失败</span>
          </el-tooltip>
          <span v-if="scope.row.status === 5">已申报</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template #default="scope">
          <div v-if="scope.row.deductible === 1">
            <div v-if="(scope.row.status === 0 || scope.row.status === 4) &&
              checkConfirm(scope.row)
              ">
              <el-button v-hasPermi="['business:deduction:confirm']" link type="primary" size="small"
                @click="showConfirm(scope.row)">确认扣款</el-button>
            </div>
            <div v-if="scope.row.sourceName === '公积金'">
              <template v-if="scope.row.status === 1">
                <el-button link v-hasPermi="['business:deduction:declare']" style="margin-right: 5px" type="primary"
                  size="small" @click="applySuccess(scope.row, 5)">申报成功</el-button>
              </template>
            </div>
            <div v-if="scope.row.sourceName === '公积金'">
              <template v-if="scope.row.status === 5">
                <el-button link v-hasPermi="['business:deduction:deduction']" style="margin-right: 5px" type="primary"
                  size="small" @click="openUpload(scope.row)">扣款成功</el-button>
                <el-button link v-hasPermi="['business:deduction:deduction']" style="margin-left: 5px; " type="primary"
                  size="small" @click="showFeedbackDialog(scope.row)">扣款失败</el-button>
              </template>
            </div>
            <div v-else>
              <div v-if="scope.row.status === 1">
                <el-button link v-hasPermi="['business:deduction:deduction']" style="margin-right: 5px" type="primary"
                  size="small" @click="openUpload(scope.row)">扣款成功</el-button>
                <el-button link v-hasPermi="['business:deduction:deduction']" style="margin-left: 5px; " type="primary"
                  size="small" @click="showFeedbackDialog(scope.row)">扣款失败</el-button>
              </div>

            </div>
          </div>
          <div v-if="scope.row.status === 2">
            <el-button link style="margin-left: 5px; " type="primary" size="small" @click="returnInit(scope.row)"
              v-hasPermi="['business:deduction:return']">退回</el-button>
          </div>
        </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">
      <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="凭证附件：" required>
              <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 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-column label="操作" width="47" align="center">
                  <template #default="scope">
                    <el-button link size="small" type="danger" @click="handleDelFile(scope.$index)">删除</el-button>
                  </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" size="small" icon="Finished" @click="saveHandler">确 定</el-button>
          <el-button icon="close" size="small" @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" />
    <feedbackDialog ref="feedbackDialogRef" :verify="verifyDeduction" />
    <FileDialog ref="fileDialog" />
    <MergeTaxViewDialog ref="mergeTaxViewDialog" />
    <HousingFundViewDialog ref="housingFundViewDialog" />
    <SocialSecurityViewDialog ref="socialSecurityViewDialog" />
    <!-- 更多搜索弹窗 -->
    <el-dialog title="更多搜索" v-model="moreSearch" width="620px" append-to-body draggable>
      <el-form :model="queryParams" ref="queryRef" size="small" label-width="100">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称：">
              <el-input v-model.trim="queryParams.companyName" size="small" type="text" placeholder="客户名称"
                :clearable="true" />
            </el-form-item>
            <el-form-item label="来源名：" prop="sourceNames">
              <el-select v-model="queryParams.sourceNames" placeholder="请选择来源名" multiple>
                <el-option v-for="item in sources" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="来源：" prop="fromCompanyName">
              <el-input size="small" v-model="queryParams.fromCompanyName" type="text" placeholder="客户来源"
                :clearable="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纳税性质：" prop="taxType">
              <el-select size="small" v-model="queryParams.taxType" placeholder="请选择纳税性质" :clearable="true"
                @change="taxTypeChange">
                <el-option v-for="item in taxTypes" :key="item.label" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属期：">
              <el-date-picker v-model="queryParams.currentMonth" type="month" format="YYYY年MM月"
                value-format="YYYY-MM" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Finished" size="small" @click="handleQuery">确 定</el-button>
          <el-button icon="close" size="small" @click="moreSearch = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Deduction">
  import {
    listDeduction,
    exportDeposition,
    saveDeduction
  } from "@/api/business/production/deduction";
  import MergeTaxViewDialog from "./MergeTaxViewDialog";
  import feedbackDialog from "./feedbackDialog";
  import { uploadFile } from "@/api/tool/file";
  import { rowNum } from "@/utils/index";
  import { listCompany } from "@/api/business/crm/company";
  import { taxTypes } from "@/utils/default";
  import useUserStore from "@/store/modules/user";
  import { getTenant } from "@/utils/auth";
  import { ref } from "vue";
  import FileDialog from "./fileDialog.vue";
  import HousingFundViewDialog from "./HousingFundViewDialog";
  import SocialSecurityViewDialog from "./SocialSecurityViewDialog";

  // import DepositForm from "./form"
  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 moreSearch = 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 flag = ref(checkPermission(['business:deduction:person']))
  const flag2 = ref(checkPermission(['business:deduction:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const sources = ref([
    {
      value: "税款",
      label: "税款",
    },
    {
      value: "社保",
      label: "社保",
    },
    {
      value: "公积金",
      label: "公积金",
    },
  ]);

  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: "",
    orderByColumn: "create_time",
    noContract: 1,
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
  });

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listDeduction(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 returnInit(row) {
    row.status = 0;
    saveDeduction(row).then(res => {
      getList();
    })
  }
  function radioChangeHandler(arg) {
    const query = {
      pageNum: 1,
      pageSize: 20,
      companyName: "",
    };
    switch (arg) {
      case "全部":
        query.status = null;
        break;
      case "待确认扣款":
        query.status = 0;
        break;
      case "可扣款":
        query.status = 1;
        break;
      case "已扣款":
        query.status = 2;
        break;
      case "已申报":
        query.status = 5;
        break;
      case "扣款失败":
        query.status = 4;
        break;
      default:
        break;
    }
    queryParams.value = query;
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    // proxy.resetForm("queryRef");
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      companyName: "",
      orderByColumn: "create_time",
      noContract: 1,
    };
    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 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() {
    exportDeposition(queryParams.value);
  }
  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 handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  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.operationId = useUserStore().user.userId;
    form.value.operationDate = proxy.moment().format("YYYY-MM-DD HH:mm:ss");
    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().subtract(1, "months").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(value).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);
  }

  getList();
</script>