<!--新增退款单-->
<template>
  <ContainerTit class="AddRefundForm">
    <div style="position: relative">
      <div class="btn-top-div">
        <el-button
          v-if="!isLook"
          type="primary"
          :loading="loading"
          @click="addData(false)"
        >
          保存并提交
        </el-button>
      </div>
    </div>
    <el-form
      ref="base_form"
      label-width="120px"
      :model="form"
      size="small"
      :rules="rules"
      :disabled="auditStatus === 2"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="新增退款单" name="one">
          <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" style="margin-bottom: 0">
              <!--              <el-form-item label="业务类型" prop="financeTypeId">-->
              <!--                <el-select-->
              <!--                  v-model="form.financeTypeId"-->
              <!--                  style="width: 270px"-->
              <!--                  clearable-->
              <!--                  placeholder="选择类型"-->
              <!--                  @change="typeChange"-->
              <!--                >-->
              <!--                  <el-option-->
              <!--                    v-for="(item, index) in financeTypeList"-->
              <!--                    :key="index"-->
              <!--                    :label="item.name"-->
              <!--                    :value="item.id"-->
              <!--                  ></el-option>-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <el-form-item label="退款单位" prop="unitName">
                <!--                <el-select-->
                <!--                  v-model="form.type"-->
                <!--                  style="width: 90px; margin-right: 2px"-->
                <!--                  @change="change"-->
                <!--                >-->
                <!--                  <el-option label="客户" :value="5"></el-option>-->
                <!--                  <el-option label="供应商" :value="4"></el-option>-->
                <!--                </el-select>-->
                <SelectCustomer
                  v-if="type === '1'"
                  v-model="form.unitName"
                  :clearable="false"
                  width="210"
                  @change="unitSel"
                />
                <SelectSupplier
                  v-if="type === '2'"
                  v-model="form.unitName"
                  width="210"
                  @change="unitSel"
                />
              </el-form-item>
            </el-col>
            <el-col class="form" :span="6" style="margin-bottom: 0">
              <el-form-item
                label="所属店铺"
                prop="shopName"
                style="min-width: 42 0px"
              >
                <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" style="margin-bottom: 0">
              <el-form-item label="单据日期" prop="brandId">
                <template>
                  <div class="block">
                    <el-date-picker
                      v-model="form.refundTime"
                      style="width: 210px"
                      type="date"
                      placeholder="选择日期"
                      value-format="timestamp"
                    ></el-date-picker>
                  </div>
                </template>
              </el-form-item>
            </el-col>
            <el-col class="form" :span="6">
              <el-form-item label="制单人">
                {{ form.currentAccountName }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div class="order_bottom">
        <p class="text">退款单明细</p>
        <el-table :data="form.accountList">
          <el-table-column
            prop="accountNumber"
            label="结算账户"
            min-width="160"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.accountName"
                readonly
                style="width: 100%"
                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 prop="money" label="实际退款金额" min-width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.money"
                :controls="false"
                placeholder="退款金额"
                size="small"
                style="width: 100%"
                :min="0"
                @blur="moneyBlur"
              ></el-input-number>
            </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 label="结算方式" min-width="160">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.payWay"
                clearable
                size="small"
                placeholder="结算方式"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in pay_type_list"
                  :key="index"
                  :label="item.title"
                  :value="item.title"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>-->
          <el-table-column
            prop="remark"
            label="操作"
            width="140"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                :disabled="form.accountList.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>
      <div v-if="false" class="order_bottom">
        <p class="text">核销明细</p>
        <div class="Enunciate">
          <div class="Enunciate_cont clearfix">
            <div class="float_left">
              <span>
                未核销金额：{{ $_common.formattedNumber(offSetNotTotal) }}
              </span>
              <span style="margin: 0 20px">
                本次核销金额：{{ $_common.formattedNumber(offSetTotal) }}
              </span>
              <span>
                核销差额：{{
                  $_common.formattedNumber(offSetTotal - moneyTotal)
                }}
              </span>
            </div>
            <div class="float_right">
              <el-button size="mini" @click="offsetGet">自动核销</el-button>
            </div>
          </div>
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          ></el-table-column>
          <el-table-column
            prop="receiptTypeId"
            label="单据类型"
            min-width="100"
          >
            <template slot-scope="scope">
              {{
                scope.row.receiptTypeId === 6
                  ? "销售退货单"
                  : scope.row.receiptTypeId === 1
                  ? "销售订单"
                  : ""
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="no"
            label="单据编号"
            min-width="140"
          ></el-table-column>
          <el-table-column prop="address" label="单据日期" min-width="120">
            <template slot-scope="scope">
              {{ $_common.formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <!--            <el-table-column-->
          <!--              prop="address"-->
          <!--              label="退款到期日"-->
          <!--              min-width="120"-->
          <!--            ></el-table-column>-->
          <el-table-column label="金额" min-width="100">
            <template slot-scope="scope">
              {{ $_common.formattedNumber(scope.row.receiveMoney) }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="未核销金额" min-width="100">
            <template slot-scope="scope">
              {{ $_common.formattedNumber(scope.row.notOffsetMoney) }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="本次核销金额" min-width="100">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.offsetMoney"
                :controls="false"
                placeholder="本次核销金额"
                :max="Number(scope.row.notOffsetMoney)"
                style="width: 100%"
                size="small"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="sourceNo"
            label="销售订单号"
            min-width="100"
          >
            <template slot-scope="scope">
              <span class="click-div" @click="goOtherDetail(scope.row.orderId)">
                {{ scope.row.sourceNo }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="unitName"
            label="往来单位名称"
            min-width="100"
          ></el-table-column>
          <!--            <el-table-column-->
          <!--              prop="address"-->
          <!--              label="业务员"-->
          <!--              min-width="100"-->
          <!--            ></el-table-column>-->
          <!--            <el-table-column-->
          <!--              prop="address"-->
          <!--              label="备注"-->
          <!--              min-width="100"-->
          <!--            ></el-table-column>-->
          <!--            <el-table-column-->
          <!--              prop="address"-->
          <!--              label="期初预收"-->
          <!--              min-width="100"-->
          <!--            ></el-table-column>-->
        </el-table>
      </div>
    </el-form>
    <AccountType
      v-if="account_show"
      :shop-id="form.shopId"
      :is-show="account_show"
      @cancel="account_show = false"
      @confirm="accountsel"
    />
    <Receivable
      v-if="receivable_show"
      :id="form.unitId"
      :is-check="false"
      :is-show="receivable_show"
      @cancel="receivable_show = false"
      @confirm="receivablesel"
    />
  </ContainerTit>
</template>

<script>
  import Receivable from "@/component/Finance/Receivable";
  import AccountType from "../AccountType";
  import { getCustomerInfo } from "@/api/Customer";
  import SelectSupplier from "@/component/common/SelectSupplier.vue";
  import {
    getRefundInfo,
    addRefund,
    editRefund,
    getTempReceivedData,
    getAllReceive,
    getAllFinanceTypeNoPage,
  } from "@/api/Finance";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  import { getAllPayment } from "@/api/System";
  export default {
    name: "AddReceipt",
    components: {
      Receivable,
      AccountType,
      SelectCustomer,
      SelectShop,
      SelectSupplier,
    },
    data() {
      const validateName = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择退款单位"));
        } else {
          callback();
        }
      };
      const validateNo = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择原单据号"));
        } else {
          callback();
        }
      };
      const validateShopName = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择店铺"));
        } else {
          callback();
        }
      };
      const validateFinanceTypeId = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择业务类型"));
        } else {
          callback();
        }
      };
      return {
        auditStatus: 1,
        tableData: [],
        show_model: false,
        add_form: {
          name: "",
          link: "",
          isDefault: 4,
          enableStatus: 5,
        },
        add_rule: {
          name: [{ required: true, message: "请输入类型名称" }],
          link: [{ required: true, message: "请选择归属单据" }],
        },
        loading: false,
        account_index: 0,
        // financeType_list: [
        //   {
        //     label: "应收退款单",
        //     value: 1,
        //   },
        //   {
        //     label: "应付退款单",
        //     value: 2,
        //   },
        // ],
        code: "",
        account_show: false,
        receivable_show: false,
        no: "",
        form: {
          // type: 5,
          unitId: "",
          unitName: "",
          sourceNo: "",
          sourceNoMoney: "",
          currentAccountName: "",
          financeType: "销售退款",
          financeTypeId: 12,
          shopId: "",
          money: "",
          shopName: "",
          refundTime: "",
          createTime: "",
          accountList: [
            {
              accountId: "",
              accountNumber: "",
              accountName: "",
              money: "",
              discountMoney: "",
              finalMoney: "",
              payWay: "",
              remark: "",
            },
          ],
        },
        rules: {
          unitName: [{ required: true, validator: validateName }],
          sourceNo: [{ required: true, validator: validateNo }],
          shopName: [{ required: true, validator: validateShopName }],
          financeTypeId: [{ required: true, validator: validateFinanceTypeId }],
        },
        account_id: "",
        isLook: false,
        isEdit: false,
        show_shop: false,
        choose_data: [],
        check_money: 0, // 勾选后合计
        id: "",
        time: "",
        pay_type_list: [],
        financeTypeList: [
          { id: 11, name: "采购退款" },
          { id: 12, name: "销售退款" },
        ],
        type: "",
        activeName: "one",
      };
    },
    computed: {
      // 退款总金额
      moneyTotal() {
        if (!this.form.accountList.length) {
          return 0;
        } else if (this.form.accountList.length === 1) {
          return this.$NP.minus(
            Number(this.form.accountList[0].money),
            Number(this.form.accountList[0].discountMoney)
          );
        } else {
          let sum = 0;
          this.form.accountList.forEach((item) => {
            const money = this.$NP.minus(
              Number(item.money),
              Number(item.discountMoney)
            );
            sum = this.$NP.plus(sum, money);
          });
          return sum;
        }
      },
      // 核销总金额
      offSetTotal() {
        if (!this.choose_data.length) {
          return 0;
        } else if (this.choose_data.length === 1) {
          return Number(this.choose_data[0].offsetMoney);
        } else {
          let sum = 0;
          this.choose_data.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.offsetMoney));
          });
          return sum;
        }
      },
      // 未核销总金额
      offSetNotTotal() {
        if (!this.tableData.length) {
          return 0;
        } else if (this.tableData.length === 1) {
          return Number(this.tableData[0].offsetMoney);
        } else {
          let sum = 0;
          this.tableData.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.offsetMoney));
          });
          return sum;
        }
      },
    },
    async created() {
      this.type = this.$route.params.type;
      await this.getAllPayment();
      this.isLook = this.$route.path.indexOf("LookReceipt") > -1;
      this.isEdit = this.$route.path.indexOf("editReceipt") > -1;
      // 退款人默认当前账户
      this.form.currentAccountName = this.userName;
      if (this.$route.params.createTime) {
        this.form.createTime = this.$route.params.createTime;
      }
      if (this.$route.params.id) {
        // 编辑退款单
        this.account_id = this.$route.params.id;
        //  获取详情 退款单详情
        await this.getRefundInfo();
      } else {
        // 新增退款单
        await this.getTempReceivedData(); // 获取暂存数据
      }
      this.form.refundTime = new Date().getTime();
      await this.getAllFinanceType();
    },
    methods: {
      goOtherDetail(orderId) {
        this.$router.push("/order/manageO/OrderDetails/1/" + orderId);
      },
      // 批量选择
      selectionChange(val) {
        this.choose_data = val;
        let num = 0;
        this.choose_data.forEach((item) => {
          num += Number(item.offsetMoney);
        });
        // console.log("勾选余额", num);
        this.check_money = num;
      },
      // 获取客户详情
      async getCustomerInfo(id) {
        const { data } = await getCustomerInfo(id);
        this.form.money = data.money || 0;
        this.form.unitId = data.id;
        this.form.unitName = data.name;
        // await this.getAllReceive();
      },
      //  应收单列表
      async getAllReceive() {
        let params = {
          page: 1,
          pageSize: 999,
          unitId: this.form.unitId,
          offsetStatus: [3, 4],
          moneyType: 1,
          // auditStatus: 2,
          // financeTypeId: this.form.financeTypeId,
        };
        const { data } = await getAllReceive(params);
        this.tableData = data.map((item) => {
          return { ...item, offsetMoney: Number(item.notOffsetMoney) };
        });
      },

      // 选择商铺
      selShop(val, row) {
        this.form.shopName = row[0].name;
        // this.form.shopId = row[0].id
      },
      receivablesel(val) {
        this.form.sourceNo = val[0].no;
        this.form.sourceNoMoney = val[0].receiveMoney;
        this.form.shopName = val[0].shopName;
        this.form.shopId = val[0].shopId;
      },
      //  退款单详情
      async getRefundInfo() {
        const { data } = await getRefundInfo({
          id: this.account_id,
          createTime: this.form.createTime,
        });
        this.auditStatus = data.auditStatus;
        this.form = {
          ...data,
          refundTime: data.refundTime * 1000,
          accountList: [data.accountList],
        };
        /*if (data.offsetDate) {
          this.tableData = data.offsetDate;
          this.choose_data = data.offsetDate;
          setTimeout(() => {
            this.tableData.forEach((item) => {
              if (item.offsetMoney > 0) {
                this.$refs.multipleTable.toggleRowSelection(item);
              }
            });
          }, 200);
        }*/
      },
      // 暂存数据
      async temData(tempSave) {
        let receiptOffsetData = this.choose_data.map((item) => {
          return {
            receiveReceiptId: item.id,
            offsetMoney: item.offsetMoney,
          };
        });
        const params = {
          ...this.form,
          refundTime: parseInt(this.form.refundTime / 1000),
          tempSave: tempSave,
          receiptOffsetData: receiptOffsetData,
        };
        this.loading = true;
        const data = await addRefund(params);
        this.loading = false;

        this.$message({
          message: "暂存成功",
          type: "success",
        });
        this.$closeCurrentGoEdit("/Finance/Receivable/ReceiptList");
      },
      //  添加
      async addData(tempSave) {
        this.$refs["base_form"].validate(async (valid) => {
          if (valid) {
            if (!tempSave) {
              let isSub = true;
              for (let i in this.form.accountList) {
                let item = this.form.accountList[i];
                if (!item.accountName) {
                  isSub = false;
                  this.$message.warning("请选择结算账户");
                  break;
                }
                if (!item.money) {
                  isSub = false;
                  this.$message.warning("请输入退款金额");
                  break;
                }
                // if (!item.payWay) {
                //   isSub = false;
                //   this.$message.warning("请选择结算方式");
                //   break;
                // }
                if (this.offSetTotal > this.moneyTotal) {
                  isSub = false;
                  this.$message.warning("核销金额不能大于付款金额");
                  break;
                }
              }
              if (!isSub) {
                return;
              }
            }

            let receiptOffsetData = this.choose_data.map((item) => {
              return {
                receiveReceiptId: item.id,
                offsetMoney: item.offsetMoney,
                receiveCreateTime: item.createTime,
              };
            });
            const params = {
              ...this.form,
              refundTime: parseInt(this.form.refundTime / 1000),
              tempSave: tempSave,
              receiptOffsetData: receiptOffsetData,
            };
            this.loading = true;
            try {
              if (this.account_id) {
                const data = await editRefund(this.account_id, params);
              } else {
                const data = await addRefund(params);
              }
              this.loading = false;
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.$closeCurrentGoEdit("/Finance/Cashier/SellRefundForm/1");
            } catch {
              this.loading = false;
            }
          }
        });
      },
      //  获取暂存数据
      async getTempReceivedData() {
        const { data } = await getTempReceivedData();

        if (JSON.stringify(data) === "{}") return;
        this.form = {
          ...data,
          refundTime: data.refundTime * 1000,
          accountList: data.accountList.map((item) => {
            return {
              ...item,
              payWay: parseInt(item.payWay),
            };
          }),
        };
        /* if (data.offsetDate) {
          this.tableData = data.offsetDate;
          this.choose_data = data.offsetDate;
          setTimeout(() => {
            this.tableData.forEach((item) => {
              this.$refs.multipleTable.toggleRowSelection(item);
            });
          }, 200);
        }*/
      },
      openAccount(index) {
        this.account_index = index;
        if (!this.form.shopId) {
          this.$message.warning("请选择所属店铺");
          return;
        }
        this.account_show = true;
      },
      // 结算账户
      accountsel(val) {
        this.form.accountList[this.account_index].accountId = val[0].id;
        this.form.accountList[this.account_index].accountNumber =
          val[0].accountNumber;
        this.form.accountList[this.account_index].accountName = val[0].name;
      },
      // 类型
      typeChange(val) {
        const target = this.financeTypeList.find((item) => {
          return item.id === val;
        });
        this.form.financeType = target.name;
      },
      addAccount() {
        this.form.accountList.push({
          accountId: "",
          accountNumber: "",
          accountName: "",
          money: "",
          discountMoney: "",
          finalMoney: "",
          payWay: "",
          remark: "",
        });
      },
      delAccount(index) {
        this.form.accountList.splice(index, 1);
      },
      //  退款单位选择
      unitSel(val, row) {
        // if (this.form.type === 5) {
        //   this.form.unitName = row[0].name;
        // } else {
        //   this.form.unitName = row[0].title;
        // }
        this.form.unitName = row[0].name;
        this.form.unitId = row[0].id;
        this.form.money = row[0].money;
        this.form.sourceNo = "";
        this.getAllReceive();
      },
      // 自动核销
      offsetGet() {
        let total = 0;
        for (let i = 0; i < this.tableData.length; i++) {
          let item = this.tableData[i];
          // 把本次核销金额相加
          total += Number(item.offsetMoney);
          // 勾选可以核销的数据
          this.$refs.multipleTable.toggleRowSelection(item);
          // 如果合计核销金额大于退款总金额，停止循环，并把停止循环前的一条核销数据修改为差值
          if (total > this.moneyTotal || total === this.moneyTotal) {
            item.offsetMoney = this.moneyTotal - (total - item.offsetMoney);
            break;
          }
        }
      },
      // 退款金额失去焦点
      moneyBlur() {
        // this.offsetGet();
        // 退款金额失去焦点后重新核销
        // this.$refs.multipleTable.clearSelection();
      },
      // 获取支付方式
      async getAllPayment() {
        const data = await getAllPayment({
          page: 1,
          pageSize: 99,
        });

        this.pay_type_list = data.data;
      },
      //  获取财务类型
      async getAllFinanceType() {
        return;
        const { data } = await getAllFinanceTypeNoPage(3);

        this.financeTypeList = data;
        const finance = data.find((item) => {
          return item.name === "销售收款";
        });
        this.form.financeTypeId = finance.id;
        this.form.financeType = finance.name;
      },
      change() {
        this.form.unitName = "";
        this.form.unitId = "";
      },
    },
  };
</script>
<style lang="scss" scoped>
  .creat-custorm {
    color: #1890ff;
    font-size: 12px;
  }
  .order_bottom {
    position: relative;
    border-top: 16px solid #f6f8f9;
    width: 100%;
    background-color: #ffffff;
    border-radius: 3px;
    .order_bottom_btn {
      position: absolute;
      top: 15px;
      right: 20px;
    }
    .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;
  }
  .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;
    }
  }
  .btn-top-div {
    position: absolute;
    right: 20px;
    top: 15px;
    z-index: 999;
  }
  .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;
    }
  }
  .Enunciate {
    width: 100%;
    height: 72px;
    color: #fff;
    font-size: 16px;
    line-height: 40px;
    padding: 16px 24px;
    border-top: 1px solid #dee2ee;
    .Enunciate_cont {
      background-color: #fa6400;
      border-radius: 3px;
      padding: 0 24px;
    }
  }
</style>
<style>
  .AddRefundForm {
    background-color: #fff;
  }
  .AddRefundForm .el-tabs__item {
    font-size: 16px !important;
    height: 60px !important;
    line-height: 60px !important;
  }
  .AddRefundForm .is-active {
    font-weight: 700;
    color: #000;
  }
  .AddRefundForm .el-tabs__nav {
    margin-left: 24px;
  }
</style>
