<template>
  <ContainerTit>
    <div class="page-tip-div" style="margin-top: 0">
      <i class="el-icon-info"></i>
      温馨提示：
      <span>1、销售单保存成功后，自动完成出库流程！</span>
      <span>2、销售单创建保存后，只能在销售单列表看到已保存的销售单据！</span>
    </div>
    <div slot="headr">
      <el-button type="primary" :loading="sub_loading" @click="subData">
        提交保存
      </el-button>
    </div>
    <el-form
      ref="add_form"
      :rules="add_rules"
      :model="add_form"
      size="small"
      inline
    >
      <div class="page-div">
        <el-form-item label="所属店铺" prop="shopId">
          <SelectShop
            v-model="shopId"
            :is-default="true"
            :clearable="false"
            @change="selShop"
            @default="shopDefault"
          />
        </el-form-item>

        <el-form-item label="客户" prop="customerName">
          <SelectCustomer
            v-model="add_form.customerName"
            :clearable="false"
            @change="customerSel"
          />
          <el-button
            size="mini"
            type="text"
            @click="$router.push('/Customer/CustomerAdmin/AddCustomer')"
          >
            【新建客户】
          </el-button>
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-select
            v-model="add_form.deliveryType"
            placeholder="请选择"
            @change="deliveryTypeChange"
          >
            <el-option
              v-for="item in deliveryType_list"
              :key="item.id"
              :label="item.title"
              :value="item.deliveryType"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="add_form.deliveryType === 1" label="收货信息">
          <el-select
            v-model="add_form.receiveAddressId"
            style="width: 400px"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in address_list"
              :key="index"
              :label="item.addressName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="add_form.deliveryType === 2" label="自提点：">
          <el-select
            v-model="add_form.selfRuleId"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in self_express_list"
              :key="index"
              :label="item.addressName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小票打印">
          <el-switch
            v-model="add_form.isEnablePrint"
            active-color="#36B365"
            inactive-color="#ff4949"
            :active-value="5"
            :inactive-value="4"
            active-text="打印"
            inactive-text="不打印"
          ></el-switch>
        </el-form-item>
        <el-table :data="saleOrderGoods">
          <el-table-column
            type="index"
            align="left"
            min-width="60"
          ></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" min-width="280">
            <template slot-scope="scope">
              <ConditionSelGoods
                v-if="!!add_form.userCenterId"
                v-model="scope.row.goodsName"
                :user-center-id="add_form.userCenterId"
                :shop-id="shopId"
                :enable-status="5"
                :spec-check="spec_check"
                @selGoods="selGoods"
                @goodsVisibleChange="goodsVisibleChange($event, scope.$index)"
                @specSelConfirm="specSelConfirm"
                @selectSelGoods="selectSelGoods"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="code"
            align="left"
            label="商品编码"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="unitName"
            align="left"
            label="单位"
            min-width="80"
          ></el-table-column>
          <el-table-column
            prop="specName"
            align="left"
            label="属性"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="inventoryNum"
            align="left"
            label="可用库存"
            min-width="80"
          >
            <template slot-scope="scope">
              {{ scope.row.inventoryNum - 0 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="buyNum"
            label="数量"
            align="left"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.buyNum"
                size="mini"
                :controls="false"
                :max="scope.row.inventoryNum - 0"
                style="width: 100%"
                :min="1"
                @change="updateBuyNum($event, scope.$index)"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column
            prop="salePrice"
            align="left"
            label="单价"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.salePrice"
                size="mini"
                :controls="false"
                style="width: 100%"
                :min="0"
                @change="updatePrice($event, scope.$index)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="totalMoney"
            label="小计"
            min-width="80"
          ></el-table-column>
          <el-table-column
            fixed="right"
            align="left"
            label="管理"
            min-width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="delGoods(scope.$index)"
              >
                删除
              </el-button>
              <el-button size="mini" type="text" @click="addListGoods">
                新增
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="total-div">
          <span class="de_label">订单总金额：</span>
          <span class="de_val">{{ orderAmount || 0 }}元</span>
          <span class="de_label">订单优惠金额：</span>
          <span class="de_val">
            <el-input-number
              v-model="totalReduceMoney"
              :controls="false"
              size="small"
              :min="0"
              :max="orderAmount"
            ></el-input-number>
            元
          </span>
          <span class="de_label">应收：</span>
          <span class="de_val">{{ payMoney }}元</span>
          <span class="de_label">实收：</span>
          <span class="de_val">
            <el-input-number
              v-model="add_form.receivedMoney"
              :controls="false"
              size="small"
              :min="0"
              :max="payMoney"
            ></el-input-number>
            元
          </span>

          <span class="de_label">结算账户：</span>
          <span class="de_val">
            <el-input
              v-model="accountName"
              :disabled="!add_form.customerId"
              readonly
              style="width: 200px"
              size="small"
              placeholder="结算账户"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="account_show = true"
              ></i>
            </el-input>
          </span>
        </div>
        <div style="padding-top: 5px">
          <el-input
            v-model="add_form.remark"
            type="textarea"
            :rows="2"
            style="width: 100%"
            placeholder="请输入一些说明吧"
          ></el-input>
        </div>
      </div>
    </el-form>
    <AccountType
      v-if="account_show"
      :id="account_shopId"
      :is-check="false"
      :is-show="account_show"
      @cancel="account_show = false"
      @confirm="accountsel"
    />
  </ContainerTit>
</template>

<script>
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import { addSalesOrder } from "@/api/Order";
  import { getAllShippingAddress } from "@/api/Customer";
  import AccountType from "@/views/Finance/AccountType";
  import { getAllDelivery, getAllSelfExpressRule } from "@/api/System";

  export default {
    name: "OrderAdd",
    components: {
      SelectCustomer,
      ConditionSelGoods,
      SelectShop,
      AccountType,
    },

    data() {
      return {
        accountName: "",
        account_shopId: 0,
        account_show: false, // 结算账户
        show_goods: false,
        loading: false,
        goods_index: 0,
        select_loading: false,
        customerId: "",
        saleOrderGoods: [],
        add_rules: {
          customerName: [
            { required: true, message: "请选择购买客户", trigger: "change" },
          ],
          deliveryType: [
            { required: true, message: "请选择配送方式", trigger: "change" },
          ],
        },
        mobile: "",
        shopId: "",
        address: "",
        address_list: [],
        goods_options: [],
        spec_check: [],
        totalReduceMoney: "",
        add_form: {
          isEnablePrint: 4,
          totalMoney: 0,
          payAmount: 0,
          customerId: "",
          userCenterId: 0,
          customerName: "",
          customerType: 0,
          receiveAddressId: "",
          source: 4,
          deliveryType: 1,
          remark: "",
          goodsData: [],
          currentAccountName: "",
          receivedMoney: 0,
          accountList: [],
          selfRuleId: 0,
        },
        payWay: 3, //支付方式
        deliveryType_list: [],
        self_express_list: [], //自提点
      };
    },
    computed: {
      orderAmount() {
        if (!this.saleOrderGoods.length) {
          return 0;
        } else if (this.saleOrderGoods.length === 1) {
          return this.saleOrderGoods[0].totalMoney;
        } else {
          let sum = 0;
          this.saleOrderGoods.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.totalMoney) || 0);
          });
          return sum;
        }
      },
      payMoney() {
        return this.$NP.minus(this.orderAmount, this.totalReduceMoney);
      },
    },
    created() {
      for (let i = 1; i <= 1; i++) {
        this.saleOrderGoods.push({
          unitName: "",
          skuId: "",
          skuData: "",
          goodsId: "",
          buyNum: 1,
          inventoryNum: 0,
          totalMoney: "",
          title: "", // 商品名称
          shopId: 0,
          shopName: "", // 店铺名称
          originPrice: 0,
          salePrice: 0,
          goodsBasicId: 0, // 商品基础资料ID
          code: "",
          conversion: 0,
          categoryPath: "",
          brandId: 0,
          warehouseId: 0,
        });
      }
      this.add_form.currentAccountName = this.userName;
      // 配送方式
      this.getAllDelivery();
      // 获取自提点
      this.getAllSelfExpressRule();
      // console.log(this.saleOrderGoods)
    },
    methods: {
      shopDefault(val) {
        this.shopId = val;
      },
      selShop(val, row) {
        this.saleOrderGoods = [];
        this.resetGoods();
      },
      resetGoods() {
        let arr = [];
        for (let i = 1; i <= 10; i++) {
          arr.push({
            unitName: "",
            skuId: "",
            skuData: "",
            goodsId: "",
            buyNum: 1,
            inventoryNum: 0,
            totalMoney: "",
            title: "", // 商品名称
            shopId: 0,
            shopName: "", // 店铺名称
            originPrice: 0,
            salePrice: 0,
            goodsBasicId: 0, // 商品基础资料ID
            code: "",
            conversion: 0,
            categoryPath: "",
            brandId: 0,
            warehouseId: 0,
          });
        }
        this.saleOrderGoods = arr;
      },
      // 选择结算账户
      accountsel(row) {
        this.accountName = row[0].name;
        this.add_form.accountList = [
          {
            accountId: row[0].id,
            accountNumber: row[0].accountNumber,
            accountName: row[0].name,
            money: this.add_form.receivedMoney,
            discountMoney: 0,
            finalMoney: this.add_form.receivedMoney,
            payWay: this.payWay,
            remark: row[0].remark,
          },
        ];
      },
      // 提交
      subData() {
        let subGoodsArr = [];
        this.$_common.deepClone(this.saleOrderGoods).forEach((item) => {
          if (item.goodsId) {
            delete item.skuData;
            delete item.inventoryNum;
            subGoodsArr.push(item);
          }
        });
        if (!subGoodsArr.length) {
          this.$message({
            type: "warning",
            message: "请选择商品",
          });
          return;
        }
        if (
          this.add_form.receivedMoney > 0 &&
          !this.add_form.accountList.length
        ) {
          this.$message.warning("请选择结算账户");
          return;
        }
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            let params = {
              ...this.add_form,
              goodsData: subGoodsArr,
              totalMoney: this.orderAmount,
              payAmount: this.payMoney,
              operatorName: this.userName,
              totalReduceMoney: this.totalReduceMoney,
            };
            try {
              this.sub_loading = true;
              const data = await addSalesOrder(
                this.add_form.userCenterId,
                params
              );
              this.sub_loading = false;
              this.$message({
                type: "success",
                message: "提交成功",
              });
              this.$closeCurrentGoEdit("/order/saleO/SaleOrderList");
            } finally {
              this.sub_loading = false;
            }
          }
        });
      },
      // 新增一条商品
      addListGoods() {
        this.saleOrderGoods.push({
          unitName: "",
          skuId: "",
          skuData: "",
          goodsId: "",
          buyNum: 1,
          inventoryNum: 0,
          totalMoney: "",
          title: "", // 商品名称
          shopId: 0,
          shopName: "", // 店铺名称
          originPrice: 0,
          salePrice: 0,
          goodsBasicId: 0, // 商品基础资料ID
          code: "",
          conversion: 0,
          categoryPath: "",
          brandId: 0,
          warehouseId: 0,
        });
      },
      specSelConfirm(params) {
        let target = this.$_common.deepClone(this.saleOrderGoods);
        const goodsD = params.goodsD.map((item) => {
          return {
            specName: item.spec.specGropName,
            unitName: item.spec.unitName,
            skuId: item.skuId,
            goodsId: params.now_goods_data.id,
            goodsName: params.now_goods_data.title,
            buyNum: 1,
            inventoryNum: item.spec.inventory,
            totalMoney: item.spec.salePrice * 1,
            title: params.now_goods_data.title, // 商品名称
            shopId: params.now_goods_data.shopId,
            shopName: params.now_goods_data.shopName, // 店铺名称
            originPrice: item.spec.originPrice,
            salePrice: item.spec.salePrice,
            goodsBasicId: params.now_goods_data.basicGoodsId, // 商品基础资料ID
            code: params.now_goods_data.code,
            conversion: item.spec.conversion || 0,
            categoryPath: params.now_goods_data.categoryPath,
            brandId: params.now_goods_data.brandId,
            warehouseId: params.now_goods_data.warehouseId,
            supplierId: item.supplierId,
            supplierName: item.supplierName,
          };
        });
        if (!target[this.goods_index].skuId) {
          target.splice(this.goods_index, 1);
        }

        // goodsD.forEach((item) => {
        //   const targetD = target.find((itemG) => itemG.skuId === item.skuId);
        //   if (!targetD) {
        //     target.unshift(item);
        //   }
        // });
        // console.log(target);
        this.saleOrderGoods = goodsD.concat(target);
      },
      // 商品选择弹窗
      selGoods(list) {
        let target = this.$_common.deepClone(this.saleOrderGoods);
        const goodsD = list.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            specName: specGropName,
            unitName: item.unitName,
            skuId: item.skuId,
            goodsId: item.id,
            goodsName: item.title,
            buyNum: 1,
            inventoryNum: item.inventory,
            totalMoney: item.salePrice * 1,
            title: item.title, // 商品名称
            shopId: item.shopId,
            shopName: item.shopName, // 店铺名称
            originPrice: item.originPrice,
            salePrice: item.salePrice,
            goodsBasicId: item.basicGoodsId, // 商品基础资料ID
            code: item.code,
            conversion: item.conversion || 0,
            categoryPath: item.categoryPath,
            brandId: item.brandId,
            warehouseId: item.warehouseId,
            supplierId: item.supplierId,
            supplierName: item.supplierName,
          };
        });
        // goodsD.forEach((item) => {
        //   const targetD = target.find((itemG) => itemG.skuId === item.skuId);
        //   if (!targetD) {
        //     target.unshift(item);
        //   }
        // });
        this.saleOrderGoods = goodsD.concat(target);
      },
      // 列表商品下拉选择
      selectSelGoods(id) {
        this.spec_check = this.saleOrderGoods
          .filter((item) => item.goodsId === id)
          .map((item) => {
            return item.skuId;
          });
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      // 修改商品数量
      async updateBuyNum(val, index) {
        const target = this.$_common.deepClone(this.saleOrderGoods);
        target[index] = {
          ...target[index],
          totalMoney: this.$NP.times(
            target[index].salePrice,
            target[index].buyNum
          ),
        };
        this.saleOrderGoods = target;
      },
      // 修改商品单价
      async updatePrice(val, index) {
        const target = this.$_common.deepClone(this.saleOrderGoods);
        target[index] = {
          ...target[index],
          totalMoney: this.$NP.times(
            target[index].salePrice,
            target[index].buyNum
          ),
        };
        this.saleOrderGoods = target;
      },
      // 移除
      delGoods(index) {
        if (this.saleOrderGoods.length === 1) {
          this.$message.warning("至少保留一条商品");
          return;
        }
        this.saleOrderGoods.splice(index, 1);
      },
      // 选择客户
      customerSel(val, list) {
        const row = list[0];
        this.add_form.userCenterId = row.userCenterId;
        this.add_form.customerId = row.id;
        this.add_form.customerType = row.type;
        this.add_form.receiveAddressId = "";
        this.resetGoods();
        if (this.add_form.deliveryType === 1) {
          this.getAllShippingAddress(this.add_form.customerId);
        }
        // 清空客户购物车
        // this.saleOrderGoods = []
      },
      // 获取客户收货地址列表
      async getAllShippingAddress(id) {
        const { data } = await getAllShippingAddress(id);
        if (data.length) {
          this.address_list = data.map((item) => {
            return {
              ...item,
              addressName:
                item.name +
                " " +
                item.mobile +
                " " +
                item.area.provinceName +
                "-" +
                item.area.cityName +
                "-" +
                item.area.districtName +
                "-" +
                item.address,
            };
          });
          this.add_form.receiveAddressId = this.address_list[0].id;
        } else {
          this.address_list = [];
        }
      },
      // 配送方式
      deliveryTypeChange(val) {
        if (val === 1) {
          // const target = this.address_list[0];
          // this.add_form.addressId = target.id;
          this.getAllShippingAddress(this.add_form.customerId);
        } else if (val === 2) {
          if (this.self_express_list.length) {
            const target = this.self_express_list[0];
            this.add_form.selfRuleId = target.id;
          }
        }
      },
      // 获取配送方式
      async getAllDelivery() {
        const { data } = await getAllDelivery({
          page: 1,
          pageSize: 100,
        });

        this.deliveryType_list = data;
        const defaultType = data.find((item) => item.defaultStatus === 5);
        if (defaultType && !this.add_form.deliveryType) {
          this.add_form.deliveryType = defaultType.deliveryType;
        }
      },
      // 获取自提点
      async getAllSelfExpressRule() {
        const { data } = await getAllSelfExpressRule();
        this.self_express_list = data.map((item) => {
          return {
            ...item,
            addressName:
              item.setData.name +
              " " +
              item.setData.mobile +
              " " +
              item.setData.provinceName +
              "-" +
              item.setData.cityName +
              "-" +
              item.setData.districtName +
              "-" +
              item.setData.address,
          };
        });

        if (data.length) {
          this.add_form.selfRuleId = data[0].id;
        }
      },
    },
  };
</script>
<style slot-scope="scope" lang="scss">
  .total-div {
    border: 1px solid #ebeef5;
    text-align: right;
    border-top: 0;
    padding: 10px;
    .de_val {
      color: #ff4400;
      padding-right: 20px;
    }
  }
</style>
