<template>
  <ContainerTit>
    <div slot="headr">
      <el-button v-if="!orderId" @click="delPauseSave(1)">清除暂存</el-button>
      <el-button v-if="!orderId" @click="addPauseSave">暂存</el-button>
      <el-button :loading="sub_loading" type="primary" @click="subData">
        提交保存
      </el-button>
    </div>
    <div class="page-tip-div">
      <i class="el-icon-info"></i>
      抄码商品只能选择一个单位进行下单，重复选择则不能勾选
    </div>
    <el-form
      ref="add_form"
      :rules="add_rules"
      :model="add_form"
      size="small"
      inline
    >
      <div class="detail-tab-item">
        <p class="detail-tab-title">基本信息</p>
        <div class="detail-tab-main">
          <el-form-item label="客户" prop="customerId">
            <SelectCustomer
              v-model="add_form.customerName"
              :clearable="false"
              :disabled="parseInt(order_detail.payStatus) === 5"
              @change="customerSel"
            />
            <el-button
              v-if="parseInt(order_detail.payStatus) !== 5"
              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"
              :disabled="parseInt(order_detail.payStatus) === 5"
              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 !== 2 && add_form.customerName"
            label="收货信息"
            prop="addressId"
          >
            <!--  因为保存订单后，地址ID在数据库里面存的是个新的ID，所以把下拉框选择器改为下拉菜单   -->
            <el-dropdown @command="addressChange">
              <div
                style="
                  min-width: 300px;
                  cursor: pointer;
                  border: 1px solid #dcdfe6;
                  border-radius: 4px;
                  padding: 0 10px;
                  font-size: 13px;
                  vertical-align: middle;
                  height: 32px;
                  line-height: 32px;
                "
                class="clearfix"
              >
                <span class="float_left">{{ address_name || "请选择" }}</span>
                <span class="float_right">
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(item, index) in address_list"
                  :key="index"
                  :command="item.id"
                >
                  {{ item.addressName }}
                </el-dropdown-item>
                <el-dropdown-item v-if="!address_list.length">
                  当前客户未设置地址
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              v-if="!!add_form.customerId"
              type="text"
              size="small"
              plain
              style="margin-left: 5px; transform: translateY(-10px)"
              @click="AddAddress = true"
            >
              新增地址
            </el-button>
          </el-form-item>
          <el-form-item
            v-if="add_form.deliveryType === 3 && add_form.customerName"
            label="物流类型"
          >
            <el-select
              v-model="add_form.particularsType"
              placeholder="请选择"
              @change="deliveryTypeChange"
            >
              <el-option
                v-for="item in particularsType_list"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></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"
              @change="selfRuleIdChange"
            >
              <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-select
              v-model="add_form.payType"
              placeholder="请选择"
              @change="deliveryTypeChange"
            >
              <el-option
                v-for="item in payType_list"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="detail-tab-item">
        <p class="detail-tab-title">商品清单</p>
        <el-table
          :data="saleOrderGoods"
          :height="saleOrderGoods.length >= 10 ? 500 : ''"
        >
          <el-table-column type="index" width="50" label="#"></el-table-column>
          <el-table-column min-width="200" prop="goodsName" label="商品名称">
            <template slot-scope="scope">
              <!--              由于订单是按照店铺拆单的
所以在编辑订单时，增加此订单的商品时应该只能选择本店铺下的商品-->
              <!--              -->
              <ConditionSelGoods
                v-model="scope.row.goodsName"
                :disabled="
                  parseInt(order_detail.payStatus) === 5 || !userCenterId
                "
                :user-center-id="userCenterId"
                :spec-check="spec_check"
                :enable-status="5"
                :shop-id="shop_id"
                @goodsVisibleChange="goodsVisibleChange($event, scope.$index)"
                @specSelConfirm="specSelConfirm"
                @selectSelGoods="selectSelGoods"
                @selGoods="selGoods"
              />
            </template>
          </el-table-column>
          <el-table-column prop="specGroup" min-width="130" label="规格">
            <template slot-scope="scope">
              <span>{{ scope.row.unitName || "--" }};</span>
              <span v-for="(item, index) in scope.row.specGroup" :key="index">
                {{ item.specValueName }};
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="inventory" min-width="120" label="可用库存">
            <template slot-scope="scope">
              <div
                class="inventory-text"
                :class="[
                  scope.row.inventory <= 0 ? 'danger-color' : 'success-color',
                ]"
              >
                {{ $_common.formatNub(scope.row.inventory) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="buyNum" label="数量" min-width="100">
            <template slot-scope="scope">
              <!--    未开启负库存 有最大值验证-->
              <vxe-input
                v-if="scope.row.isDistribution === 4"
                v-model="scope.row.buyNum"
                style="width: 100%"
                :disabled="parseInt(order_detail.payStatus) === 5"
                :min="0"
                :max="scope.row.inventory"
                size="mini"
                placeholder="数值类型"
                type="number"
                @change="updateBuyNum(scope.$index)"
              ></vxe-input>
              <!--    开启负库存 无最大值验证-->
              <vxe-input
                v-else
                v-model="scope.row.buyNum"
                style="width: 100%"
                :disabled="parseInt(order_detail.payStatus) === 5"
                :min="0"
                size="mini"
                placeholder="数值类型"
                type="number"
                @change="updateBuyNum(scope.$index)"
              ></vxe-input>
              <br />
              <!--             其他单位数量 -->
              <vxe-input
                v-if="scope.row.isEq === 5 && scope.row.isMaster === 5"
                v-model="scope.row.otherNum"
                style="width: 100%; margin-top: 5px"
                :disabled="parseInt(order_detail.payStatus) === 5"
                size="mini"
                placeholder="其他单位数量"
                type="integer"
              ></vxe-input>
            </template>
          </el-table-column>

          <el-table-column min-width="100" prop="price" label="单价">
            <template slot-scope="scope">
              <vxe-input
                v-if="$accessCheck($Access.OrderAddeditGoodsPrice)"
                v-model="scope.row.salePrice"
                size="mini"
                style="width: 100%"
                :disabled="parseInt(order_detail.payStatus) === 5"
                :min="0"
                @change="updateBuyNum(scope.$index)"
              ></vxe-input>
              <span v-else>
                {{ scope.row.salePrice }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="100" prop="totalMoney" label="小计">
            <template slot-scope="scope">
              <vxe-input
                v-if="$accessCheck($Access.OrderAddeditGoodsPrice)"
                v-model="scope.row.subMoney"
                size="mini"
                :disabled="parseInt(order_detail.payStatus) === 5"
                style="width: 100%"
              ></vxe-input>
              <span v-else>
                {{ scope.row.subMoney }}
              </span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" prop="tag" label="管理" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :disabled="parseInt(order_detail.payStatus) === 5"
                @click="deleteRowGoods(scope.$index)"
              >
                删除
              </el-button>
              <el-button
                :disabled="parseInt(order_detail.payStatus) === 5"
                size="mini"
                type="text"
                @click="addListGoods"
              >
                新增
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="price-div">
          <span class="de_label">商品总额:</span>
          <span class="de_val">
            {{ $_common.formattedNumber(orderAmount) }}
          </span>

          <span class="de_label">优惠金额:</span>
          <span class="de_val">
            ¥
            <el-input-number
              v-if="$accessCheck($Access.OrderAddeditGoodsPrice)"
              v-model="totalReduceMoney"
              :controls="false"
              size="small"
              :disabled="parseInt(order_detail.payStatus) === 5"
              :min="0"
              :max="orderAmount"
            ></el-input-number>
            <span v-else>{{ totalReduceMoney }}</span>
          </span>
          <span class="de_label">应收:</span>
          <span class="de_val">{{ $_common.formattedNumber(payMoney) }}</span>
          <span class="de_label">实收:</span>
          <span class="de_val">
            ¥
            <el-input-number
              v-if="$accessCheck($Access.OrderAddeditGoodsPrice)"
              v-model="add_form.receivedMoney"
              :controls="false"
              size="small"
              :disabled="parseInt(order_detail.payStatus) === 5"
              :min="0"
              :max="payMoney"
            ></el-input-number>
            <span v-else>{{ add_form.receivedMoney }}</span>
          </span>

          <span class="de_label">结算账户:</span>
          <span class="de_val">
            <el-input
              v-model="accountName"
              readonly
              :disabled="
                !add_form.customerId || parseInt(order_detail.payStatus) === 5
              "
              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>
      <div v-if="false" class="detail-tab-item">
        <div class="detail-tab-title clearfix">
          <span class="float_left">赠品清单</span>
          <span class="float_right">
            <el-button size="mini" type="primary" @click="giveawayAddListGoods">
              新增
            </el-button>
          </span>
        </div>
        <el-table
          :height="giveawayGoods.length >= 10 ? '500' : ''"
          :data="giveawayGoods"
        >
          <el-table-column type="index" width="50" label="#"></el-table-column>
          <el-table-column min-width="200" prop="goodsName" label="商品名称">
            <template slot-scope="scope">
              <!--              由于订单是按照店铺拆单的
所以在编辑订单时，增加此订单的商品时应该只能选择本店铺下的商品-->
              <!--              -->
              <ConditionSelGoods
                v-model="scope.row.goodsName"
                :disabled="
                  parseInt(order_detail.payStatus) === 5 || !userCenterId
                "
                :user-center-id="userCenterId"
                :spec-check="spec_check"
                :enable-status="5"
                :shop-id="shop_id"
                @goodsVisibleChange="
                  giveawayVisibleChange($event, scope.$index)
                "
                @specSelConfirm="giveawaySpecSelConfirm"
                @selectSelGoods="giveawaySelectSelGoods"
                @selGoods="giveawaySelGoods"
              />
            </template>
          </el-table-column>
          <el-table-column prop="specGroup" min-width="130" label="规格">
            <template slot-scope="scope">
              <span>{{ scope.row.unitName || "--" }};</span>
              <span v-for="(item, index) in scope.row.specGroup" :key="index">
                {{ item.specValueName }};
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="inventory" min-width="120" label="可用库存">
            <template slot-scope="scope">
              <div
                class="inventory-text"
                :class="[
                  scope.row.inventory <= 0 ? 'danger-color' : 'success-color',
                ]"
              >
                {{ $_common.formatNub(scope.row.inventory) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="buyNum" label="数量" min-width="100">
            <template slot-scope="scope">
              <!--    未开启负库存 有最大值验证-->
              <el-input-number
                v-if="scope.row.isDistribution === 4"
                v-model="scope.row.buyNum"
                size="mini"
                :controls="false"
                style="width: 100%"
                :disabled="parseInt(order_detail.payStatus) === 5"
                :min="0"
                :max="scope.row.inventory"
                @change="giveawayUpdateBuyNum(scope.$index)"
              ></el-input-number>
              <!--    开启负库存 无最大值验证-->
              <el-input-number
                v-else
                v-model="scope.row.buyNum"
                size="mini"
                :controls="false"
                style="width: 100%"
                :disabled="parseInt(order_detail.payStatus) === 5"
                :min="0"
                @change="giveawayUpdateBuyNum(scope.$index)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column fixed="right" prop="tag" label="管理" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :disabled="parseInt(order_detail.payStatus) === 5"
                @click="giveawayDeleteRowGoods(scope.$index)"
              >
                删除
              </el-button>
              <el-button
                :disabled="parseInt(order_detail.payStatus) === 5"
                size="mini"
                type="text"
                @click="giveawayAddListGoods"
              >
                新增
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="detail-tab-item">
        <p class="detail-tab-title">备注说明</p>
        <!--          备注-->
        <div class="detail-tab-main">
          <el-input
            v-model="add_form.remark"
            type="textarea"
            :rows="2"
            style="width: 100%"
            placeholder="请输入一些说明吧"
          ></el-input>
        </div>
      </div>
    </el-form>
    <!--    新增收货地址-->
    <el-dialog
      title="新增地址"
      :visible.sync="AddAddress"
      :show-close="false"
      width="50%"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="closeDialog('form')"
    >
      <el-form
        ref="form"
        :model="form"
        size="medium"
        label-width="100px"
        :rules="form_rules"
      >
        <el-form-item label="收货人" prop="name">
          <el-input
            v-model="form.name"
            placeholder="收货人名称"
            autocomplete="off"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="provinceCode">
          <RegionSelect
            v-model="regionName"
            size="medium"
            style="margin-bottom: 10px"
            @change="regionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="详细地址，例如楼牌，门号"
            autocomplete="off"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="填写收货人联系方式"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否默认">
          <el-switch
            v-model="form.defaultStatus"
            active-color="#ff4949"
            inactive-color="#36B365"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="AddAddress = false">取 消</el-button>
        <el-button type="primary" @click="addShippingAddress">确 定</el-button>
      </div>
    </el-dialog>
    <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 RegionSelect from "@/component/common/RegionSelectJSON";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import { getOrderInfoById, newOrderEdit, newAddOrder } from "@/api/Order";
  import { addShippingAddress, getAllShippingAddress } from "@/api/Customer";
  import { getAllDelivery, getAllSelfExpressRule } from "@/api/System";
  import { addPauseSave, getPauseSave, delPauseSave } from "@/api/common";
  import AccountType from "@/views/Finance/AccountType";
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  const goodsItem = {
    skuId: 0,
    code: "",
    goodsId: 0,
    buyNum: 1,
    shopId: 0,
    basicGoodsId: 0,
    goodsName: "",
    unitName: "",
    specGroup: "",
    inventory: 0,
    salePrice: 0,
    subMoney: 0,
    shopName: "",
    goodsImages: "",
    brandId: 0,
    brandName: "",
    categoryPath: "",
    categoryName: "",
    conversion: "",
    barCode: "",
    storageCode: "",
    warehouseId: 0,
    originPrice: "",
    specType: "",
  };
  export default {
    name: "OrderAdd",
    components: {
      SelectCustomer,
      RegionSelect,
      ConditionSelGoods,
      AccountType,
    },

    data() {
      const validateMobile = (rule, value, callback) => {
        const re = /^1[3456789]\d{9}$/; // 正则表达式
        if (value === "") {
          callback(new Error());
        } else if (!re.test(value)) {
          callback(new Error("手机号格式有误，请重新输入!"));
        } else {
          callback();
        }
      };
      const validateAddressId = (rule, value, callback) => {
        if (this.add_form.deliveryType !== 2) {
          if (!value) {
            callback(new Error("请选择收货信息"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
      return {
        address_name: "",
        warehouse: "",
        warehouse_show: false,
        account_shopId: 0,
        account_show: false, // 结算账户
        // 新增地址
        AddAddress: false,
        loading: false,
        userCenterId: "",
        deliveryType_list: [],

        saleOrderGoods: [], //商品清单
        giveawayGoods: [], //赠品品清单
        add_rules: {
          customerId: [
            { required: true, message: "请选择购买客户", trigger: "change" },
          ],
          addressId: [
            { required: true, validator: validateAddressId, trigger: "change" },
          ],
          deliveryType: [
            { required: true, message: "请选择配送方式", trigger: "change" },
          ],
        },
        form_rules: {
          name: [
            { required: true, message: "请填写收货人", trigger: "change" },
          ],
          address: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
          ],
          mobile: [
            { required: true, message: "请填写联系方式", trigger: "blur" },
            { validator: validateMobile, trigger: "blur" },
          ],
          provinceCode: [
            { required: true, message: "请选择收货地址", trigger: "change" },
          ],
        },
        mobile: "",
        address: "",
        /*
        *
        * 'ios'         => 1, //ios
          'android'     => 2,//安卓
          'miniProgram' => 3,//小程序
          'manage'      => 4, //后台创建
          'H5'          => 5, //H5页面
          'Pc'          => 6, //Pc页面
        * */
        address_list: [], //收货地址列表
        accountName: "",
        add_form: {
          currentAccountName: "",
          receivedMoney: 0,
          accountList: [],
          deliveryType: "", //配送方式
          customerName: "", //客户名称
          customerId: "",
          remark: "", // 备注
          addressId: "", // 收货地址
          selfRuleId: [],
          selfRuleData: {},
          payType: 3, //支付方式
          particularsType: "", //物流详情
        },
        totalReduceMoney: 0, // 优惠金额
        // 新增地址
        regionName: [],
        //新增收货地址
        form: {
          name: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          address: "",
          mobile: "",
          defaultStatus: 5,
        },
        pageName: "",
        orderId: "",
        goods_index: 0,
        give_goods_index: 0, // 赠品下标
        spec_check: [], // 属性
        self_express_list: [], //自提点
        order_detail: {}, //订单详情
        change_num: 0,
        payWay: 3, //支付方式
        operatorName: "",
        shop_id: "",
        payType_list: [
          { label: "货到付款", value: 3 },
          { label: "先款后货", value: 9 },
        ],
        particularsType_list: [
          { label: "物流专线", value: 4 },
          { label: "物流专车", value: 5 },
        ],
      };
    },
    computed: {
      // 商品总额
      orderAmount() {
        if (!this.saleOrderGoods.length) {
          return 0;
        } else if (this.saleOrderGoods.length === 1) {
          return Number(this.saleOrderGoods[0].subMoney);
        } else {
          let sum = 0;
          this.saleOrderGoods.forEach((item) => {
            sum = this.$NP.plus(sum, Number(item.subMoney) || 0);
          });
          return sum;
        }
      },
      payMoney() {
        return this.$NP.minus(
          this.orderAmount || 0,
          this.totalReduceMoney || 0
        );
      },
    },
    async created() {
      // 配送方式
      await this.getAllDelivery();
      // 获取自提点
      await this.getAllSelfExpressRule();
      this.pageName = this.$route.name;
      this.orderId = this.$route.params.id;
      this.userCenterId = this.$route.params.userCenterId;
      this.add_form.currentAccountName = this.userName;

      if (this.orderId) {
        // 获取订单详情
        await this.getOrderInfoById();
      } else {
        this.pushGoods();
        // 获取暂存信息
        await this.getPauseSave();
      }
    },
    methods: {
      pushGoods() {
        this.saleOrderGoods = [];
        for (let i = 0; i < 1; i++) {
          this.saleOrderGoods.push(this.$_common.deepClone(goodsItem));
        }
      },
      // 拼音商品名称
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      giveawayVisibleChange(visible, index) {
        if (visible) {
          this.give_goods_index = index;
        }
      },
      specSelConfirm(params) {
        console.log(params.goodsD);
        if (params.now_goods_data.isEq === 5) {
          const goods = this.saleOrderGoods.find((item) => {
            return item.goodsId === params.now_goods_data.id;
          });
          if (goods) {
            const repeatGoods = params.goodsD.find(
              (gf) => gf.spec.unitName !== goods.unitName
            );
            if (repeatGoods) {
              this.$message.warning(
                `【${params.now_goods_data.title}】为抄码商品，只能选择一个单位进行下单`
              );
              return;
            }
          } else {
            let unitId = params.goodsD[0].spec.unitId;
            let isRepeat = params.goodsD.every(
              (item) => item.spec.unitId === unitId
            );
            if (!isRepeat) {
              this.$message.warning(
                `【${params.now_goods_data.title}】为抄码商品，只能选择一个单位进行下单`
              );
              return;
            }
          }
        }
        const goodsData = params.goodsD.map((item) => {
          return {
            skuId: item.skuId,
            code: params.now_goods_data.code,
            goodsId: params.now_goods_data.id,
            buyNum: 1,
            shopId: params.now_goods_data.shopId,
            basicGoodsId: params.now_goods_data.basicGoodsId,
            goodsName: params.now_goods_data.title,
            unitName: item.spec.unitName,
            specGroup: item.spec.specGroup,
            inventory: item.spec.inventory,
            salePrice: item.spec.salePrice,
            subMoney: item.spec.salePrice,
            shopName: params.now_goods_data.shopName,
            goodsImages: item.spec.specImage || params.now_goods_data.images[0],
            brandId: params.now_goods_data.brandId,
            brandName: params.now_goods_data.brandName,
            categoryPath: params.now_goods_data.categoryPath,
            categoryName: params.now_goods_data.categoryName,
            conversion: item.spec.conversion,
            barCode: item.spec.barCode,
            storageCode: params.now_goods_data.storage,
            warehouseId: params.now_goods_data.warehouseId,
            originPrice: item.spec.originPrice,
            specType: item.spec.specType,
            supplierId: item.supplierId,
            supplierName: item.supplierName,
            isEq: item.isEq,
            isMaster: item.spec.isMaster,
            isDistribution: item.isDistribution,
            merchantId: item.merchantId,
          };
        });
        // this.saleOrderGoods = this.$_common.unique(
        //   goodsData.concat(this.saleOrderGoods),
        //   ["goodsId", "skuId"]
        // );
        this.saleOrderGoods = goodsData.concat(this.saleOrderGoods);
      },
      // 赠品
      giveawaySpecSelConfirm(params) {
        const goodsData = params.goodsD.map((item) => {
          return {
            skuId: item.skuId,
            code: params.now_goods_data.code,
            goodsId: params.now_goods_data.id,
            buyNum: 1,
            shopId: params.now_goods_data.shopId,
            basicGoodsId: params.now_goods_data.basicGoodsId,
            goodsName: params.now_goods_data.title,
            unitName: item.spec.unitName,
            specGroup: item.spec.specGroup,
            inventory: item.spec.inventory,
            salePrice: item.spec.salePrice,
            subMoney: item.spec.salePrice,
            shopName: params.now_goods_data.shopName,
            goodsImages: item.spec.specImage || params.now_goods_data.images[0],
            brandId: params.now_goods_data.brandId,
            brandName: params.now_goods_data.brandName,
            categoryPath: params.now_goods_data.categoryPath,
            categoryName: params.now_goods_data.categoryName,
            conversion: item.spec.conversion,
            barCode: item.spec.barCode,
            storageCode: params.now_goods_data.storage,
            warehouseId: params.now_goods_data.warehouseId,
            originPrice: item.spec.originPrice,
            specType: item.spec.specType,
            supplierId: item.supplierId,
            supplierName: item.supplierName,
            isEq: item.isEq,
            isMaster: item.spec.isMaster,
            isDistribution: item.isDistribution,
            merchantId: item.merchantId,
          };
        });
        this.giveawayGoods = goodsData.concat(this.giveawayGoods);
      },
      selectSelGoods(id) {
        this.spec_check = this.saleOrderGoods
          .filter((item) => item.goodsId === id)
          .map((item) => {
            return item.skuId;
          });
      },
      giveawaySelectSelGoods(id) {
        this.spec_check = this.giveawayGoods
          .filter((item) => item.goodsId === id)
          .map((item) => {
            return item.skuId;
          });
      },
      // 新增一条商品
      addListGoods() {
        this.saleOrderGoods.push(this.$_common.deepClone(goodsItem));
      },
      // 新增一条赠品
      giveawayAddListGoods() {
        this.giveawayGoods.push(this.$_common.deepClone(goodsItem));
      },
      // 新增地址
      async addShippingAddress() {
        if (
          !this.form.name.trim() ||
          !this.regionName ||
          !this.form.mobile.trim() ||
          !this.form.address.trim()
        ) {
          this.$message.warning("都是必填项不能为空");
          return;
        }
        const data = await addShippingAddress({
          ...this.form,
          customerId: this.add_form.customerId,
        });

        this.$message({
          type: "success",
          message: "添加成功",
        });
        this.AddAddress = false;
        await this.getAllShippingAddress(this.add_form.customerId);
      },
      regionChange(val, params) {
        this.form.provinceCode = val[0];
        this.form.cityCode = val[1];
        this.form.districtCode = val[2];
      },
      // 关闭弹窗
      handleClose() {
        this.form = {};
      },
      // 获取订单详情
      async getOrderInfoById() {
        const { data } = await getOrderInfoById(
          this.$route.params.userCenterId,
          {
            orderId: this.orderId,
          }
        );
        this.order_detail = data;
        this.add_form = {
          accountList: data.accountList || [],
          deliveryType: data.deliveryType, //配送方式
          customerName: data.customerName, //客户名称
          customerId: data.customerId,
          remark: data.remark, // 备注
          addressId: data.receiveData.id, // 收货地址
          selfRuleId: data.selfRuleId,
          selfRuleData: data.selfRuleData,
          receivedMoney: data.receivedMoney,
          payType: Number(data.payType),
        };
        if (this.add_form.deliveryType === 4) {
          this.add_form.deliveryType = 3;
          this.add_form.particularsType = 4;
        }
        if (this.add_form.deliveryType === 5) {
          this.add_form.deliveryType = 3;
          this.add_form.particularsType = 5;
        }
        if (data.receiveData.area) {
          this.address_name =
            data.receiveData.realName +
            " " +
            data.receiveData.mobile +
            " " +
            data.receiveData.area.provinceName +
            "-" +
            data.receiveData.area.cityName +
            "-" +
            data.receiveData.area.districtName +
            "-" +
            data.receiveData.address;
        }

        if (data.accountList && data.accountList.length) {
          this.accountName = data.accountList[0].accountName;
        }
        this.add_form.currentAccountName = data.currentAccountName;
        this.totalReduceMoney = data.totalReduceMoney || 0;
        this.userCenterId = data.userCenterId;
        this.saleOrderGoods = data.goodsData.map((item) => {
          return {
            ...item,
            subMoney: item.totalMoney,
            salePrice: item.price,
            code: item.goodsCode,
            goodsImages: item.images[0],
          };
        });
        if (data.customerId) {
          // 获取客户收货地址列表
          await this.getAllShippingAddress(data.customerId);
        }
        //由于订单是按照店铺拆单的
        // 所以在编辑订单时，增加此订单的商品时应该只能选择本店铺下的商品
        this.shop_id = data.shopId;
        this.account_shopId = data.shopId;
        if (this.add_form.deliveryType === 2) {
          const selfRuleData = JSON.parse(data.selfRuleData);
          this.mobile = selfRuleData.mobile;
          this.address =
            selfRuleData.provinceName +
            " " +
            selfRuleData.cityName +
            " " +
            selfRuleData.districtName +
            " " +
            selfRuleData.address;
        } else {
          const receiveData = data.receiveData;
          this.mobile = receiveData.mobile;
          this.address =
            receiveData.area.provinceName +
            " " +
            receiveData.area.cityName +
            " " +
            receiveData.area.districtName +
            " " +
            receiveData.address;
        }
      },
      // 添加暂存
      async addPauseSave() {
        const params = {
          add_form: this.add_form,
          totalReduceMoney: this.totalReduceMoney,
          saleOrderGoods: this.saleOrderGoods,
          userCenterId: this.userCenterId,
        };
        const data = await addPauseSave({
          key: this.pageName,
          data: params,
        });
        this.$message({
          type: "success",
          message: "暂存成功",
        });
        if (this.systemType === 2) {
          this.$closeCurrentGoEdit("/SingleStore/order/OrderList/waitAudit");
        } else {
          this.$closeCurrentGoEdit("/order/manageO/orderQuery");
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        if (data.add_form) {
          this.add_form = data.add_form;
          if (data.add_form.customerId) {
            await this.getAllShippingAddress(data.add_form.customerId);
          }
          this.totalReduceMoney = data.totalReduceMoney || 0;
          this.saleOrderGoods = data.saleOrderGoods || [goodsItem];
          this.userCenterId = data.userCenterId || 0;
        }
      },
      // 获取配送方式
      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 delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          if (this.systemType === 2) {
            this.$closeCurrentGoEdit("/SingleStore/order/OrderList/waitAudit");
          } else {
            this.$closeCurrentGoEdit("/order/manageO/orderQuery");
          }
        }
      },
      // 提交
      subData() {
        if (this.add_form.deliveryType === 2 && !this.add_form.selfRuleId) {
          this.$message.warning("请选择自提点");
          return;
        }
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            const list = this.saleOrderGoods.filter((item) => item.skuId);
            // 验证抄码商品数量
            const isEqNum = list.every((item) => {
              if (item.isEq === 5 && item.isMaster === 5) {
                return item.otherNum > 0;
              } else {
                return true;
              }
            });
            if (!isEqNum) {
              this.$message.warning("抄码商品其他单位数量不能为0");
              return;
            }
            // 验证商品数量
            const isBuyNum = list.every((item) => item.buyNum > 0);
            if (!isBuyNum) {
              this.$message.warning("请输入大于0的商品数量");
              return;
            }
            // 验证商品单价
            const isSalePrice = list.every((item) => item.salePrice > 0);
            // if (!isSalePrice) {
            //   this.$message.warning("商品单价不能为0");
            //   return;
            // }
            // 验证商品金额
            const isSubMoney = list.every((item) => item.subMoney > 0);
            // if (!isSubMoney) {
            //   this.$message.warning("商品金额不能为0");
            //   return;
            // }
            const saleOrderGoods = list.map((item) => {
              if (!this.orderId) {
                delete item.inventory;
                delete item.enabledLadder;
                delete item.ladderPrice;
              }
              return item;
            });
            if (!saleOrderGoods.length) {
              this.$message.warning("请选择商品");
              return;
            }

            if (
              this.add_form.receivedMoney > 0 &&
              !this.add_form.accountList.length
            ) {
              this.$message.warning("请选择结算账户");
              return;
            }
            if (this.orderId) {
              await this.editOrder(saleOrderGoods);
            } else {
              await this.addOrder(saleOrderGoods);
            }
          }
        });
      },
      // 编辑订单
      async editOrder(saleOrderGoods) {
        if (this.add_form.particularsType) {
          this.add_form.deliveryType = this.add_form.particularsType;
        }
        const goodsData = saleOrderGoods.map((item) => {
          return {
            ...item,
            totalMoney: item.subMoney,
            price: item.salePrice,
            goodsCode: item.code,
            images: [item.goodsImages],
          };
        });
        // console.log(goodsData);
        // return;
        this.sub_loading = true;
        try {
          const data = await newOrderEdit(this.orderId, {
            ...this.order_detail,
            deliveryType: this.add_form.deliveryType,
            customerName: this.add_form.customerName,
            addressId: this.add_form.addressId,
            remark: this.add_form.remark,
            accountList: this.add_form.accountList,
            totalMoney: this.orderAmount,
            payMoney: this.payMoney,
            totalReduceMoney: this.totalReduceMoney || 0,
            receivedMoney: this.add_form.receivedMoney,
            currentAccountName: this.add_form.currentAccountName,
            userCenterId: this.userCenterId,
            customerId: this.add_form.customerId,
            selfRuleId: this.add_form.selfRuleId,
            selfRuleData: this.add_form.selfRuleData,
            goodsData: goodsData,
            payType: this.add_form.payType,
          });
          this.sub_loading = false;
          this.$message({
            type: "success",
            message: "提交成功",
          });
          if (this.systemType === 2) {
            this.$closeCurrentGoEdit("/SingleStore/order/OrderList/waitAudit");
          } else {
            this.$closeCurrentGoEdit("/order/manageO/orderQuery");
          }
        } finally {
          this.sub_loading = false;
        }
      },
      // 新增订单
      async addOrder(saleOrderGoods) {
        if (this.totalReduceMoney === "") {
          this.totalReduceMoney = 0;
        }
        if (this.add_form.particularsType) {
          this.add_form.deliveryType = this.add_form.particularsType;
        }
        let params = {
          deliveryType: this.add_form.deliveryType,
          customerName: this.add_form.customerName,
          addressId: this.add_form.addressId,
          remark: this.add_form.remark,
          accountList: this.add_form.accountList,
          currentAccountName: this.add_form.currentAccountName,
          receivedMoney: this.add_form.receivedMoney,
          lists: saleOrderGoods,
          totalMoney: this.orderAmount,
          payMoney: this.payMoney,
          totalReduceMoney: this.totalReduceMoney || 0,
          userCenterId: this.userCenterId,
          customerId: this.add_form.customerId,
          selfRuleId: this.add_form.selfRuleId,
          selfRuleData: this.add_form.selfRuleData,
          operatorName: this.userName,
          payType: this.add_form.payType,
        };
        this.sub_loading = true;
        try {
          const data = await newAddOrder(params);
          this.sub_loading = false;
          this.$message({
            type: "success",
            message: "提交成功",
          });
          await this.delPauseSave();

          if (this.systemType === 2) {
            this.$closeCurrentGoEdit("/SingleStore/order/OrderList/waitAudit");
          } else {
            this.$closeCurrentGoEdit("/order/manageO/orderQuery");
          }
        } finally {
          this.sub_loading = false;
        }
      },
      // 选择商品
      async selGoods(val) {
        if (val.length) {
          //抄码商品只能选择一个单位进行下单
          let arr = [];
          let isEqMore = false;

          for (let i in val) {
            const item = val[i];
            if (item.isEq === 5) {
              if (
                arr.find(
                  (fin) => fin.id === item.id && fin.unitId !== item.unitId
                )
              ) {
                this.$message.warning(
                  "抄码商品只能选择一个单位进行下单，请重新勾选"
                );
                isEqMore = true;
                break;
              } else {
                arr.push(item);
              }
            }
          }
          if (isEqMore) {
            return;
          }

          let goodsData = val.map((item) => {
            let salePrice = 0;
            if (item.enabledLadder) {
              salePrice = item.ladderPrice[0].price;
            } else {
              salePrice = item.salePrice;
            }
            return {
              goodsName: item.title,
              skuId: item.skuId,
              code: item.code,
              goodsId: item.id,
              buyNum: 1,
              otherNum: "",
              shopId: item.shopId,
              basicGoodsId: item.basicGoodsId,
              unitName: item.unitName,
              unitId: item.unitId,
              specGroup: item.specGroup,
              inventory: item.inventory,
              salePrice: salePrice,
              subMoney: item.salePrice,
              shopName: item.shopName,
              goodsImages: item.images[0],
              brandId: item.brandId,
              brandName: "",
              categoryPath: item.categoryPath,
              categoryName: item.categoryName,
              conversion: item.conversion,
              barCode: "",
              storageCode: "",
              warehouseId: item.warehouseId,
              originPrice: item.originPrice,
              specType: item.specType,
              enabledLadder: item.enabledLadder,
              ladderPrice: item.ladderPrice,
              supplierId: item.supplierId,
              supplierName: item.supplierName,
              isEq: item.isEq,
              isMaster: item.isMaster,
              isDistribution: item.isDistribution,
              merchantId: item.merchantId,
            };
          });
          const saleOrderGoods = this.$_common.deepClone(this.saleOrderGoods);
          goodsData = goodsData.filter((item) => {
            // 抄码商品只能选择一个单位进行下单
            let indexF = -1;
            if (item.isEq === 5) {
              indexF = saleOrderGoods.findIndex(
                (itemF) =>
                  itemF.goodsId === item.goodsId && itemF.unitId !== item.unitId
              );
            }
            return indexF === -1;
          });

          const goodsArr = saleOrderGoods.filter((item) => item.skuId);
          const noSkuArr = saleOrderGoods.filter((item) => !item.skuId);
          this.saleOrderGoods = [...goodsArr, ...goodsData].concat(noSkuArr);
        }
      },
      // 选择赠品商品
      async giveawaySelGoods(val) {
        if (val.length) {
          const goodsData = val.map((item) => {
            let salePrice = 0;
            if (item.enabledLadder) {
              salePrice = item.ladderPrice[0].price;
            } else {
              salePrice = item.salePrice;
            }
            return {
              goodsName: item.title,
              skuId: item.skuId,
              code: item.code,
              goodsId: item.id,
              buyNum: 1,
              otherNum: "",
              shopId: item.shopId,
              basicGoodsId: item.basicGoodsId,
              unitName: item.unitName,
              specGroup: item.specGroup,
              inventory: item.inventory,
              salePrice: salePrice,
              subMoney: item.salePrice,
              shopName: item.shopName,
              goodsImages: item.images[0],
              brandId: item.brandId,
              brandName: "",
              categoryPath: item.categoryPath,
              categoryName: item.categoryName,
              conversion: item.conversion,
              barCode: "",
              storageCode: "",
              warehouseId: item.warehouseId,
              originPrice: item.originPrice,
              specType: item.specType,
              enabledLadder: item.enabledLadder,
              ladderPrice: item.ladderPrice,
              supplierId: item.supplierId,
              supplierName: item.supplierName,
              isEq: item.isEq,
              isDistribution: item.isDistribution,
              merchantId: item.merchantId,
            };
          });

          // this.saleOrderGoods = this.$_common.unique(
          //   goodsData.concat(this.saleOrderGoods),
          //   ["goodsId", "skuId"]
          // );
          const goodsArr = this.giveawayGoods.filter((item) => item.skuId);
          const noSkuArr = this.giveawayGoods.filter((item) => !item.skuId);
          // this.saleOrderGoods = this.$_common
          //   .unique([...goodsArr, ...goodsData], ["goodsId", "skuId"])
          //   .concat(noSkuArr);
          this.giveawayGoods = [...goodsArr, ...goodsData].concat(noSkuArr);
        }
      },

      // 修改购物车数量
      async updateBuyNum(index) {
        const target = this.$_common.deepClone(this.saleOrderGoods);
        let salePrice = target[index].salePrice;
        let inventory = target[index].inventory;
        let isDistribution = target[index].isDistribution;
        if (isDistribution === 4) {
          if (target[index].buyNum > inventory) {
            target[index].buyNum = target[index].inventory;
          }
        }
        // 根据阶梯价判断销售价
        if (target[index].enabledLadder) {
          let priceObj = target[index].ladderPrice.find(
            (item) =>
              target[index].buyNum >= item.from &&
              target[index].buyNum <= item.to
          );
          salePrice = priceObj ? priceObj.price : target[index].salePrice;
        }
        target[index].subMoney = this.$NP.times(
          salePrice,
          target[index].buyNum
        );
        target[index].salePrice = salePrice;
        console.log(target);
        this.saleOrderGoods = target;
      },
      // 修改购物车数量
      async giveawayUpdateBuyNum(index) {
        const target = this.$_common.deepClone(this.giveawayGoods);
        let salePrice = target[index].salePrice;
        let buyNum = target[index].buyNum;
        let inventory = target[index].inventory;
        let isDistribution = target[index].isDistribution;
        if (isDistribution === 4) {
          if (buyNum > inventory) {
            target[index].buyNum = target[index].inventory;
          }
        }
        // 根据阶梯价判断销售价
        if (target[index].enabledLadder) {
          let priceObj = target[index].ladderPrice.find(
            (item) => buyNum >= item.from && buyNum <= item.to
          );
          salePrice = priceObj ? priceObj.price : target[index].salePrice;
        }
        target[index].subMoney = this.$NP.times(salePrice, buyNum);
        target[index].salePrice = salePrice;
        this.giveawayGoods = target;
      },
      // 选择客户
      customerSel(val, list) {
        const row = list[0];
        this.add_form.customerId = row.id;
        this.account_shopId = row.shopId;
        this.userCenterId = row.userCenterId;
        this.add_form.addressId = "";
        this.address_name = "";
        this.saleOrderGoods = [this.$_common.deepClone(goodsItem)];
        if (this.add_form.deliveryType !== 2) {
          this.getAllShippingAddress(this.add_form.customerId);
        }
      },
      // 选择结算账户
      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,
          },
        ];
      },
      // 获取客户收货地址列表
      async getAllShippingAddress(id) {
        const { data } = await getAllShippingAddress(id);
        if (data.length) {
          this.add_form.addressId = data[0].id;
          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.address_name = this.address_list[0].addressName;
        } else {
          this.address_list = [];
        }
      },
      // 移出购物车
      async deleteRowGoods(index) {
        if (this.saleOrderGoods.length > 1) {
          this.saleOrderGoods.splice(index, 1);
        } else {
          this.$message.warning("至少保留一条商品");
        }
      },
      // 移出赠品购物车
      async giveawayDeleteRowGoods(index) {
        this.giveawayGoods.splice(index, 1);
      },
      // 获取自提点
      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;
          this.add_form.selfRuleData = data[0].setData;
        }
      },
      // 配送方式
      deliveryTypeChange(val) {
        this.payType_list.forEach((item) => {
          if (val === item.value) {
            this.order_detail.payTypeMsg = item.label;
          }
        });
        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;
            this.add_form.selfRuleData = target.setData;
          }
        }
      },
      addressChange(command) {
        this.add_form.addressId = command;
        this.address_name = this.address_list.find(
          (item) => item.id === command
        ).addressName;
      },
      closeDialog(formName) {
        this.regionName = [];
        this.$refs[formName].resetFields();
      },
      // 选择自提点
      selfRuleIdChange(val) {
        const data = this.self_express_list.find((item) => item.id === val);
        this.add_form.selfRuleData = data ? data.setData : {};
      },
    },
  };
</script>
<style scoped lang="scss">
  .add-div {
    text-align: center;
    padding-top: 10px;
  }
  .price-div {
    padding-top: 10px;
    text-align: right;
    .de_val {
      color: $base-color-red;
      padding-right: 20px;
    }
  }
</style>
