<template>
  <div class="app-container">
    <div style="display: flex; gap: 20px;">
      <el-select v-model="queryParams.signingCompany" placeholder="请选择签约公司" @change="getList">
        <el-option :value="undefined" label="全部" key="all" />
        <el-option v-for="dict in dict.type.signing_company" :key="dict.value" :label="dict.label"
          :value="dict.value"></el-option>
        <el-option value="100" label="王瑞春账户" :key="100" />
      </el-select>

      <el-button type="primary" @click="handleClick">新增</el-button>
      <el-button type="primary" @click="getList">刷新</el-button>
    </div>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="出账名称" align="left" prop="financeTitle" />
      <el-table-column label="经手人" align="center" prop="financeParties" />
      <el-table-column label="签约公司" align="center" prop="signingCompany">
        <template slot-scope="scope">
          <span v-if="scope.row.signingCompany == '100'"">王瑞春账户</span>
          <dict-tag v-else :options="dict.type.signing_company" :value="scope.row.signingCompany" />
        </template>
      </el-table-column>
      <el-table-column label="支出类型" align="center" prop="outType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_out_finance" :value="scope.row.outType" />
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center">
        <template slot-scope="scope">
          {{'￥' + scope.row.detailList.reduce((acc, curr) => acc + Number(curr.price), 0)}}
        </template>
      </el-table-column>
      <el-table-column label="支付类型" align="center" prop="payType" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_pay_type" :value="scope.row.payType" />
        </template>
      </el-table-column>
      <el-table-column label="交易日期" align="center" prop="financeTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.financeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" width="80" />
      <el-table-column label="开票状态" align="center" prop="makeTime" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.makeTime == null || (scope.row.makePrice == null || scope.row.makePrice == '')"
            style="color: #cccccc">未开票</span>
          <span v-else style="color: #1ab394">已开票</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark">
        <template slot-scope="scope">
          <span>{{ scope.row.remark == null || scope.row.remark == '' ? "暂无" : scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleLook(scope.row)">查看
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="financeUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 出入账提交信息弹出层 -->
    <el-dialog :title="title" :visible.sync="open" width="76%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" v-loading="formLoading" label-width="120px">
        <el-row>
          <el-col :span="16">
            <el-form-item :label="financeType == 1 ? '入账名称' : '出账名称'" prop="financeTitle">
              <el-input v-model="form.financeTitle" placeholder="请输入账务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易时间" prop="financeTime">
              <el-date-picker clearable v-model="form.financeTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择交易时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item :label="financeType == 1 ? '付款方' : '经手人'" prop="financeParties">
              <el-input v-model="form.financeParties" placeholder="请输入经手人/付款方" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付类型" prop="payType">
              <el-select v-model="form.payType" placeholder="请选择支付类型">
                <el-option v-for="dict in dict.type.sys_pay_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约公司" prop="signingCompany">
              <el-select v-model="form.signingCompany" placeholder="请选择签约公司">
                <el-option v-for="dict in dict.type.signing_company" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
                <el-option value="100" label="王瑞春账户" :key="100" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支出用途" prop="costCategory">
              <el-select v-model="form.outType" placeholder="请选择支出用途">
                <el-option v-for="dict in dict.type.oa_out_finance" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票比例" prop="makeRatio">
              <el-input v-model="form.makeRatio" placeholder="请输入开票比例" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票金额" prop="makePrice">
              <el-input v-model="form.makePrice" placeholder="请输入开票金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票时间" prop="makeTime">
              <el-input v-model="form.makeTime" placeholder="请输入开票金额" />

            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票情况说明" prop="makeExplain">
              <el-input v-model="form.makeExplain" placeholder="请输入开票情况说明" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" prop="accessory">
              <file-upload v-model="form.accessory" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">明细</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAddDetailList">添加明细
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" plain @click="handleDeleteDetailList">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="detailList" :row-class-name="rowDetailListIndex"
          @selection-change="handleDetailListSelectionChange" ref="detailList">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="明细名称" prop="detailTitle">
            <template slot-scope="scope">
              <el-input v-model="scope.row.detailTitle" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="金额(单位：元)" prop="price">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入金额" οnkeyup="value=value.replace(/[^\d]/g,'')"
                @input="updateBigPrice(scope.$index, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="大写金额(零壹贰叁肆伍陆柒捌玖万仟佰拾亿元角分)" prop="bigPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.bigPrice" placeholder="请输入大写金额" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看账目明细-->
    <el-dialog :title="title" :visible.sync="openLook" width="60%" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item :label="type == 1 ? '入账名称' : '出账名称'" :span="3" :labelStyle="lableBg">
          {{ form.financeTitle }}
        </el-descriptions-item>
        <el-descriptions-item label="交易时间" :span="1" :labelStyle="lableBg">
          {{ parseTime(form.financeTime, '{y}-{m}-{d}') }}
        </el-descriptions-item>
        <el-descriptions-item :label="type == 1 ? '付款方' : '经手人'" :span="1" :labelStyle="lableBg">
          {{ form.financeParties }}
        </el-descriptions-item>
        <el-descriptions-item label="支付类型" :span="1" :labelStyle="lableBg">
          <dict-tag :options="dict.type.sys_pay_type" :value="form.payType" />
        </el-descriptions-item>
        <el-descriptions-item label="开票状态" :span="2" :labelStyle="lableBg">
          <span v-if="form.makeTime == null || form.makePrice == null" style="color: #cccccc">未开票</span>
          <span v-else style="color: #1ab394">
            已开票, 开票金额：¥ {{ form.makePrice }},
            开票比例：{{ form.makeRatio == null ? '未填' : form.makeRatio }},
            开票时间：{{ form.makeTime }},
            开票情况说明：{{ form.makeExplain == null ? '未填' : form.makeExplain }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建者" :span="1" :labelStyle="lableBg">
          {{ form.createBy }}
        </el-descriptions-item>
        <el-descriptions-item label="附件" :span="3" :labelStyle="lableBg">
          <!--附件-->
          <template>
            <file-preview v-model="form.accessory" />
          </template>

          <!--附件-->
        </el-descriptions-item>
      </el-descriptions>
      <el-table :data="detailList" style="margin-top: 30px;">
        <el-table-column label="明细名称" prop="detailTitle">
          <template slot-scope="scope">
            <div>{{ scope.row.detailTitle }}</div>
          </template>
        </el-table-column>
        <el-table-column label="金额(单位：元)" prop="price">
          <template slot-scope="scope">
            <div>¥{{ scope.row.price }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="大写金额" prop="bigPrice">
          <template slot-scope="scope">
            <div>{{ scope.row.bigPrice }}</div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="备注" prop="remark" >
                  <template slot-scope="scope">
                    <div>{{scope.row.remark}}</div>
                  </template>
                </el-table-column>-->
      </el-table>
      <h2 class="cl3">{{ type == 1 ? '入账合计' : '出账合计' }}：¥{{ priceSum }}元</h2>
    </el-dialog>
  </div>
</template>

<script>
import { addFinance, getFinance, listFinance, updateFinance } from "@/api/oa/finance";
import FilePreview from "@/components/FilePreview";
import { numberToCNY } from "@/utils/currencyFormatter";

export default {
  dicts: ['sys_project_type', 'sys_project_status', 'sys_pay_type', 'signing_company', 'oa_out_finance'],
  components: {
    FilePreview,
  },
  data () {
    return {
      list: [],
      loading: false,
      total: 0,
      lableBg: "background: #f0f9eb; width:150px; text-align: center;",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: 0,
        financeType: 0,
        signingCompany: undefined, // 默认选中全部
      },
      priceSum: 0,
      buttonLoading: false,
      //入账弹出层标题
      title: '',
      //出入账弹出层
      open: false,
      type: '',
      //表单
      form: {},
      detailList: [],
      formLoading: false,
      financeType: '0',  // 0 出账 1 入账
      // 表单校验
      rules: {
        financeTitle: [
          { required: true, message: "账务名称不能为空", trigger: "blur" }
        ],
        financeParties: [
          { required: true, message: "经手人/付款方不能为空", trigger: "blur" }
        ],
        financeType: [
          { required: true, message: "进出账类型不能为空", trigger: "blur" }
        ]
      },
      openLook: false,
    }
  },
  methods: {
    getList () {
      this.loading = true;
      listFinance(this.queryParams).then(res => {
        this.list = res.rows;
        this.total = res.total;
        this.loading = false;
      })
    },
    /** 出入账明细序号 */
    rowDetailListIndex ({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    isDecimal (n, len) {
      return new RegExp("^\\d+(\\.\\d{1," + len + "})?$").test(n);
    },
    /** 复选框选中数据 */
    handleDetailListSelectionChange (selection) {
      this.checkedDetailList = selection.map(item => item.index)
    },
    updateBigPrice (index, row) {

      if (row.price !== '') {
        row.bigPrice = numberToCNY(parseFloat(row.price) || 0);
      } else {
        row.bigPrice = ''; // 如果价格为空，则大写金额也清空
      }
    },
    /**查看按钮操作**/
    handleLook (row) {
      this.type = row.financeType
      this.loading = true;
      this.title = "查看账目";
      this.reset();
      const financeId = row.financeId || this.ids
      getFinance(financeId).then(response => {
        this.loading = false;
        this.form = response.data;

        this.detailList = response.data.detailList;
        //核算求和
        this.detailPriceSum(response.data.detailList);
        this.openLook = true;

      });
    },
    /**
     * 求和
     * obj是列表数据
     * */
    detailPriceSum (obj) {
      if (obj.length > 0) {
        let sum = []
        obj.forEach((vo, key) => {
          sum.push(parseFloat(vo.price))
        })
        this.priceSum = sum.reduce((accumulator, currentValue) => accumulator + currentValue);
      }
    },
    financeUpdate (row) {
      /** 入账按钮操作 */
      this.reset();
      this.open = true;
      this.title = "提交出账信息";
      this.isRubbish = false;
      this.financeType = '0';
      this.form = row;
      this.detailList = row.detailList;
      if (this.detailList.length == 0) {
        this.handleAddDetailList()
      }
    },
    /** 出入账明细添加按钮操作 */
    handleAddDetailList () {
      let obj = {};
      obj.detailTitle = "";
      obj.price = "";
      obj.remark = "";
      if (!this.detailList) {
        this.detailList = [];
      }
      console.log(this.detailList)
      this.detailList.push(obj);
    },
    /** 出入账明细删除按钮操作 */
    handleDeleteDetailList () {
      if (this.checkedDetailList.length == 0) {
        this.$modal.msgError("请先选择要删除的出入账明细数据");
      } else {
        const detailList = this.detailList;
        const checkedDetailList = this.checkedDetailList;
        this.detailList = detailList.filter(function (item) {
          return checkedDetailList.indexOf(item.index) == -1
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const financeId = row.financeId;
      this.$modal.confirm('是否确认删除编号为"' + financeId + '"的数据项？').then(() => {
        this.loading = true;
        return delFinance(financeId);
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleClick () {
      this.handleAddRubbish({ signingCompany: this.queryParams.signingCompany })
    },
    handleAddRubbish ({ signingCompany }) {
      this.open = true;
      this.title = "提交出账信息";
      this.financeType = '0';
      this.form = {
        signingCompany,
        financeType: '0',
        financeId: undefined,
        financeTitle: undefined,
        financeParties: undefined,
        payType: undefined,
        financeTime: undefined,
        makeTime: undefined,
        makeRatio: undefined,
        makePrice: undefined,
        makeExplain: undefined,
        accessory: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        fileList: [],
      };
      this.detailList = [];
      this.handleAddDetailList()
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          try {
            this.buttonLoading = true;
            let arr = this.detailList;
            let boolValue = []
            arr.forEach((vo, i) => {
              let ii = i + 1
              if (vo.detailTitle == null || vo.detailTitle == undefined || vo.detailTitle == "") {
                this.$modal.msgWarning("第" + ii + "条明细名称不能为空！");
              } else if (vo.price == null || vo.price == undefined || vo.price == "") {
                this.$modal.msgWarning("第" + ii + "条明细金额不能为空,且必须是两位小数点数字！");
              } else if (vo.bigPrice == null || vo.bigPrice == undefined || vo.bigPrice == "") {
                this.$modal.msgWarning("第" + ii + "条明细大写金额不能为空！");
              } else {
                boolValue.push(1)
              }
            })

            if (arr.length == boolValue.length) {
              this.form.detailList = arr;
              if (this.form.financeId != null) {
                const response = await updateFinance(this.form);
                this.$modal.msgSuccess(response.msg);
                this.open = false;
              } else {
                this.form.financeType = this.financeType;
                await addFinance(this.form);
                this.$modal.msgSuccess("新增成功");
                this.open = false;
              }
              this.getList();
            }
          } finally {
            this.buttonLoading = false;
          }
        } else {
          console.log("验证失败")
        }
      })
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        financeId: undefined,
        projectId: undefined,
        financeTitle: undefined,
        financeParties: undefined,
        payType: undefined,
        financeType: undefined,
        financeTime: undefined,
        makeTime: undefined,
        makeRatio: undefined,
        makePrice: undefined,
        makeExplain: undefined,
        accessory: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        fileList: [],
        signingCompany: undefined
      };
      this.detailList = []
      this.resetForm("form");
    },
  },
  created () {
    this.getList();
  }
}
</script>