<template>
  <div>
    <el-dialog :title="props.title" width="1000px" v-model="props.modelValue" :before-close="handleClose">
      <div class="config">
        <el-form :model="ruleForm" :rules="rules" label-width="140px" class="demo-ruleForm.value" ref="ruleFormRef"
          :disabled="disabled">
          <el-form-item label="预算项目：" style="width: 80%">
            <el-input v-model="ruleForm.budgettitle" style="width: 100%" disabled></el-input>
          </el-form-item>
          <el-form-item label="预算类别：" style="width: 80%">
            <MOSTY.DictTree :zdbh="'D_BZ_YSFYLB'" v-model="ruleForm.ctype" :placeholder='"请选择预算类别"' :disabled='true'
              style="width: 100%;" />
          </el-form-item>
          <el-form-item label="费用明细：" prop="costDetailTitle" style="width: 80%">
            <el-input v-model="ruleForm.costDetailTitle" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item style="width: 80%">
            <div class="count-container">
              <div>
                <span> <span class="count-title">总预算：</span>{{ oldData.budgets || 0 }}万元，</span>
                <span> <span class="count-title">总已使用：</span>{{ oldData.free || 0 }}万元，</span>
                <span> <span class="count-title">总可使用：</span>{{ oldData.ksy || 0 }}万元</span>
              </div>
              <div>
                <span> <span class="count-title">当前预算：</span>{{ oldData.thisBudgetsNum || 0 }}万元，</span>
                <span> <span class="count-title">当前已使用：</span>{{ oldData.thisFree || 0 }}万元，</span>
                <span> <span class="count-title">项目剩余：</span>{{ oldData.thisKsy || 0 }}万元</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="使用金额：" prop="costFee" style="width: 80%;">
            <el-input v-model="ruleForm.costFee" type="number" style="width: 100%"><template #append>万元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="情况说明：" style="width: 80%">
            <el-input v-model="ruleForm.costExplain" type="textarea" style="width: 100%" />
          </el-form-item>
          <el-form-item label="备注：" style="width: 80%">
            <el-input v-model="ruleForm.bz" type="textarea" style="width: 100%" />
          </el-form-item>
          <el-form-item label="附件：" style="width: 80%">
            <MOSTY.Upload :widthNumber="565" :limit="4" :nopicer="true" :isImg="false" :ShowfileList="true"
              v-model="ruleForm.fj" :showinput="true" :delrow="delrow">
            </MOSTY.Upload>
          </el-form-item>
        </el-form>
      </div>

      <div v-if='ruleForm.id' style='height:23vh;'>
        <MOSTY.Assort :title="'历史记录'" class='marleft' />
        <el-table ref="multipleTableRef" stripe height="23vh" :data="tableData" v-loading="tableloading"
          element-loading-text="数据加载中..." style="width: 100%" @selection-change="handleSelectionChange" border>
          <el-table-column label="修改时间" property="xtCjsj"></el-table-column>
          <el-table-column label="使用金额（万元）" property="costFee"></el-table-column>
          <el-table-column label="费用明细" property="costDetailTitle"></el-table-column>
          <el-table-column label="情况说明" property="costExplain"></el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <span class="operesee" @click="seeInfo(scope.row)">
                <el-icon>
                  <Compass />
                </el-icon>查看</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="fenye">
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
            layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
        </div>
      </div>
      <template #footer>

        <span class="dialog-footer">

          <el-button type="primary" v-if="props.title != '查看预算'" :loading="loading" @click="handleSave(ruleFormRef)">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="handleClose" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>

        </span>
      </template>
    </el-dialog>
    <aqfysyjlxq v-model="addplanShow" @changeAddVi="addplanShow = false" :id="props.id" :rowid="rowid"
      v-if="addplanShow" />
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, watch, getCurrentInstance } from "vue";
import { getApi, postApi, putApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import aqfysyjlxq from "./aqfysyjlxq.vue";
import { numAdd } from "@/utils/tools.js";
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
const loading = ref(false); //新增保存按钮截流
const delrow = ref({}); //删除文件列表
const tableloading = ref(false);
const rowid = ref(null);
const addplanShow = ref(false);
const total = ref(0);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
const ysyje = ref(0)
const tableData = ref([]);
const ruleForm = ref({});
const emits = defineEmits(["changeAddVi"]);
//规则校验
const rules = reactive({
  costDetailTitle: [{ trigger: "blur", required: true, message: "费用明细不能为空" }],
  costFee: [
    {
      validator: (rule, value, callback) => {
        if (value === '' || value == 0) {
          callback(new Error('使用金额不能为空'));
        } else if (value > oldData.value.ksy) {
          callback(new Error('使用金额必须小于可使用金额'));
        } else if (value < 0 || !/^[0-9]{0,10}(\.[0-9]{0,4})?$/.test(value)) {
          callback(new Error(`只能输入10位整数，4位小数`));
        } else {
          callback();
        }
      },
      trigger: 'blur',
      required: true,
    }
  ]
});
const disabled = ref(false)
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: true
  },
  title: String,
  rowid: String,
  id: {
    type: String,
    default: null
  },
});
const ruleFormRef = ref();
const oldData = ref({})
onMounted(() => {
  // 查询已使用
  const data = { budgetId: props.id, costId: props.rowid }
  if (props.title == "查看预算") {
    data.costId = null;
  }
  getApi(data, `/mosty-jcgl/budgets/getCost`).then((item) => {
    oldData.value = item
  })
  // 查询详情
  getApi({}, `/mosty-jcgl/budgets/showInfo?id=${props.id}`).then((item) => {
    if (item) {
      item.budget = item.budget ? item.budget : 0;
      item.gkpf = numAdd("add", 4, item.budget, item.gkshzj);
      item.ndgkpfs = numAdd("add", 4, item.gkpf, item.yeargkshzj);
      item.costFeer = item.costFee ? item.costFee : 0;
      item.ksyfree = numAdd("reduce", 4, item.ndgkpfs, item.costFee);

      ruleForm.value = {}
      ruleForm.value.fj = null;
      ruleForm.value.budgettitle = item.budgettitle;
      ruleForm.value.budgetid = item.id;
      ruleForm.value.ctype = item.ctype;
      ruleForm.value.ndgkpfs = item.ndgkpfs;
      ruleForm.value.costFeer = item.costFeer;
      ruleForm.value.ksyfree = item.ksyfree;

      if (props.title == "添加使用") {
        ruleForm.value.ndgkpfs = item.ndgkpfs;
        ruleForm.value.costFeer = item.costFeer;
        ruleForm.value.ksyfree = item.ksyfree;
        ysyje.value = Number(ruleForm.value.costFeer)
        ruleForm.value.costDetailTitle = "";
        ruleForm.value.costFee = "";
        ruleForm.value.costExplain = "";
        ruleForm.value.bz = "";
        ruleForm.value.fj = null;
        disabled.value = false
      } else if (props.title == "修改预算") {
        ruleForm.value.ndgkpfs = item.ndgkpfs;
        ruleForm.value.costFeer = item.costFeer;
        ruleForm.value.ksyfree = item.ksyfree;
        disabled.value = false
        ruleForm.value.fj = null;
        getxqData(props.rowid);
        getxgjl()
      } else if (props.title == "查看预算") {
        ruleForm.value.ndgkpfs = item.ndgkpfs;
        ruleForm.value.costFeer = item.costFeer;
        ruleForm.value.ksyfree = item.ksyfree;
        ruleForm.value.fj = null;
        disabled.value = true
        getxqData(props.rowid);
        getxgjl()
      }
    }
  });
});
function getfreexq(params) {

}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getxgjl();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getxgjl();
};
function getxgjl() {
  listQuery.value.budgetid = props.id
  listQuery.value.zbid = props.rowid
  tableloading.value = true;
  postApi(listQuery.value, '/mosty-jcgl/budgetsCost/getJlb').then(res => {
    if (res.orders) {
      tableloading.value = false;
      tableData.value = res.records;
      total.value = res.total;
    }

  }).catch((err) => {
    tableData.value = [];
    tableloading.value = false;
  });
}
//获取费用详情
function getxqData(id) {
  getApi({}, `/mosty-jcgl/budgetsCost/getBudgetsCostById/${id}`).then((res) => {
    ruleForm.value.costDetailTitle = res.costDetailTitle;
    ruleForm.value.costFee = res.costFee;
    ruleForm.value.costExplain = res.costExplain;
    ruleForm.value.bz = res.bz;
    ruleForm.value.id = res.id;
    ruleForm.value.fj = res.fj;
    ysyje.value = numAdd("reduce", 4, ruleForm.value.costFeer, ruleForm.value.costFee)
  });
}

// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (ruleForm.value) {
        ruleForm.value.costFee = Number(ruleForm.value.costFee);
        ruleForm.value.fj = ruleForm.value.fj ? ruleForm.value.fj.toString() : null
        loading.value = true;
        if (!ruleForm.value.id) {
          postApi(ruleForm.value, "/mosty-jcgl/budgetsCost/addCost").then((res) => {
            ElMessage.success("新增成功");
            emits("changeAddVi", false);
          }).finally(() => {
            loading.value = false;
          });
        } else {
          postApi(ruleForm.value, "/mosty-jcgl/budgetsCost/editCost").then((res) => {
            ElMessage.success("修改成功");
            emits("changeAddVi", false);
          }).finally(() => {
            loading.value = false;
          });;
        }
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
// 关闭
const handleClose = () => {
  if (props.title != '查看预算') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        ruleForm.value = {}
        ruleForm.value.fj = null;
        ruleFormRef.value.clearValidate();
        ruleFormRef.value.resetFields();
        emits("changeAddVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    ruleForm.value = {}
    ruleForm.value.fj = null;
    ruleFormRef.value.clearValidate();
    ruleFormRef.value.resetFields();
    emits("changeAddVi", false);
  }


};
//记录详情
function seeInfo(row) {
  rowid.value = row.id;
  addplanShow.value = true
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 70vh !important;
}

.fj {
  .el-form {
    padding: 10px;
    margin-top: 10px;
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .from_fix {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: 10px;

    // .el-form-item--default .el-form-item__content {
    //   flex-wrap: nowrap !important;
    // }

    .el-input {
      width: 100%;
    }
  }
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.txbj {
  display: flex;
  justify-content: space-between;
}

.config {
  .el-form {
    padding: 10px 40px;
    margin-top: 10px;
    display: block;
    // flex-wrap: wrap;
    // justify-content: space-between;
  }

  .el-form-item {
    text-align: center;
  }
}

.pxdx_box {
  width: 500px;
}

.titleBox {
  align-items: center;
  margin: 0;
  padding: 0;
  height: 60px;
  border: 1px solid rgb(32, 75, 54);
  padding: 20px;
}

.form>div {
  position: relative;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;

  div {
    display: flex;
    align-items: center;

    .el-select {
      width: 65%;
    }
  }
}

.el-input {
  width: 75%;
}

.two .el-input {
  width: 65%;
}

.three {
  justify-content: flex-start !important;

  .el-select {
    width: 15%;
  }
}

.four {
  display: flex;
  align-items: center;

  span {
    width: 5%;
  }

  .el-textarea__inner {
    width: 95%;
  }
}

.group {
  margin-top: 50px;
  // background-color: red;
  position: relative;
}

.fj {
  margin-top: 50px;
  width: 100%;

  .content {
    width: 100%;
    display: flex;
    padding: 20px;

    div {
      display: flex;
      width: 85%;
      align-items: center;
    }

    justify-content: space-between;
  }
}

.jc {
  margin-top: 50px;
}

.count-container .count-title {
  display: inline-block;
  width: 6.5em;
  text-align: right
}

.el-form-item__content {
  flex-wrap: nowrap;
}

.el-collapse {
  border-color: var(--el-color-primary);
  height: 460px;
}

::v-deep .el-collapse-item__header {
  border-bottom-color: var(--el-color-primary);
}

::v-deep .el-collapse-item__header.is-active {
  border-bottom-color: transparent;
}
</style>
