<!--添加基础资料-->
<template>
  <ContainerTit class="AddApplyReceipt">
    <div style="position: relative">
      <div class="btn-top-div">
        <el-button
          :loading="loading"
          :disabled="isLook || isEdit"
          @click="delData(1)"
        >
          清除暂存
        </el-button>
        <el-button
          :loading="loading"
          :disabled="isLook || isEdit"
          @click="temData"
        >
          暂存
        </el-button>
        <el-button
          v-if="!isLook"
          type="primary"
          :loading="loading"
          @click="addData"
        >
          保存并提交
        </el-button>
      </div>
    </div>
    <el-form
      ref="base_form"
      label-width="120px"
      :model="form"
      size="small"
      :rules="rules"
      :disabled="isLook"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane
          label="新增收款申请单"
          name="one"
          style="position: relative"
        >
          <el-row style="padding-bottom: 13px">
            <el-col :span="24">
              <p
                style="padding-left: 20px"
                class="order_midden_left_text el-icon-arrow-right"
              >
                收款申请信息
              </p>
            </el-col>
            <el-col class="form" :span="6">
              <el-form-item
                label="收款单位"
                prop="customerName"
                style="min-width: 420px"
              >
                <SelectCustomer
                  v-model="form.customerName"
                  :clearable="false"
                  width="180"
                  @change="customerSel"
                />
                <el-button
                  size="mini"
                  type="text"
                  @click="$router.push('/Customer/CustomerAdmin/AddCustomer')"
                >
                  【新建客户】
                </el-button>
              </el-form-item>
            </el-col>
            <el-col class="form" :span="6">
              <el-form-item
                label="所属店铺"
                prop="shopId"
                style="min-width: 420px"
              >
                <SelectShop
                  v-model="form.shopId"
                  width="210"
                  :clearable="false"
                  placeholder="选择商铺"
                  @change="selShop"
                />
                <el-button
                  size="mini"
                  type="text"
                  @click="$router.push('/SystemSettings/liansuoguanli/AddShop')"
                >
                  【新建商铺】
                </el-button>
              </el-form-item>
            </el-col>
            <el-col class="form" :span="6">
              <el-form-item label="当前应收" prop="money">
                <el-input
                  v-model="form.receivable"
                  disabled
                  style="width: 210px"
                  placeholder="不可编辑"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col class="form" :span="6">
              <el-form-item label="收款人">
                {{ form.operatorName }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div class="order_bottom">
        <p class="text">收款单明细</p>
        <el-table :data="form.receiptRequisitionAccountDate">
          <el-table-column
            type="index"
            label="序号"
            min-width="60"
            align="center"
          ></el-table-column>
          <el-table-column prop="money" label="收款金额" min-width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.collectionAmount"
                :controls="false"
                placeholder="收款金额"
                size="small"
                style="width: 100%"
                @change="moneyChange(scope.$index)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="优惠金额" min-width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.preferentialAmount"
                :controls="false"
                placeholder="优惠金额"
                style="width: 100%"
                size="small"
                :min="0"
                :max="Number(scope.row.collectionAmount || 1)"
                @change="moneyChange(scope.$index)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="实际收款金额" min-width="120" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.actualAmount"
                :controls="false"
                placeholder="实际收款金额"
                style="width: 100%"
                size="small"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="结算账户" min-width="160">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.accountName"
                readonly
                size="small"
                placeholder="结算账户"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="openAccount(scope.$index)"
                ></i>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                style="width: 100%"
                size="small"
                placeholder="备注"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="操作"
            width="140"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                :disabled="form.receiptRequisitionAccountDate.length === 1"
                size="mini"
                type="text"
                @click="delAccount(scope.$index)"
              >
                删除
              </el-button>
              <!--              <el-button size="mini" type="text" @click="addAccount">-->
              <!--                新增-->
              <!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <div class="table-b-div">
          <div class="table-b-div-cont" @click="addAccount">
            <el-button type="text" size="mini" @click="addAccount">
              <i class="el-icon-plus"></i>
              新增
            </el-button>
          </div>
        </div>
        <div class="Enunciate">
          <div class="Enunciate_cont clearfix">
            <div class="float_left">
              <span>收款总额:</span>
              <span>
                {{ $_common.formattedNumber(totalCollectionAmount) }}
              </span>
              <span style="margin: 0 10px"></span>
              <span>优惠总额:</span>
              <span>
                {{ $_common.formattedNumber(totalPreferentialAmount) }}
              </span>
              <span style="margin: 0 10px"></span>
              <span>实收总额:</span>
              <span>
                {{ $_common.formattedNumber(totalActualAmount) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <AccountType
      v-if="account_show"
      :is-check="false"
      :is-show="account_show"
      :shop-id="form.shopId"
      @cancel="account_show = false"
      @confirm="accountsel"
    />
  </ContainerTit>
</template>

<script>
  import { getCustomerInfo } from "@/api/Customer";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import {
    getReceiptRequisitionInfo,
    addReceiptRequisition,
    editReceiptRequisition,
  } from "@/api/Finance";
  import AccountType from "../AccountType";
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  import { mapGetters } from "vuex";
  import { getAllPayment } from "@/api/System";
  export default {
    name: "AddApplyReceipt",
    components: {
      SelectCustomer,
      AccountType,
      SelectShop,
    },
    data() {
      const validateName = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择收款单位"));
        } else {
          callback();
        }
      };
      return {
        loading: false,
        pay_type_list: [],
        form: {
          customerId: "",
          customerName: "",
          operatorId: "",
          operatorName: "",
          receivable: "",
          shopId: "",
          shopName: "",
          receiptRequisitionAccountDate: [
            {
              collectionAmount: "",
              preferentialAmount: "",
              actualAmount: "",
              // settlementMethod: "",
              remark: "",
              accountName: "",
              accountId: "",
            },
          ],
        },
        rules: {
          customerName: [{ required: true, validator: validateName }],
        },
        account_id: "",
        isLook: false,
        isEdit: false,
        show_shop: false,
        pageName: "",
        account_show: false,
        account_index: "",
        delReceiptRequisitionAccountDate: [],
        flag: false,
        activeName: "one",
      };
    },
    computed: {
      ...mapGetters({
        userCenterId: "MUser/userCenterId",
      }),
      // 收款总额
      totalCollectionAmount() {
        if (!this.form.receiptRequisitionAccountDate.length) {
          return 0;
        } else if (this.form.receiptRequisitionAccountDate.length === 1) {
          return Number(
            this.form.receiptRequisitionAccountDate[0].collectionAmount
          );
        } else {
          let sum = 0;
          this.form.receiptRequisitionAccountDate.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.collectionAmount) || 0);
          });
          return sum;
        }
      },
      // 优惠总额
      totalPreferentialAmount() {
        if (!this.form.receiptRequisitionAccountDate.length) {
          return 0;
        } else if (this.form.receiptRequisitionAccountDate.length === 1) {
          return Number(
            this.form.receiptRequisitionAccountDate[0].preferentialAmount
          );
        } else {
          let sum = 0;
          this.form.receiptRequisitionAccountDate.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.preferentialAmount) || 0);
          });
          return sum;
        }
      },
      // 实收总额
      totalActualAmount() {
        if (!this.form.receiptRequisitionAccountDate.length) {
          return 0;
        } else if (this.form.receiptRequisitionAccountDate.length === 1) {
          return Number(
            this.form.receiptRequisitionAccountDate[0].actualAmount
          );
        } else {
          let sum = 0;
          this.form.receiptRequisitionAccountDate.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.actualAmount) || 0);
          });
          return sum;
        }
      },
    },
    async created() {
      this.isLook = this.$route.path.indexOf("ApplyReceiptInfo") > -1;
      this.isEdit = this.$route.path.indexOf("editApplyReceipt") > -1;
      this.pageName = this.$route.name;
      // 收款人默认当前账户
      this.form.operatorName = this.userName;
      this.form.operatorId = this.userCenterId;
      if (this.$route.params.id) {
        this.account_id = this.$route.params.id;
        //  获取详情 收款单详情
        await this.getReceiptRequisitionInfo();
      } else {
        await this.getPauseSave(); // 获取暂存数据
      }
      if (this.$route.query.customerId) {
        await this.getCustomerInfo(this.$route.query.customerId);
      }
      await this.getAllPayment();
    },
    methods: {
      // 获取客户详情
      async getCustomerInfo(id) {
        const { data } = await getCustomerInfo(id);
        this.form.receivable = data.money || 0;
        this.form.customerId = data.id;
        this.form.customerName = data.name;
      },
      //  收款申请单详情
      async getReceiptRequisitionInfo() {
        const { data } = await getReceiptRequisitionInfo(this.account_id);
        this.form = {
          ...data,
          receiptRequisitionAccountDate: data.receiptRequisitionAccountDate.map(
            (item) => {
              return {
                ...item,
                // settlementMethod: item.settlementMethod,
              };
            }
          ),
        };
      },
      // 暂存数据
      async temData() {
        const params = {
          ...this.form,
          totalCollectionAmount: this.totalCollectionAmount,
          totalPreferentialAmount: this.totalPreferentialAmount,
          totalActualAmount: this.totalActualAmount,
        };
        try {
          this.loading = true;
          const data = await addPauseSave({
            data: params,
            key: this.pageName,
          });
          this.loading = false;

          this.$message({
            message: "暂存成功",
            type: "success",
          });
          this.$closeCurrentGoEdit("/Finance/Receivable/ApplyReceipt");
        } finally {
          this.loading = false;
        }
      },
      // 清除暂存
      async delData(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Finance/Receivable/ApplyReceipt");
        }
      },
      //  添加
      async addData() {
        this.$refs["base_form"].validate(async (valid) => {
          if (valid) {
            if (this.flag) {
              this.form.receiptRequisitionAccountDate = [
                ...this.form.receiptRequisitionAccountDate,
                ...this.delReceiptRequisitionAccountDate,
              ];
            }
            const params = {
              ...this.form,
              totalCollectionAmount: this.totalCollectionAmount,
              totalPreferentialAmount: this.totalPreferentialAmount,
              totalActualAmount: this.totalActualAmount,
            };
            let isSub = true;
            for (let i in this.form.receiptRequisitionAccountDate) {
              let item = this.form.receiptRequisitionAccountDate[i];
              if (!item.collectionAmount) {
                isSub = false;
                this.$message.warning("请输入收款金额");
                break;
              }
              // if (!item.settlementMethod) {
              //   isSub = false;
              //   this.$message.warning("请选择结算方式");
              //   break;
              // }
            }
            if (!isSub) {
              return;
            }
            try {
              this.loading = true;
              if (this.account_id) {
                const data = await editReceiptRequisition(
                  this.account_id,
                  params
                );
              } else {
                const data = await addReceiptRequisition(params);
              }
              this.loading = false;
              this.$message({
                message: "提交成功",
                type: "success",
              });
              this.$closeCurrentGoEdit("/Finance/Receivable/ApplyReceipt");
            } finally {
              this.loading = false;
            }
          }
        });
      },
      //  获取暂存数据
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = {
          ...data,
          receiptRequisitionAccountDate: data.receiptRequisitionAccountDate.map(
            (item) => {
              return {
                ...item,
                // settlementMethod: parseInt(item.settlementMethod),
              };
            }
          ),
        };
      },
      addAccount() {
        this.form.receiptRequisitionAccountDate.push({
          collectionAmount: "",
          preferentialAmount: "",
          actualAmount: "",
          // settlementMethod: "",
          remark: "",
        });
      },
      delAccount(index) {
        if (this.account_id) {
          this.flag = true;
          // this.delReceiptRequisitionAccountDate = this.$_common.deepClone(
          //   this.form.receiptRequisitionAccountDate
          // );
          if (
            this.form.receiptRequisitionAccountDate[index].actualAmount &&
            this.form.receiptRequisitionAccountDate[index].accountId
            // this.form.receiptRequisitionAccountDate[index].settlementMethod
          ) {
            this.form.receiptRequisitionAccountDate[index].deleteStatus = 4;
            this.delReceiptRequisitionAccountDate.push(
              this.form.receiptRequisitionAccountDate[index]
            );
          }
        }
        this.form.receiptRequisitionAccountDate.splice(index, 1);
      },
      //  客户弹窗
      customerSel(val, row) {
        this.form.customerId = row[0].id;
        this.form.receivable = row[0].money;
      },
      moneyChange(index) {
        const target = this.$_common.deepClone(
          this.form.receiptRequisitionAccountDate
        );
        let collectionAmount = target[index].collectionAmount;
        let preferentialAmount = target[index].preferentialAmount;
        target[index].actualAmount = this.$NP.minus(
          collectionAmount,
          preferentialAmount
        );
        this.form.receiptRequisitionAccountDate = target;
      },
      openAccount(index) {
        this.account_index = index;
        if (!this.form.shopId) {
          this.$message.warning("请选择商铺");
          return;
        }
        this.account_show = true;
      },
      // 获取支付方式
      async getAllPayment() {
        const data = await getAllPayment({
          page: 1,
          pageSize: 9,
        });
        this.pay_type_list = data.data;
      },
      // 选择商铺
      selShop(val, row) {
        this.form.shopName = row[0].name;
        this.form.shopId = row[0].id;
      },
      accountsel(val) {
        const target = this.$_common.deepClone(
          this.form.receiptRequisitionAccountDate
        );
        target[this.account_index].accountName = val[0].name;
        target[this.account_index].accountId = val[0].id;
        this.form.receiptRequisitionAccountDate = target;
        // this.form.receiptRequisitionAccountDate[this.account_index].accountId =
        //   val[0].id;
        // this.form.receiptRequisitionAccountDate[
        //   this.account_index
        // ].accountName = val[0].name;
      },
    },
  };
</script>
<style lang="scss" scoped>
  .price-div {
    padding-top: 10px;
    .de_val {
      color: $base-color-red;
      padding-right: 20px;
    }
  }
  .creat-custorm {
    color: #1890ff;
    font-size: 12px;
  }
  .order_bottom {
    border-top: 16px solid #f6f8f9;
    width: 100%;
    background-color: #ffffff;
    border-radius: 3px;
    .text {
      font-size: 16px;
      font-weight: 600;
      color: #2d405e;
      line-height: 64px;
      padding: 0px 24px;
    }
  }
  .order_midden_left_text {
    font-weight: bold;
    font-size: 16px;
    margin: 0 0 27px 0;
  }
  .table-b-div {
    height: 80px;
    width: 100%;
    padding: 16px 24px 32px 25px;
    border: 1px solid #ebeef5;
    text-align: center;
    line-height: 40px;
    border-top: 0 none;
    cursor: pointer;
    .table-b-div-cont {
      border: 1px dashed #2153d4;
    }
  }
  .form {
    padding-left: 40px;
    font-size: 14px;
    margin-bottom: 19px;
    .form_left {
      margin-right: 32px;
      color: #62738e;
      font-weight: 400;
    }
    .form_right {
      color: #2d405e;
      font-weight: 500;
    }
  }
  .Enunciate {
    width: 100%;
    height: 96px;
    color: #fff;
    font-size: 16px;
    line-height: 40px;
    padding: 24px 24px 32px;
    .Enunciate_cont {
      background-color: #fa6400;
      border-radius: 3px;
      padding: 0 24px;
    }
  }
  .btn-top-div {
    position: absolute;
    right: 20px;
    top: 15px;
    z-index: 999;
  }
</style>
<style>
  .AddApplyReceipt {
    background-color: #fff;
  }
  .AddApplyReceipt .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddApplyReceipt .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddApplyReceipt .el-tabs__nav {
    margin-left: 24px;
  }
</style>
