<template>
  <div class="page-container list-container">
    <div class="list-btns-container">
      <el-button v-show="info.status !== 2" type="primary" size="small" icon="Plus" @click="handleAdd"
        v-hasPermi="['business:deduct:add']">生成新对账单</el-button>

      <el-button size="small" icon="Close" @click="handleClose">关闭</el-button>
    </div>

    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="68px">
      <el-form-item label="对账日期：" size="small" prop="dictLabel">
        <el-date-picker clearable size="small" v-model="queryParams.formDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择签约日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="dataList" height="100%" size="small" border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="对账日期" align="center" prop="statementDate" />
      <el-table-column label="委托单号" align="center" prop="formNo">
      </el-table-column>
      <el-table-column label="对账金额" align="center" prop="amount" />
      <el-table-column label="对账月份" align="center">
        <template #default="scope">
          {{ scope.row.year }}年{{ scope.row.month }}月
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="entrust_deduct_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-show="scope.row.status !== 2" link size="small" type="warning" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:deduct:edit']">查看</el-button>
          <el-button v-show="scope.row.status !== 2" link size="small" type="danger" @click="handleDelete(scope.row)"
            v-hasPermi="['business:deduct:remove']">删除</el-button>
          <el-button v-show="scope.row.status === 2" link size="small" type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:deduct:info']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <statement-account-form ref="statementAccountFormRef" :get-list="getList" />
    <choice-month-dialog ref="choiceMonthDialogRef" @confirm="monthConfirmHandler" />
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="Data">
  import {
    listDeduct,
    delDeduct,
    exportDeduct,
    checkStatementAccount,
    getEntrustOrder,
  } from "@/api/business/entrust/deduct";
  import statementAccountForm from "./form.vue";
  import ChoiceMonthDialog from "./ChoiceMonthDialog.vue";

  const { proxy } = getCurrentInstance();
  const { entrust_deduct_status } = proxy.useDict("entrust_deduct_status");
  const info = ref({});

  const dataList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const defaultDictType = ref("");
  const typeOptions = ref([]);

  const statementAccountFormRef = ref(null);
  const choiceMonthDialogRef = ref(null);

  const route = useRoute();
  const webHost = import.meta.env.VITE_APP_BASE_API;

  // 数据标签回显样式
  const listClassOptions = ref([
    { value: "default", label: "默认" },
    { value: "primary", label: "主要" },
    { value: "success", label: "成功" },
    { value: "info", label: "信息" },
    { value: "warning", label: "警告" },
    { value: "danger", label: "危险" },
  ]);

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      orderByColumn: "create_time",
      pageSize: 20,
      entrustOrderId: null,
    },
    rules: {
      dictLabel: [
        { required: true, message: "数据标签不能为空", trigger: "blur" },
      ],
      dictValue: [
        { required: true, message: "数据键值不能为空", trigger: "blur" },
      ],
      dictSort: [
        { required: true, message: "数据顺序不能为空", trigger: "blur" },
      ],
    },
  });

  const { queryParams, form, rules } = toRefs(data);
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询字典类型详细 */
  function setEntrustOrder(id) {
    queryParams.value.entrustOrderId = id;
    getInfo(id);
    getList();
  }

  function getInfo(id) {
    getEntrustOrder(id).then((res) => {
      info.value = res.data;
    });
  }

  /** 查询字典数据列表 */
  function getList() {
    loading.value = true;
    listDeduct(queryParams.value).then((response) => {
      dataList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }
  /** 表单重置 */
  function reset() {
    form.value = {
      dictCode: undefined,
      dictLabel: undefined,
      dictValue: undefined,
      cssClass: undefined,
      listClass: "default",
      dictSort: 0,
      status: "0",
      remark: undefined,
    };
    proxy.resetForm("dataRef");
  }

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

  /** 返回按钮操作 */
  function handleClose() {
    const obj = { path: "/contracts/entrustOrder" };
    proxy.$tab.closeOpenPage(obj);
  }

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

  /** 新增按钮操作 */
  function handleAdd() {
    // 判断是否有上月委托
    // 判断上月委托是否已做对账单
    // 假设已做对账单 则询问是否做本月对账单
    // 假设做本月对账单 传入本月信息到dialog
    choiceMonthDialogRef.value.open(queryParams.value.entrustOrderId);
    // checkStatementAccount(queryParams.value.entrustOrderId).then((res) => {
    //   const currentDate = res.msg;
    //   statementAccountFormRef.value.add({
    //     entrustOrderId: queryParams.value.entrustOrderId,
    //     currentDate: currentDate,
    //   });
    //   // console.log(res)
    // });
  }

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

  /** 修改按钮操作 */
  function handleUpdate(row) {
    statementAccountFormRef.value.open(row.id);
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["dataRef"].validate((valid) => {
      if (valid) {
        if (form.value.dictCode != undefined) {
          updateData(form.value).then((response) => {
            useDictStore().removeDict(queryParams.value.dictType);
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addData(form.value).then((response) => {
            useDictStore().removeDict(queryParams.value.dictType);
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }
  /** 删除按钮操作 */
  function handleDelete(row) {
    const ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除？")
      .then(function () {
        return delDeduct(ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => { });
  }

  function monthConfirmHandler(daterange) {
    const startMonth = daterange[0];
    const endMonth = daterange[1];
    statementAccountFormRef.value.add({
      entrustOrderId: queryParams.value.entrustOrderId,
      startMonth: startMonth,
      endMonth: endMonth,
    });
  }

  setEntrustOrder(route.params && route.params.orderId);
</script>