<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="primary" size="small" icon="Plus" @click="handleAdd"
        v-hasPermi="['business:accountAdjustment:add']">新增</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-hasPermi="['business:deposit:export']">
              导出</el-dropdown-item>
            <!-- <el-dropdown-item type="warning" size="small" icon="Download" @click="handleArea"
              v-hasPermi="['business:deposit:export']"> area</el-dropdown-item> -->
            <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['business:accountAdjustment:remove']">
              删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-radio-group v-model="queryRadio" style="margin-left: 20px" 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-group>
      <!-- <el-button type="warning" size="small" icon="Download" @click="handleExport"
        v-hasPermi="['business:deposit:export']">导出</el-button> -->
      <!--<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </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="list" 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="申请时间" prop="createTime" width="150" align="center" />
      <el-table-column label="申请人" prop="applieName" width="150" align="center" />
      <el-table-column label="客户名称" prop="companyName" width="150" align="center" />
      <el-table-column label="调账账期" width="150" align="center">
        <template #default="scope">
          <span>{{ scope.row.year + "-" + scope.row.month }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调账原因" prop="adjustmentResult" width="100" align="center" />
      <!-- <el-table-column label="要求完成时间" prop="planFinishedDate" align="center" /> -->
      <el-table-column label="实际完成时间" prop="actuallyFinishedDate" width="126" align="center" />
      <el-table-column label="记账会计" prop="accountantName" width="100" align="center" />
      <el-table-column label="操作" width="60" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.status == 0" type="primary" size="small" icon="Edit" circle
            @click="edit(scope.row.id)" />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.status === 1">已审批&nbsp;&nbsp;</span>
          <span v-if="scope.row.status === 2">已完成</span>
          <span v-if="scope.row.status === 3">审核失败</span></template>
      </el-table-column>
      <el-table-column label="审批" width="220" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.status === 0" type="primary" size="small"
            @click="editStatus(scope.row, 1)">审批通过</el-button>
          <el-button v-if="scope.row.status === 0" type="primary" size="small"
            @click="editStatus(scope.row, 3)">审批不通过</el-button>
          <el-button v-if="scope.row.status === 1" type="primary" size="small"
            @click="editStatus(scope.row, 2)">完成</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="扣款信息" v-model="formOpen" width="500px" append-to-body draggable @close="formCancel"
      :close-on-click-modal="false">
      <!-- 功能按钮 -->
      <div class="form-btns-container">
        <el-button type="success" size="small" @click="handleSave"><i class="fa fa-floppy-o" aria-hidden="true" />
          保存</el-button>
      </div>
      <div style="padding: 8px 24px 16px 24px">
        <el-form size="small" label-width="130px">
          <el-form-item label="客户名称：" required>
            <el-autocomplete :fetch-suggestions="querySearchCompanyAsync" :trigger-on-focus="true"
              v-model="form.companyName" placeholder="请输入客户名称" popper-class="my-autocomplete"
              @select="handleSelectCompany">
              <template #default="{ item }">
                <div style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  ">
                  <div class="name" style="font-size: 12px">
                    {{ item.name }}
                  </div>
                  <!-- <span class="code" style="font-size: 10px; color: darkgrey">{{ item.code }}</span> -->
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="账期：" required>
            <el-select v-model="form.creditTerm" placeholder="选择月" style="width: 80.8%" @change="getCreditTerm">
              <el-option v-for="item in creditTermList" :key="item.checkDate" :label="item.checkDate"
                :value="item.checkDate" value-format="yyyy-MM-dd" />
            </el-select>
          </el-form-item>
          <el-form-item label="调账原因">
            <el-input v-model="form.adjustmentResult" size="small" type="text" placeholder="请输入调账原因"
              style="width: 80.8%" :clearable="true" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" size="small" type="text" placeholder="备注" style="width: 80.8%"
              :clearable="true" />
          </el-form-item>
        </el-form>
      </div>
    </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>
  import {
    listAccountAdjustment,
    listCompany,
    getCreditTermByCompId,
    addAccountAdjustment,
    updateAccountAdjustment,
    delAccountAdjustment,
    getAccountAdjustment,
  } from "@/api/business/production/accountAdjustment";
  import useUserStore from "@/store/modules/user";
  import { reactive, toRefs } from "vue";
  const { proxy } = getCurrentInstance();

  const formOpen = ref(false);

  const data = reactive({
    // 列表数据源
    list: [],
    comList: [],
    // 查询请求携带的参数
    queryParams: {
      pageNum: 1,
      pageSize: 20,
    },
    visible: false,
    custom: {},
    creditTerm: null,
    stages: [],
    queryRadio: "全部",
    selections: [],
    creditTermList: [],
    form: {},
    userId: null,
    employeeId: null,
    formEmptyData: {
      id: null,
      companyId: "",
      planFinishedDate: "",
      actuallyFinishedDate: "",
      remark: "",
      year: "",
      month: "",
      adjustmentResult: "",
    },
  });
  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 companyQuery = ref({
    pageNum: 1,
    pageSize: 50,
    keyword: "",
  });

  const {
    queryParams,
    form,
    list,
    queryRadio,
    selections,
    creditTerm,
    creditTermList,
  } = toRefs(data);
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  function getList() {
    listAccountAdjustment(queryParams.value).then((res) => {
      list.value = res.rows.map((l) => ({ ...l }));
      total.value = res.total;
      loading.value = false;
    });
  }

  function getCompanies() {
    listCompany();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

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

  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 = 3;
        break;
      default:
        break;
    }
    queryParams.value = query;
    handleQuery();
  }

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

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

  function handleAdd() {
    formOpen.value = true;
  }

  function getCreditTermList() {
    getCreditTermByCompId({ id: form.value.companyId }).then((res) => {
      creditTermList.value = res.rows;
    });
  }

  function handleSave() {
    form.value.applierId = useUserStore().user.userId;
    if (form.value.companyId == null || form.value.companyId === "") {
      proxy.$modal.msgError("客户名称不能为空");
      return;
    }
    if (
      form.value.year == null ||
      form.value.month == null ||
      form.value.year === "" ||
      form.value.month === ""
    ) {
      proxy.$modal.msgError("账期不能为空");
      return;
    }
    if (form.value.id == null) {
      addAccountAdjustment(form.value).then((res) => {
        getList();
        formCancel();
      });
    } else {
      updateAccountAdjustment(form.value).then((res) => {
        getList();
        formCancel();
      });
    }
  }

  function edit(id) {
    formOpen.value = true;
    form.value.id = id;
    getFormValue();
  }

  function getFormValue() {
    getAccountAdjustment(form.value.id).then((res) => {
      form.value = res.data;
      form.value.creditTerm = form.value.year + "-" + form.value.month + "-01";
      getCreditTermList();
    });
  }

  function querySearchCompanyAsync(queryString, cb) {
    const query =
      queryString.length > 0
        ? {
          keyword: queryString,
          pageSize: 50,
          pageNum: 1,
          orderByColumn: "create_time",
        }
        : { pageSize: 50, pageNum: 1, orderByColumn: "create_time" };
    listCompany(query).then((res) => {
      cb(res.rows);
    });
  }

  function handleSelectCompany(item) {
    form.value.companyName = item.name;
    form.value.companyId = item.id;
    getCreditTermList();
  }

  function getCreditTerm(arg) {
    console.log(arg);
    form.value.year = proxy.moment(arg).format("YYYY");
    form.value.month = proxy.moment(arg).format("MM");
  }

  function reset() {
    form.value = {};
  }

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

  function handleExport() { }

  function editStatus(row, status) {
    if (status === 2) {
      row.accountantId = useUserStore().user.userId;
      row.actuallyFinishedDate = proxy.moment().format("YYYY-MM-DD HH:mm:ss");
    }
    proxy.$modal
      .confirm(`确认${status !== 2 ? "审批" : "完成"}么`)
      .then((_) => {
        row.status = status;
        updateAccountAdjustment(row).then((res) => {
          getList();
          formCancel();
        });
      })
      .catch((_) => {
        proxy.$modal.msg("取消审批");
      });
  }

  getList();
</script>
<style>
  .companylist .el-badge__content.el-badge__content--undefined.is-fixed {
    top: 0px;
    right: -5px;
  }

  .companylist .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    color: rgb(64, 158, 255);
    background-color: rgba(0, 0, 0, 0);
    border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) rgb(64, 158, 255) rgba(0, 0, 0, 0);
    border-style: none none solid none;
    border-width: 0 0 3px 0;
    box-shadow: none;
  }

  .companylist .el-radio-button__inner {
    border: none;
    background-color: rgba(0, 0, 0, 0);
    border-color: rgba(0, 0, 0, 0);
    border-style: none none solid none;
    border-width: 0 0 3px 0;
    box-shadow: none;
  }

  .companylist .el-radio-button:first-child .el-radio-button__inner {
    border-left: none;
    border-radius: 0 0 0 0;
  }

  .companylist .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 0 0 0 0;
  }

  .companylist .badge-radio .el-badge__content.el-badge__content--undefined.is-fixed {
    top: -8px;
    right: 10px;
  }
</style>