<template>
  <div class="page-container list-container">
    <el-row :gutter="0" style="height: 100%">
      <el-col :span="10" style="height: 100%">
        <!--员工部门列表 开始-->
        <div class="page-container list-container">
          <!--操作按钮 开始-->
          <div>
            <span style="
                display: inline-block;
                height: 20px;
                line-height: 18px;
                font-size: 15px;
                padding: 10px 20px 0 8px;
                margin-top: 5px;
                font-weight: 700;
                border-left: 3px;
              ">支出类目</span>
            <el-button type="primary" size="small" v-hasPermi="['paymentEntry:type:add']" icon="plus" @click="newType">
              新增</el-button>

            <el-button type="success" size="small" icon="refresh" @click="loadData">
              刷新</el-button>
          </div>
          <div class="el-table-container" style="height: 100%; position: relative; overflow: auto">
            <div style="
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
              ">
              <el-table class="table-falex" v-loading="loading" :data="typeList" size="small" border height="100%"
                @row-click="rowClick" @selection-change="handleSelectionChange" highlight-current-row="true">
                <el-table-column label="支出类目" align="center" prop="name">
                  <template #default="scope">
                    <el-input size="small" v-if="scope.row.isAdd || scope.row.isEdit" v-model="scope.row.name"
                      placeholder="请输入支出类目"></el-input>
                    <span v-else>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="备注" align="center" prop="remark">
                  <template #default="scope">
                    <el-input size="small" v-if="scope.row.isAdd || scope.row.isEdit" v-model="scope.row.remark"
                      placeholder="请输入备注"></el-input>
                    <span v-else>{{ scope.row.remark }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <template v-if="!scope.row.isAdd && !scope.row.isEdit">
                      <el-button v-show="!scope.row.isAdd && !scope.row.isEdit" link type="warning" size="small"
                        @click="handleUpdate(scope.row)" circle v-hasPermi="['paymentEntry:type:edit']">修改</el-button>
                      <el-button v-show="!scope.row.isAdd && !scope.row.isEdit" link type="danger" size="small"
                        @click="handleDelete(scope.row)" v-hasPermi="['paymentEntry:type:remove']">删除</el-button>
                    </template>
                    <template v-if="scope.row.isEdit || scope.row.isAdd">
                      <el-button v-if="scope.row.isEdit || scope.row.isAdd" link type="primary" size="small"
                        @click="typeleSave(scope.row)">保存</el-button>
                      <el-button v-if="scope.row.isEdit || scope.row.isAdd" link type="Delete" size="small"
                        @click="handleCancel(scope.row)">取消</el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="14" style="height: 100%">
        <div class="page-container list-container">
          <div>
            <span style="
                display: inline-block;
                height: 20px;
                line-height: 18px;
                font-size: 15px;
                padding: 10px 20px 0 8px;
                margin-top: 5px;
                font-weight: 700;
                border-left: 3px;
              ">支付科目</span>
            <template v-if="currentDepartment !== null">
              <el-button type="primary" size="small" icon="plus" v-hasPermi="['expenditure:subject:add']"
                @click="newSubType">新增</el-button>
            </template>
            <el-button type="success" size="small" icon="refresh" @click="loadSubData">
              刷新</el-button>
          </div>
          <div class="el-table-container" style="height: 100%">
            <div style="height: 100%">
              <el-table v-loading="loading" :data="typeSubLis" size="small" border height="100%"
                @selection-change="handleSelectionChange">
                <el-table-column label="支付科目" align="center" prop="name">
                  <template #default="scope">
                    <el-input size="small" v-if="scope.row.isAdd || scope.row.isEdit" v-model="scope.row.name"
                      placeholder="请输入支付科目"></el-input>
                    <span v-else>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                  <template #default="scope">
                    <el-select size="small" style="width: 100%" v-if="scope.row.isAdd || scope.row.isEdit"
                      v-model.trim="scope.row.status" placeholder="选择状态" :clearable="true">
                      <el-option v-for="item in subType" :key="item.label" :label="item.label" :value="item.value" />
                    </el-select>
                    <span v-else>{{
                      scope.row.status === 0 ? "启用" : "停用"
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <template v-if="!scope.row.isAdd && !scope.row.isEdit">
                      <el-button v-show="!scope.row.isAdd && !scope.row.isEdit" link type="warning" size="small"
                        @click="handleUpdate(scope.row)" circle v-hasPermi="['expenditure:subject:edit']">修改</el-button>
                      <el-button v-show="!scope.row.isAdd && !scope.row.isEdit" link type="danger" size="small"
                        @click="handleSubDelete(scope.row)" v-hasPermi="['expenditure:subject:remove']">删除</el-button>
                    </template>
                    <template v-if="scope.row.isEdit || scope.row.isAdd">
                      <el-button v-if="scope.row.isEdit || scope.row.isAdd" link type="primary" size="small"
                        @click="typeSubSave(scope.row)">保存</el-button>
                      <el-button v-if="scope.row.isEdit || scope.row.isAdd" link type="Delete" size="small"
                        @click="subCancel(scope.row)">取消</el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="loadSubData" />
  </div>
</template>

<script setup name="PaymentEntry">
  import {
    listType,
    delType,
    listTypeSub,
    addType,
    updateType,
  } from "@/api/business/paymentEntry/type";
  import {
    addSubject,
    updateSubject,
    delSubject,
  } from "@/api/business/paymentEntry/subject";
  import { subType } from "@/utils/default";

  import { ref } from "vue";
  // import typeForm from "./form";
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const typeList = ref([]);
  const typeSubLis = ref([]);
  const bizPaymentSubjectList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const typeId = ref();
  /** 查询对象 */

  const query = ref({
    name: null,
    remark: null,
    isAdd: false,
    isEdit: false,
  });

  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    id: null,
    name: null,
    isAdd: false,
    isEdit: false,
    status: 0,
  });

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询支出类目列表 */
  function getList() {
    listType(query.value).then((response) => {
      typeList.value = response.rows;

      if (typeList.value.length > 0) {
        queryParams.value.paymentTypeId = typeList.value[0].id;
        typeId.value = typeList.value[0].id;
        getTypeSubList(queryParams.value);
      } else {
        loading.value = false;
      }
    });
  }

  /** 支出类目列表刷新 */
  function loadData() {
    getList();
  }

  //支付科目刷新
  function loadSubData() {
    if (typeId.value != null) {
      loading.value = true;
      queryParams.value.paymentTypeId = typeId.value;
      getTypeSubList(queryParams.value);
    }
  }

  /** 支出类目列表点击事件 */
  function rowClick(record) {
    if (record.isAdd) {
      return;
    }
    queryParams.value.paymentTypeId = record.id;
    typeId.value = record.id;
    getTypeSubList(queryParams.value);
  }

  /** 获取支出科目列表 */
  function getTypeSubList(data) {
    listTypeSub(data).then((response) => {
      typeSubLis.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 新增支付科目 */
  function newSubType() {
    // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
    const _newSource = JSON.parse(JSON.stringify(queryParams.value));
    typeSubLis.value.push(_newSource);
    handleSourceCurrentChange(_newSource);
  }

  /** 支出科目保存 */
  function typeSubSave(row) {
    if (typeList.value.length == 0) {
      proxy.$modal.msgError("请先添加支出类目");
      return;
    }
    if (typeId.value == null || typeId.value === "") {
      proxy.$modal.msgError("请选择支出类目");
      return;
    }
    if (row.name == "" || row.name == null) {
      proxy.$modal.msgError("支付科目不能为空");
      return;
    }
    if (row.status == null || row.status === "") {
      proxy.$modal.msgError("状态不能为空");
      return;
    }
    loading.value = true;

    if (row.isAdd) {
      addSubject(row).then((response) => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("保存成功");
          queryParams.value.paymentTypeId = typeId.value;
          getTypeSubList(queryParams.value);
        }
      });
    } else {
      updateSubject(row).then((response) => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("保存成功");
          queryParams.value.paymentTypeId = typeId.value;
          getTypeSubList(queryParams.value);
        }
      });
    }
  }

  /** 支出类目保存按钮 */
  function typeleSave(row) {
    if (row.name == "" || row.name == null) {
      proxy.$modal.msgError("支出类目不能为空");
      return;
    }
    if (row.isAdd) {
      addType(row).then((response) => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("保存成功");
          getList();
        }
      });
    } else {
      updateType(row).then((response) => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("保存成功");
          getList();
        }
      });
    }
  }

  /** 取消按钮 */
  function handleCancel(row) {
    console.log("取消", row.isAdd);
    if (row.isAdd) {
      typeList.value.length = typeList.value.length - 1;
    } else {
      row.isEdit = false;
    }
  }

  /** 支出科目取消按钮 */
  function subCancel(row) {
    console.log("科目取消", row.isAdd);
    if (row.isAdd) {
      typeSubLis.value.length = typeSubLis.value.length - 1;
    } else {
      row.isEdit = false;
    }
  }

  /** 支出类目新增按钮 */
  function newType() {
    // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
    const _newSource = JSON.parse(JSON.stringify(query.value));
    typeList.value.push(_newSource);
    handleSourceCurrentChange(_newSource);
  }

  /** 修改新增属性判断 */
  function handleSourceCurrentChange(row) {
    row.isAdd = true;
  }

  /** 输入框输出建议 */
  const querySearchAsync = (queryString, cb) => {
    console.log(links);
    const results = queryString
      ? links.value.filter(createFilter(queryString))
      : links.value;
    cb(results);
  };

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

  /** 重置按钮操作 */
  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.typeRef.open();
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    row.isEdit = true;
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    queryParams.value.paymentTypeId = _ids;
    console.log("ids", _ids);
    listTypeSub(queryParams.value).then((response) => {
      if (response.rows.length > 0) {
        proxy.$modal.msgError("请先删除支出科目！");
        return;
      }
      proxy.$modal
        .confirm("是否确认删除选中的数据项？")
        .then(function () {
          return delType(_ids);
        })
        .then(() => {
          getList();
          proxy.$modal.msgSuccess("删除成功！");
        })
        .catch(() => { });
    });
  }
  /** 科目删除按钮操作 */
  function handleSubDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delSubject(_ids);
      })
      .then(() => {
        queryParams.value.paymentTypeId = typeId.value;
        getTypeSubList(queryParams.value);
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download(
      "paymentEntry/type/export",
      {
        ...queryParams.value,
      },
      `type_${new Date().getTime()}.xlsx`
    );
  }

  getList();
</script>