<!--新建退货单-->
<template>
  <ContainerTit>
    <div slot="headr">
      <el-button
        v-if="!look_path"
        :loading="loading"
        :disabled="!!$route.params.id"
        @click="delPauseSave"
      >
        清除暂存
      </el-button>
      <el-button
        v-if="!look_path"
        :loading="loading"
        :disabled="!!$route.params.id"
        @click="addPauseSave"
      >
        暂存
      </el-button>
      <el-button
        v-if="!look_path"
        type="primary"
        :loading="loading"
        @click="addPurchaseOrder"
      >
        保存
      </el-button>
      <el-button
        v-if="look_path"
        size="mini"
        type="primary"
        :loading="loading"
        @click="openUrl"
      >
        打印
      </el-button>
    </div>
    <div>
      <el-form
        ref="form"
        label-width="110px"
        size="small"
        :model="form"
        :rules="rules"
      >
        <div class="detail-tab-item">
          <p class="detail-tab-title">基础信息</p>
          <div class="detail-tab-main">
            <el-form-item label="退货单号：" style="display: inline-block">
              <el-input
                v-model="form.no"
                class="width240"
                placeholder="自动生成"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item
              label="订单号："
              prop="order"
              style="display: inline-block"
            >
              <el-input
                v-model="form.order"
                readonly
                class="width240"
                placeholder="请选择订单"
                :disabled="look_path"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="orderShow = true"
                ></i>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="detail-tab-item">
          <p class="detail-tab-title">商品清单</p>
          <div class="detail-tab-main">
            <div class="clearfix" style="padding-bottom: 10px">
              <el-button
                v-if="!look_path"
                type="primary"
                size="small"
                :disabled="!form.order"
                @click="show_selgoods = true"
              >
                选择商品
              </el-button>
            </div>
            <vxe-table
              show-footer
              border="inner"
              resizable
              show-overflow
              :data="goods_list"
              :edit-config="{ trigger: 'click', mode: 'cell' }"
              :footer-method="objectSpanMethod"
              @edit-actived="editActivedEvent"
            >
              <vxe-table-column type="seq" width="60"></vxe-table-column>
              <vxe-table-column
                field="goodsCode"
                title="商品编码"
              ></vxe-table-column>
              <vxe-table-column
                field="goodsName"
                title="商品名称"
              ></vxe-table-column>
              <vxe-table-column
                field="shopName"
                title="商铺"
              ></vxe-table-column>
              <vxe-table-column field="orderout_id" title="规格">
                <template #default="{ row }">
                  <div v-if="!orderout_id">
                    {{ row.unitName }};
                    <span
                      v-for="(itemU, indexU) in row.specGroup"
                      :key="indexU"
                    >
                      <span v-if="indexU > 0">_</span>
                      {{ itemU.specValueName }}
                    </span>
                  </div>
                  <div v-else>{{ row.unitName }};{{ row.skuName }}</div>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="saleNum"
                title="销售数量"
              ></vxe-table-column>
              <vxe-table-column field="quantity" title="出库数量">
                <template #default="{ row }">
                  {{ $_common.formatNub(row.quantity) }}
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="outNum"
                title="退货数量"
                :edit-render="{
                  name: '$input',
                  props: {
                    type: 'integer',
                    min: 0,
                    max: saleNum,
                    disabled: look_path,
                  },
                }"
              ></vxe-table-column>
              <vxe-table-column
                field="otherNum"
                title="其他单位"
                :edit-render="{
                  name: '$input',
                  props: {
                    type: 'float',
                    digits: 2,
                    min: 0,
                    disabled: other_disables,
                  },
                }"
              ></vxe-table-column>
              <vxe-table-column
                field="returnUnitPrice"
                title="退货单价"
                :edit-render="{
                  name: '$input',
                  props: {
                    type: 'float',
                    digits: 2,
                    min: 0.01,
                    disabled: look_path,
                  },
                }"
              ></vxe-table-column>
              <vxe-table-column field="subtotalPrice" title="小计金额">
                <template #default="{ row }">
                  {{ $NP.times(row.returnUnitPrice || 0, row.outNum || 0) }}
                </template>
              </vxe-table-column>
              <vxe-table-column width="80" title="操作">
                <template #default="{ row, $rowIndex }">
                  <el-button type="text" @click="delData($rowIndex, row)">
                    删除
                  </el-button>
                </template>
              </vxe-table-column>
            </vxe-table>
          </div>
        </div>
        <div class="detail-tab-item">
          <p class="detail-tab-title">
            <span>备注说明</span>
            <span
              style="
                font-size: 12px;
                color: #e6a23c;
                font-weight: 400;
                padding-left: 10px;
              "
            >
              (按下回车键可进行换行)
            </span>
          </p>
          <div class="detail-tab-main">
            <el-form-item label-width="0">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                style="width: 100%"
                placeholder="请输入一些说明吧"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="detail-tab-item">
          <p class="detail-tab-title">其他</p>
          <el-row style="padding-top: 10px">
            <el-col :span="6">
              <el-form-item label="操作人：">
                <span>{{ operatorName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制单时间：">
                <span>{{ createTime }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus === 2" :span="6">
              <el-form-item label="审核人员：">
                <span>{{ operatorName }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus === 2" :span="6">
              <el-form-item label="审核时间：">
                <span>{{ $_common.formatDate(form.auditTime) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <SaleOrder
      v-if="orderShow"
      :dialog-visible="orderShow"
      :return-status="[0, 1]"
      @close="orderShow = false"
      @confirm="orderSel"
    />
    <ChooseOrderDetail
      v-if="show_selgoods"
      :is-show="show_selgoods"
      :order-id="order_id"
      :user-center-id="userCenterId"
      @cancel="show_selgoods = false"
      @confirm="selMoreGoods"
    />
  </ContainerTit>
</template>

<script>
  import ChooseOrderDetail from "@/component/goods/ChooseOrderDetail";
  import SaleOrder from "@/component/goods/SaleOrder";

  import {
    getOrderInfoById,
    getOrderOut,
    updateOrderOut,
    addOrderOut,
  } from "@/api/Order";
  import { getPauseSave, addPauseSave, delPauseSave } from "@/api/common";

  export default {
    name: "AddWareOrder",
    components: {
      SaleOrder,
      ChooseOrderDetail,
    },

    data() {
      return {
        shopName: "",
        loading: false,
        del_id_arr: [],
        createTime: "",
        auditId: "",
        auditStatus: "",
        orderStatus: "", // 单据状态
        form: {
          no: "",
          order: "",
          remark: "",
        },
        rules: {
          order: [
            { required: true, message: "请选择订单号", trigger: "change" },
          ],
        },
        order_id: "",
        userCenterId: "",
        operatorName: "",
        couponAmount: 0,
        otherAmount: 0,
        goodsData: [],
        show_selgoods: false,
        orderShow: false,
        goods_list: [],
        orderout_id: "", // 详情id
        shopId: "", // 编辑时商铺的id
        look_path: false,
        pageName: "",
        orderDetail: {},
        customerId: "",
        customerName: "",
        other_disables: false,
        saleNum: "",
      };
    },
    created() {
      this.pageName = this.$route.name;
      this.look_path = this.$route.path.includes("LookWareOrder");
      if (this.$route.params.id) {
        this.orderout_id = this.$route.params.id;
        //    调用详情接口
        this.getOrderOut();
      } else {
        this.operatorName = this.userName;
        if (this.$route.query.orderId) {
          this.getOrderInfoById(
            this.$route.query.userCenterId,
            this.$route.query.orderId
          );
          this.userCenterId = this.$route.query.userCenterId;
        } else {
          this.getPauseSave();
        }
        this.createTime = this.$_common.formatDate(new Date().getTime());
      }
    },
    activated() {
      if (this.$_isInit()) return;
      if (this.$route.query.orderId) {
        this.getOrderInfoById(
          this.$route.query.userCenterId,
          this.$route.query.orderId
        );
      } else {
        this.getPauseSave();
      }
    },
    methods: {
      // 获取订单详情
      async getOrderInfoById(userCenterId, orderId) {
        const { data } = await getOrderInfoById(userCenterId, {
          orderId: orderId,
        });

        this.orderSelResult(data);
      },
      // 打印
      openUrl(id) {
        let routeData = this.$router.resolve({
          path: `/ReturnOrderPrinting/${this.orderout_id}`,
        });
        window.open(routeData.href, "_blank");
      },
      editActivedEvent({ row }) {
        this.other_disables = row.isEq === 4;
        this.saleNum = row.saleNum;
      },
      // 合计
      objectSpanMethod({ columns, data }) {
        const properties = ["returnUnitPrice", "otherNum"];
        let totalArr = this.$_common.getSummariesVxe(columns, data, properties);
        // 小计合计
        let num = 0;
        data.forEach((item) => {
          num = this.$NP.plus(
            num,
            this.$NP.times(item.returnUnitPrice || 0, item.outNum || 0)
          );
        });
        if (totalArr.length) {
          totalArr[0].splice(totalArr[0].length - 2, 1, num);
        }
        return totalArr;
      },
      //  详情接口
      async getOrderOut() {
        const data = await getOrderOut(this.orderout_id);
        this.form = data.data;
        this.createTime = this.$_common.formatDate(data.data.createTime);
        this.shopId = data.data.shopId;
        this.shopName = data.data.shopName;
        this.order_id = data.data.originId;
        this.form.order = data.data.originNo;
        this.form.no = data.data.no;
        this.form.remark = data.data.remark;
        this.auditId = data.data.auditId;
        this.operatorName = data.data.operatorName;
        this.auditStatus = data.data.auditStatus;
        this.goods_list = data.data.details.map((item) => {
          return {
            ...item,
            saleNum: item.extend.saleNum,
          };
        });
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = data;
        this.shopId = data.shopId;
        this.shopName = data.shopName;
        this.order_id = data.originId;
        this.form.order = data.originNo;
        this.form.no = data.no;
        this.form.remark = data.remark;
        this.auditId = data.auditId;
        this.operatorName = data.operatorName;
        this.auditStatus = data.auditStatus;
        this.goods_list = data.details;
      },
      // 暂存
      async addPauseSave() {
        const params = {
          deleteArray: this.del_id_arr,
          originId: this.order_id,
          originNo: this.form.order,
          shopId: this.shopId,
          shopName: this.shopName,
          operatorName: this.operatorName,
          remark: this.form.remark,
          details: this.goods_list.map((item) => {
            return {
              outNum: item.outNum,
              otherNum: item.otherNum,
              id: item.id,
              quantity: item.outNum,
              goodsId: item.goodsId,
              goodsCode: item.goodsCode,
              goodsName: item.goodsName,
              goodsBasicId: item.goodsBasicId,
              skuId: item.skuId,
              num: item.outNum,
              unitName: item.unitName,
              saleNum: item.saleNum,
              saleUnitPrice: item.saleUnitPrice, // 销售单价
              returnUnitPrice: item.returnUnitPrice, // 退货单价
              returnTotalPrice: this.$NP.times(item.returnUnitPrice, item.num), // 退货总价
              saleTotalPrice: this.$NP.times(item.saleUnitPrice, item.saleNum), // 销售总价
            };
          }),
        };
        this.loading = true;
        const data = await addPauseSave({
          key: this.pageName,
          data: params,
        });
        this.loading = false;

        this.$message({
          type: "success",
          message: "暂存成功",
        });
        this.$closeCurrentGoEdit("/order/manageO/ReturnWarehousingOrder");
      },
      // 删除暂存信息
      async delPauseSave(tag, flag) {
        const data = delPauseSave({
          key: this.pageName,
        });
        if (!flag) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
        }
        if (tag) return;
        this.$closeCurrentGoEdit("/order/manageO/AddWareOrder");
      },
      //  保存
      async addPurchaseOrder() {
        let flag = false;
        this.goods_list.forEach((item) => {
          if (item.isEq === 5 && Number(item.otherNum) === 0) {
            flag = true;
          }
        });
        if (flag) {
          this.$message.warning("抄码商品的其他单位不能为0");
          return;
        }
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let target = {};
            const params = {
              deleteArray: this.del_id_arr,
              originId: this.order_id,
              originNo: this.form.order,
              shopId: this.shopId,
              shopName: this.shopName,
              operatorName: this.operatorName,
              remark: this.form.remark,
              userCenterId: this.userCenterId,
              customerId: this.customerId,
              customerName: this.customerName,
              details: this.goods_list.map((item) => {
                const skuName = this.orderout_id
                  ? item.skuName
                  : item.specGroup
                      .map((itemM) => {
                        return itemM.specValueName;
                      })
                      .join("_");
                return {
                  otherNum: item.otherNum,
                  id: item.id,
                  goodsId: item.goodsId,
                  goodsCode: item.goodsCode,
                  goodsName: item.goodsName,
                  goodsBasicId: item.goodsBasicId,
                  skuId: item.skuId,
                  skuName: skuName,
                  unitName: item.unitName,
                  num: item.outNum,
                  // quantity: item.outNum,
                  saleNum: item.saleNum,
                  // outNum: item.outNum,
                  saleUnitPrice: item.saleUnitPrice, // 销售单价
                  returnUnitPrice: item.returnUnitPrice, // 退货单价
                  returnTotalPrice: this.$NP.times(
                    item.returnUnitPrice || 0,
                    item.outNum || 0
                  ), // 退货总价
                  saleTotalPrice: this.$NP.times(
                    item.saleUnitPrice || 0,
                    item.saleNum || 0
                  ), // 销售总价
                };
              }),
            };
            this.loading = true;
            try {
              if (this.orderout_id) {
                target = await updateOrderOut(this.orderout_id, params);
              } else {
                target = await addOrderOut(params);
              }
              const data = target;
              this.loading = false;
              this.$message({
                type: "success",
                message: "提交成功",
              });
              await this.delPauseSave(1, 1);
              this.$closeCurrentGoEdit("/order/manageO/ReturnWarehousingOrder");
            } catch {
              this.loading = false;
            }
          }
        });
      },
      // 选择多个商品
      selMoreGoods(val) {
        const goodsData = val.map((item) => {
          return {
            isEq: item.isEq,
            otherNum: item.otherNum,
            id: item.id,
            outNum: item.outNum,
            goodsId: item.goodsId,
            goodsCode: item.goodsCode,
            goodsName: item.goodsName,
            unitName: item.unitName,
            specGroup: item.specGroup,
            saleNum: item.buyNum,
            quantity: item.outNum,
            shopName: item.shopName,
            goodsBasicId: item.goodsBasicId,
            skuId: item.skuId,
            num: item.buyNum,
            saleUnitPrice: item.price, // 销售单价
            returnUnitPrice: item.returnPrice, // 退货单价
            returnTotalPrice: this.$NP.times(item.price, item.buyNum), // 退货总价
            saleTotalPrice: this.$NP.times(item.price, item.buyNum), // 销售总价
          };
        });
        if (this.goods_list.length) {
          this.goods_list = this.$_common.unique(
            this.goods_list.concat(goodsData),
            ["id", "goodsId", "skuId"]
          );
        } else {
          this.goods_list = goodsData;
        }
        // 新增商品后，对比删除数组里面的id,避免与提交的商品重复
        this.goods_list.forEach((item) => {
          const index = this.del_id_arr.indexOf(item.id);
          if (index > -1) {
            this.del_id_arr.splice(index, 1);
          }
        });
      },
      //  选择订单
      orderSel(row) {
        const allowReturn = row[0].allowReturn;
        const allowReturnDay = row[0].allowReturnDay;
        if (allowReturn === 4) {
          this.$confirm(
            `已经超过${allowReturnDay}天,建议不能退货, 是否确定强制退货?`,
            "提醒",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.$message({
              type: "error",
              message: "你已确定强制退货!",
            });
            this.getOrderInfoById(row[0].userCenterId, row[0].id);
            // this.orderSelResult(row[0])
          });
          return;
        }
        this.getOrderInfoById(row[0].userCenterId, row[0].id);
        // this.orderSelResult(row[0])
      },
      orderSelResult(row) {
        this.order_id = row.id;
        this.form.order = row.no;
        this.userCenterId = row.userCenterId;
        // 订单状态 orderStatus
        this.orderStatus = row.orderStatus;
        this.shopId = row.shopId;
        this.shopName = row.shopName;
        this.customerName = row.customerName;
        this.customerId = row.customerId;
        // this.goods_list = row.goodsData.map((item) => {
        //   return {
        //     isEq: item.isEq,
        //     otherNum: item.otherNum,
        //     id: item.id,
        //     goodsId: item.goodsId,
        //     goodsName: item.goodsName,
        //     shopName: row.shopName,
        //     goodsCode: item.goodsCode,
        //     goodsBasicId: item.goodsBasicId,
        //     skuId: item.skuId,
        //     quantity: item.outNum,
        //     outNum: item.outNum,
        //     unitName: item.unitName,
        //     specGroup: item.specGroup,
        //     num: item.buyNum,
        //     saleNum: item.buyNum,
        //     saleUnitPrice: item.price, // 销售单价
        //     returnUnitPrice: item.returnPrice, // 退货单价
        //     returnTotalPrice: this.$NP.times(item.price, item.buyNum), // 退货总价
        //     saleTotalPrice: this.$NP.times(item.price, item.buyNum), // 销售总价
        //   };
        // });
      },
      delData(index, row) {
        console.log(index);
        this.$confirm("请确认是否删除该商品?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.del_id_arr.push(row.id);
          this.del_id_arr = this.$_common.unique(this.del_id_arr);
          this.goods_list.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
    },
  };
</script>

<style scoped>
  .width240 {
    width: 240px;
  }
  .other-price-view {
    padding-top: 10px;
    border: 1px solid #ecf0f7;
    border-top: 0;
  }
</style>
