<!--
 * @Author: ysh
 * @Date: 2025-02-27 10:43:04
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-06-25 09:53:56
-->
<template>
  <view class="container">
    <!-- 列表标题 -->
    <view class="list-header">
      <text class="header-item">开支项目</text>
      <text class="header-item amount">申请金额</text>
    </view>

    <!-- 数据列表 -->
    <view class="list-box" v-for="(item, index) in detailList" :key="item.borrowDetailId">
      <view class="indexs">
        <text>{{ index + 1 }}</text>
      </view>
      <view class="list-item">
        <view class="item-left">
          <text class="item-title">{{ item.borrowItem }}</text>
          <text class="item-sub">
            ￥{{ item.price }} × {{ item.quantity }}{{ item.unit }}
          </text>
        </view>
        <view class="item-right">
          <text class="total-amount">￥{{ item.applyAmount }}</text>
        </view>
      </view>
      <uv-divider :dashed="true" v-if="taskName != '借款申请' && taskName != '部门审核' && taskName != '党工团审核'"></uv-divider>
      <view class="list-item" v-if="taskName != '借款申请' && taskName != '部门审核' && taskName != '党工团审核'">
        <view class="item-left">
          <text style="color:#398ade;padding-left: 10rpx;">分管审核金额</text>
        </view>
        <view class="item-right">
          <uni-easyinput type="number" v-model="item.managerAmount" placeholder="请输入审核金额" v-if="taskName == '分管审核'"
            @blur="editManagerAmount(detailList)" />
          <text class="mg-amount" v-else>￥{{ item.managerAmount }}</text>
        </view>
      </view>
      <view class="box-button" v-if="taskName == '借款申请'">
        <u-button size="normal" icon="edit-pen" @click="editItem(item)">修改</u-button>
        <u-button size="normal" icon="trash" @click="deleteItem(item)">删除</u-button>
      </view>
    </view>
    <u-button type="primary" @click="showAddPopup = true" v-if="taskName == '借款申请'">+ 新增借款项</u-button>
    <!-- 借款弹窗 -->
    <view v-if="showAddPopup" class="add-popup">
      <view class="popup-content">
        <text class="popup-title">新增借款项</text>
        <uni-forms ref="form" :modelValue="newItem" :rules="rules" label-position="top" label-width="150">
          <uni-forms-item label="开支项目" name="borrowItem" required class="form-item">
            <uni-data-select v-model="newItem.borrowItem" :localdata="dictsList" placeholder="请选择开支项目"
              @change="handleExpenseChange" v-if="borrowUsage == '0'" />
            <uni-easyinput v-model="newItem.borrowItem" placeholder="请输入开支项目" v-else />
          </uni-forms-item>
          <uni-forms-item label="单位" name="unit" required class="form-item">
            <uni-easyinput v-model="newItem.unit" placeholder="请输入单位" />
          </uni-forms-item>
          <uni-forms-item label="单价" name="price" required class="form-item">
            <uni-easyinput type="number" v-model="newItem.price" placeholder="请输入单价" />
          </uni-forms-item>
          <uni-forms-item label="数量" name="quantity" required class="form-item">
            <uni-easyinput type="number" v-model="newItem.quantity" placeholder="请输入数量" />
          </uni-forms-item>
          <uni-forms-item label="合计">
            <text>{{ getTotal() }}</text>
          </uni-forms-item>
          <view class="popup-buttons">
            <u-button style="margin-right: 10px;" @click="cancelAdd">取消</u-button>
            <u-button type="primary" class="confirm" @click="confirmAdd" v-if="!isModify">确认添加</u-button>
            <u-button type="primary" class="confirm" @click="confirmAdd" v-else>确认修改</u-button>
          </view>
        </uni-forms>
      </view>
    </view>
    <!-- 新增开支项字典弹窗 -->
    <view class="new-expense-popup" v-if="openNewExpense">
      <view class="popup-content">
        <text class="popup-title">新增开支项</text>
        <uni-easyinput v-model="newExpenseName" placeholder="请输入开支名称" />
        <view class="popup-buttons">
          <u-button style="margin-right: 10px;" @click="openNewExpense = false">取消</u-button>
          <u-button type="primary" class="confirm" @click="addNewExpense">确认添加</u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { listBorrowDetail, addBorrowDetail, updateBorrowDetail, delBorrowDetail, delBorrowDetailByDetailId } from "@/api/oa/borrow/borrowDetail";
import uButton from '../../../uni_modules/uview-ui/components/u-button/u-button.vue';
import { addData, getDicts } from "@/api/system/dict/data";
export default {
  components: { uButton },
  props: {
    borrowId: String,
    taskName: String,
    borrowUsage: String,
  },
  data() {
    return {
      detailList: [],
      showAddPopup: false,
      newItem: {
        borrowItem: '',
        unit: '',
        price: '',
        quantity: '',
        applyAmount: 0
      },
      rules: {
        borrowItem: {
          rules: [{
            required: true,
            errorMessage: '请填写开支项目',
          },]
        },
        unit: {
          rules: [{
            required: true,
            errorMessage: '请填写单位',
          },]
        },
        price: {
          rules: [{
            required: true,
            errorMessage: '请填写单价',
          },]
        },
        quantity: {
          rules: [{
            required: true,
            errorMessage: '请填写数量',
          },]
        },
      },
      errorMessage: '',
      isModify: false,
      dictsList: [], //开支项字典
      openNewExpense: false, //新增开支项字典弹窗
      newExpenseName: '', //新增开支项名称
    }
  },
  created() {
    this.initList();
    this.initDict();
  },
  watch: {
    borrowId() {
      this.initList();
    },
    detailList(newval) {
      this.getAomunt(newval)
    }
  },
  methods: {
    initList() {
      listBorrowDetail({ pageSize: 999, borrowId: this.borrowId }).then(res => {
        if (res.rows.length != 0) {
          this.detailList = res.rows
          if (!this.detailList[0].managerAmount) {
            this.detailList.forEach(item => {
              item.managerAmount = item.applyAmount;
            });
            this.editManagerAmount(this.detailList);
          }
        }
      });
    },
    initDict() {
      getDicts('cmc_borrow_expense').then(res => {
        this.dictsList = res.data.map(item => ({
          value: item.dictValue,
          text: item.dictLabel
        }))
        // this.dictsList.push({
        //   value: 'newExpense',
        //   text: '+新增更多开支项...'
        // })
      })
    },
    handleExpenseChange(value) {
      if (value == 'newExpense') {
        this.openNewExpense = true;
      }
    },
    addNewExpense() {
      if (this.newExpenseName == '') {
        this.$modal.msgError('请输入开支名称');
        return;
      }
      let length = this.dictsList.length;
      let newExpenseForm = {
        dictType: 'cmc_borrow_expense',
        dictLabel: this.newExpenseName,
        dictValue: this.newExpenseName,
        listClass: 'default',
        dictSort: length
      }
      addData(newExpenseForm).then(res => {
        this.$modal.msgSuccess('新增成功');
        this.openNewExpense = false;
        this.newItem.borrowItem = this.newExpenseName;
        this.newExpenseName = '';
        this.initDict();
      })
    },
    // 确认添加
    confirmAdd() {
      const borrowId = this.borrowId
      this.$refs.form.validate().then(async res => {
        this.newItem.applyAmount = this.getTotal();
        this.newItem.managerAmount = this.getTotal();
        if (this.isModify) {
          await updateBorrowDetail(this.newItem);
        } else {
          this.newItem.borrowId = borrowId;
          await addBorrowDetail(this.newItem);
        }
        this.clearForm()
        this.showAddPopup = false
        this.initList();
        this.$modal.msgSuccess('操作成功');
      }).catch(err => {
        console.log('表单错误信息：', err);
      })
    },
    // 清空表单
    clearForm() {
      this.newItem = {
        borrowItem: '',
        unit: '',
        price: '',
        quantity: '',
        applyAmount: 0
      }
    },

    // 取消添加
    cancelAdd() {
      this.clearForm()
      this.showAddPopup = false
    },
    getTotal() {
      return (Number(this.newItem.price) * Number(this.newItem.quantity)).toFixed(2)
    },
    deleteItem(item) {
      this.$modal.confirm('是否删除开支项目为' + item.borrowItem + '的项？').then(() => {
        delBorrowDetailByDetailId(item.borrowDetailId).then(res => {
          this.$modal.msgSuccess(res.msg);
          this.initList();
        })
      })

    },
    editItem(item) {
      this.newItem = item;
      this.isModify = true;
      this.showAddPopup = true;
    },
    getAomunt(list) {
      let sum = list.reduce((sum, item) => sum + Number(item.applyAmount), 0);
      let managerSum = list.reduce((sum, item) => sum + Number(item.managerAmount), 0);
      this.$emit('getApplyAmount', sum);
      this.$emit('getManagerAmount', managerSum);
    },
    async editManagerAmount(list) {
      this.getAomunt(list);
      for (let item of list) {
        await updateBorrowDetail(item);
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx 30rpx;
  background-color: #f8f8f8;
}

/* 列表标题样式 */
.list-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  font-weight: bold;
  border-bottom: 1rpx solid #eee;
}

.list-box {
  margin-bottom: 20rpx;
  padding: 30rpx 10rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .indexs {
    font-size: 25rpx;
    height: 30rpx;
    position: relative;

    text {
      display: block;
      position: absolute;
      right: 10rpx;
      width: 32rpx;
      height: 32rpx;
      text-align: center;
    }
  }

  .box-button {
    display: flex;
    padding: 10rpx;

  }
}

/* 列表项样式 */
.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-left {
  flex: 1;
}

.item-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  padding-left: 10rpx;
}

.item-sub {
  font-size: 26rpx;
  color: #999;
  padding-left: 10rpx;
}

.total-amount {
  font-size: 30rpx;
  color: #f1a532;
  font-weight: bold;
  padding-right: 30rpx;
}

.mg-amount {
  font-size: 30rpx;
  color: #398ade;
  font-weight: bold;
  padding-right: 30rpx;
}

.delete {
  font-size: 30rpx;
  color: #ff6a6c;
  font-weight: bold;
}

.edit {
  font-size: 30rpx;
  color: #3c9cff;
  font-weight: bold;
  padding-right: 20rpx;
}

/* 金额列对齐 */
.amount {
  min-width: 100rpx;
  padding-right: 20rpx;
}


.item-right {
  flex: 1;
  min-width: 200rpx;
  text-align: right;
}



.add-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.popup-content {
  background-color: white;
  width: 600rpx;
  padding: 40rpx;
  border-radius: 20rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 40rpx;
}

.popup-buttons {
  display: flex;
}

.new-expense-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
</style>