<template>
  <view class="addAndEditProduct-container">
    <navBar
      class="nav-bar"
      :statusBar="true"
      :border="false"
      :fixed="true"
      :height="'44px'"
      :rightWidth="40"
      :leftWidth="30"
      :title="isAdd ? '添加商品' : '编辑商品'"
      backgroundColor="#fff"
    >
      <block slot="left">
        <u-icon
          name="arrow-left"
          color="#000"
          size="20"
          @click="pageBack()"
        ></u-icon>
      </block>
      <block slot="right" v-if="!isAdd">删除</block>
    </navBar>
    <view class="addAndEditProduct-content">
      <u--form
        labelPosition="left"
        :model="form"
        ref="uForm"
        label-width="100"
        :rules="rules"
      >
        <u-form-item
          label="商品名称"
          prop="product_name"
          class="form-item"
          required
        >
          <u--input
            v-model="form.product_name"
            placeholder="请输入商品名称"
            border="none"
            clearable
          ></u--input>
        </u-form-item>
        <u-form-item
          label="商品分类"
          prop="category_name"
          class="form-item"
          required
          @click="hadnerShowClassifyListPopup()"
        >
          <u--input
            v-model="form.category_name"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择商品分类"
            border="none"
            @click="hideKeyboard()"
          ></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="商品主图" prop="img" class="form-item" required>
          <!-- <u-upload
            class="shop2-2-upload"
            @afterRead="afterRead($event, 'businessLicense')"
            @delete="deletePic($event, 'businessLicense')"
            accept="image"
            :fileList="form.businessLicenseFiles"
            :max-count="1"
            width="125"
            height="88"
            :maxSize="maxSize"
            @oversize="overSize"
            uploadText="上传图片"
          ></u-upload> -->
          <imgUpload
            :imgArr="primaryImg"
            uploadImgCount="1"
            imgCount="1"
            :imgSize="8"
            :header="header"
            :async="true"
            :config="config"
            :isAdd="isAdd"
            url="https://mall.gpxscs.cn/mobile/shop/oss/upload"
            :formData="formData"
            @result="handerResultUrl($event, 'primary')"
          ></imgUpload>
        </u-form-item>
        <u-form-item label="商品附图" class="form-item">
          <imgUpload
            :imgArr="viceImg"
            uploadImgCount="1"
            imgCount="5"
            :imgSize="8"
            :header="header"
            :async="true"
            :config="config"
            :isAdd="isAdd"
            url="https://mall.gpxscs.cn/mobile/shop/oss/upload"
            :formData="formData"
            @result="handerResultUrl($event, 'vice')"
          ></imgUpload>
        </u-form-item>
        <u-form-item
          label="商品卖点"
          prop="product_tips"
          :class="[
            'form-item',
            { 'form-item-margin-top-20': isUnfold },
            { 'form-item-margin-20': !isUnfold },
          ]"
        >
          <u--textarea
            v-model="form.product_tips"
            placeholder="15字以内突出商品特点"
            count
            :autoHeight="true"
            maxlength="15"
          ></u--textarea>
        </u-form-item>
        <u-form-item
          label="商品类型"
          class="form-item"
          labelWidth="80"
          v-if="form.category_name"
        >
          <u-radio-group v-model="form.kind_id" placement="row" shape="circle">
            <u-radio
              :customStyle="{ marginRight: '28rpx' }"
              v-for="(item, index) in commodityTypeRadioList"
              :key="index"
              :label="item.name"
              :name="item.value"
              :disabled="!categoryVirtualEnable"
            ></u-radio>
          </u-radio-group>
        </u-form-item>

        <u-form-item
          v-if="isUnfold"
          label="商品货号"
          prop="product_number"
          class="form-item"
        >
          <u--input
            v-model="form.product_number"
            placeholder="请输入商品货号"
            border="none"
            clearable
          ></u--input>
        </u-form-item>
        <u-form-item
          v-if="isUnfold"
          label="购买上限"
          prop="product_buy_limit"
          class="form-item"
        >
          <u--input
            v-model="form.product_buy_limit"
            placeholder="请输入购买上限"
            border="none"
            clearable
          ></u--input>
        </u-form-item>
        <u-form-item
          v-if="isUnfold"
          label="开售时间"
          prop="product_state_id"
          class="form-item form-sale-time-item"
        >
          <u-radio-group
            v-model="form.product_state_id"
            placement="row"
            shape="circle"
          >
            <u-radio
              :customStyle="{ marginRight: '28rpx' }"
              v-for="(item, index) in saleTimeRadioList"
              :key="index"
              :label="item.name"
              :name="item.value"
            ></u-radio>
          </u-radio-group>
          <view
            class="sale-time"
            v-if="form.product_state_id == 1002"
            @click="showSaleTime = true"
          >
            {{ form.product_sale_time || "预计上架时间" }}
          </view>
        </u-form-item>
        <u-form-item
          v-if="isUnfold"
          label="库存锁定"
          prop="product_inventory_lock"
          class="form-item"
        >
          <u-radio-group
            v-model="form.product_inventory_lock"
            placement="row"
            shape="circle"
          >
            <u-radio
              :customStyle="{ marginRight: '28rpx' }"
              v-for="(item, index) in inventoryRadioList"
              :key="index"
              :label="item.name"
              :name="item.value"
            ></u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item
          v-if="isUnfold"
          style="margin-bottom: 40rpx"
          label="商品描述"
          prop="product_detail"
          class="form-item"
        >
          <u--textarea
            v-model="form.product_detail"
            placeholder="200字以内介绍商品描述"
            count
            :autoHeight="true"
            maxlength="200"
          ></u--textarea>
        </u-form-item>
        <u-form-item
          label="售卖规格"
          class="form-item form-item-specification"
          labelWidth="80"
          @click="handerRightPopup"
          required
        >
          <view class="total-content">
            <view class="total-name">
              共{{ specificationInfoList.length || 1 }}个规格
            </view>
            <u-icon name="arrow-right"></u-icon>
          </view>
          <view class="specification-content">
            <view
              class="specification-item"
              v-for="(item, index) of specificationInfoList"
            >
              <view class="specification-name">{{ item.spec_item_name }}</view>
              <view class="specification-info">
                <view class="info-item">
                  <view class="specification-num">
                    属性编号：{{ item.item_number }}
                  </view>
                  <view class="specification-num">
                    库存：{{ item.item_quantity || item.item_quantity_2 }}
                  </view>
                </view>
                <view class="info-item">
                  <view class="specification-num">
                    市场价：{{
                      item.item_market_price || item.item_market_price_2
                    }}
                  </view>
                  <view class="specification-num">
                    零售价：{{ item.item_unit_price || item.item_unit_price_2 }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </u-form-item>
      </u--form>
      <view class="tips-content">
        <view class="tips">
          还可以设置购买上限、店内码/货号、商品描述、 开售时间、 库存锁定
        </view>

        <u-button
          :plain="true"
          :hairline="true"
          shape="circle"
          class="btn-unfold"
          @click="isUnfold = !isUnfold"
        >
          <block>
            {{ isUnfold ? "收起部分" : "  展示全部" }}

            <u-icon
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-up"
              color="#000"
              v-if="isUnfold"
              size="12"
            ></u-icon>
            <u-icon
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              color="#000"
              size="12"
              v-else
            ></u-icon>
          </block>
        </u-button>
      </view>
      <view class="bottom-btn">
        <view class="bottom-list">
          <u-button
            class="bottom-btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerAddAndEditPopup()"
          >
            {{ isAdd ? "添加" : "保存" }}
          </u-button>
        </view>
      </view>
    </view>
    <u-popup
      class="right-popup"
      zIndex="998"
      :overlay="false"
      :show="showRightPopup"
      mode="right"
    >
      <specificationOfGood
        :commoditSpecificationBaseInfo="commoditSpecificationBaseInfo"
        :sonSpecificationInfoList="specificationInfoList"
        :productInfoByPid="productInfoByPid"
        :typeId="typeId"
        @handerSpecificationInfoList="handerSpecificationInfoList"
        @pageBack="showRightPopup = false"
        :isAdd="isAdd"
      ></specificationOfGood>
    </u-popup>
    <u-popup
      class="affirm-popup"
      zIndex="10077"
      :show="showBackPopup"
      mode="center"
    >
      <view class="affirm-popup-content">
        <view class="affirm-popup-title">确认退出</view>
        <view class="affirm-popup-tips">
          退出后已编辑商品信息将不被保存，是否退出
        </view>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="showBackPopup = false"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerPageBack"
          >
            退出
          </u-button>
        </view>
      </view>
    </u-popup>
    <tki-tree
      ref="tkitree"
      :range="baTreePickerList"
      :foldAll="true"
      rangeKey="category_name"
      idKey="category_id"
      title="选择商品分类"
      @confirm="treeConfirm"
      @cancel="treeCancel"
    ></tki-tree>
    <u-datetime-picker
      ref="datetimePicker"
      :show="showSaleTime"
      v-model="productSaleTime"
      @cancel="showSaleTime = false"
      @confirm="handerConfirmSaleTime"
      mode="datetime"
    ></u-datetime-picker>
    <u-toast ref="uToast"></u-toast>
    <u-loading-page
      class="loading-page"
      :loading="loadingPage"
      loading-text="加载中..."
    ></u-loading-page>
  </view>
</template>

<script>
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
import { mapState } from "vuex";
import { GetCommodityClassify } from "@/api/warehouse/classifyList";
import imgUpload from "@/components/poiuy-uImgUpload/imgUpload.vue";
import {
  UpdateCommodityInfo,
  GetCommoditSpecification,
  GetCommodityBaseInfo,
  GetClassifyInfo,
  GetCommoditSpecificationBaseInfo,
} from "@/api/warehouse/commodity";
import tkiTree from "./components/tree/tree";
import specificationOfGood from "./specificationOfGood.vue";
import store from "../../../store";
export default {
  name: "addAndEditProduct",
  props: {
    productItem: {
      type: Object,
      default: () => ({
        product_id: null,
      }),
    },
    isAdd: {
      type: Boolean,
      default: true,
    },
  },
  components: {
    navBar,
    imgUpload,
    tkiTree,
    specificationOfGood,
  },
  data() {
    return {
      form: {
        product_video: "",
        product_buy_limit: 0, // 购买上限
        product_sale_time: "",
        product_number: "",
        product_name: "", // 商品名称
        kind_id: 1201,
        product_inventory_lock: 1001,
        payment_type_id: 0,
        product_state_id: 1001,
        contract_type_ids: [],
        product_transport_id: [],
        transport_type_id: 38,
        store_category_ids: [],
        product_service: "",
        product_param: "",
        product_detail: "",
        product_id: undefined,
        product_tips: "",
        voucher_activity_id: "",
        category_id: "",
        category_name: "",
        kind_id: 1201,
        coupon_type_id: "",
        store_id: 0,
      },
      productDetail: {
        product_detail: "",
        product_tags: [],
      },
      valid: {
        product_service_contactor_flag: 1,
        product_service_date_flag: 0,
        product_valid_period: 1001,
        product_valid_type: 1001,
      },
      rules: {
        product_name: [
          {
            required: true,
            message: "请输入规格名称",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        type_category_name: [
          {
            required: true,
            message: "请选择商品分类",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
      maxSize: 10 * 1024 * 1024,
      primaryImg: [],
      header: [],
      config: {
        delIcon: "", //删除图片icon
        resultTip: true, //结果提示
        resultType: "1", //结果展示类型
        loadIcon: "", //加载时的图标
        loadText: "", //加载时的文字
      },
      formData: {
        perm_key: "",
      },
      viceImg: [],
      isUnfold: false,
      saleTimeRadioList: [
        {
          name: "立即开售",
          value: 1001,
        },
        {
          name: "定时开售",
          value: 1002,
        },
      ],
      inventoryRadioList: [
        {
          name: "下单锁定",
          value: 1001,
        },
        {
          name: "支付锁定",
          value: 1002,
        },
      ],
      commodityTypeRadioList: [
        {
          name: "实体商品",
          value: 1201,
        },
        {
          name: "虚拟商品",
          value: 1202,
        },
        {
          name: "电子卡券",
          value: 1203,
        },
      ],
      showSaleTime: false,
      productSaleTime: Number(new Date()),
      baTreePickerList: [],
      showRightPopup: false,
      commoditSpecificationBaseInfo: {},
      selectCommodisItems: [],
      typeId: 0,
      specificationInfoList: [],
      categoryVirtualEnable: false,
      showBackPopup: false,
      loadingPage: false,
      productInfoByPid: {
        shop_product_assist_index: [],
        shop_product_detail: {},
        shop_product_image: [],
        shop_product_index: {},
        shop_product_info: {},
      },
    };
  },
  computed: {
    ...mapState(["user", "ukey"]),
  },
  onLoad: function (options) {},
  onReady() {},
  onShow() {
    // this.classifyItem = form;
  },

  mounted() {
    this.formData.perm_key = uni.getStorageSync("ukey") || "";
    this.getCommodityClassify();
    if (!this.isAdd) {
      this.form = { ...this.form, ...this.productItem };

      console.log(this.form);

      this.loadingPage = true;
      this.getCommodityBaseInfo(this.productItem.product_id);
    }
  },
  methods: {
    pageBack() {
      this.showBackPopup = true;
    },
    handerPageBack() {
      this.$emit("pageBack");
    },
    overSize(e) {
      uni.$u.toast("上传图片大小不能超过10MB!");
    },
    handerResultUrl(e, type) {
      if (type == "primary") {
        this.primaryImg = [...new Set([...this.primaryImg, ...e.all])];
      } else {
        this.viceImg = [...new Set([...this.viceImg, ...e.all])];

        console.log(this.viceImg);
      }
    },
    async getCommodityBaseInfo(product_id) {
      let params = {
        product_id: product_id,
      };

      let res = await GetCommodityBaseInfo(params);
      if (res && res.status == 200) {
        this.productInfoByPid = res.data;

        this.primaryImg = this.productInfoByPid.shop_product_image.map(
          (item) => item.item_image_default
        );

        if (
          this.productInfoByPid.shop_product_image[0].item_image_other.length >
          0
        ) {
          this.viceImg =
            this.productInfoByPid.shop_product_image[0].item_image_other.split(
              ","
            );
        } else {
          this.viceImg = [];
        }

        console.log(this.viceImg);
        await this.getClassifyInfo(
          this.productInfoByPid.shop_product_index.category_id
        );
        await this.getCommoditSpecificationBaseInfo(
          this.productInfoByPid.shop_product_index.type_id,
          product_id
        );
      }
    },
    async getClassifyInfo(category_id) {
      let params = {
        category_id: category_id,
      };
      let res = await GetClassifyInfo(params);
      if (res && res.status == 200) {
        this.form.category_name = res.data.category_name;
        this.form.category_id = res.data.category_id;
      }
    },
    async getCommodityClassify() {
      this.loadingClassIfy = true;
      let res = await GetCommodityClassify();
      if (res && res.status == 200) {
        const classifyList = res.data;
        if (classifyList.length > 0) {
          this.baTreePickerList = classifyList.map((item) => {
            // 创建父节点，并保留所有原始字段
            const parentNode = {
              ...item, // 保留所有原始数据
              children: null, // 先初始化为 null
            };

            // 如果有子分类，递归处理
            if (item.sub && item.sub.length > 0) {
              parentNode.children = item.sub.map((subItem) => ({
                ...subItem, // 保留所有子分类的原始数据
              }));
            }

            return parentNode;
          });
        }
      }
      this.loadingClassIfy = false;
    },
    async getCommoditSpecification() {
      let params = {
        product_id: this.productItem.product_id,
      };

      let res = await GetCommoditSpecification(params);
      if (res && res.status == 200) {
        this.selectCommodisItems = res.data;

        // 1. 解析产品规格模板
        let productSpec = this.productInfoByPid.shop_product_info.product_spec;
        try {
          productSpec = JSON.parse(productSpec);
          if (!Array.isArray(productSpec)) {
            productSpec = [productSpec]; // 确保是数组格式
          }

          // 2. 创建规格项映射表 {itemId: 完整规格信息}
          const specItemMap = [];
          productSpec.forEach((specGroup) => {
            if (specGroup.item && Array.isArray(specGroup.item)) {
              specGroup.item.forEach((item) => {
                specItemMap.push(item.id);
              });
            }
          });

          const specificationInfoList1 = this.selectCommodisItems
            .map((item) => {
              try {
                // 解析规格数据（兼容字符串和对象）
                const itemSpec =
                  typeof item.item_spec === "string"
                    ? JSON.parse(item.item_spec)
                    : item.item_spec;

                if (Array.isArray(itemSpec) && itemSpec.length > 0) {
                  const firstSpec = itemSpec[0];

                  // 匹配规格逻辑
                  if (firstSpec.item && firstSpec.item.id) {
                    const matchedSpec = specItemMap.find(
                      (id) => id == firstSpec.item.id
                    );

                    if (matchedSpec) {
                      return {
                        ...item,
                        spec_item_id: matchedSpec,
                        item_is_default: Boolean(item.item_is_default),
                        // 保留原始数据（调试用）
                      };
                    }
                  }
                }
              } catch (e) {
                console.error(`处理商品 ${item.item_id} 时出错:`, e);
              }
            })
            .filter((item) => item != undefined);

          const specificationInfoList2 =
            this.commoditSpecificationBaseInfo.specs[0].specItems
              .map((item) => {
                if (specItemMap.includes(item.spec_item_id)) {
                  return item;
                }
              })
              .filter((item) => item != undefined);

          this.specificationInfoList = specificationInfoList1.map((item) => {
            // 找到匹配的 specItem
            const matchedSpecItem = specificationInfoList2.find(
              (specItem) => specItem.spec_item_id === item.spec_item_id
            );

            // 如果找到匹配项，则合并
            if (matchedSpecItem) {
              return {
                ...item, // 保留原 item 的所有属性
                ...matchedSpecItem, // 覆盖或添加 specItem 的属性
              };
            }
            return item; // 如果没有匹配项，返回原 item
          });

          if (this.specificationInfoList.length == 0) {
            debugger;
          }
          console.log(this.specificationInfoList);
        } catch (e) {
          console.error("解析productSpec失败:", e);
        }
      }

      this.loadingPage = false;
    },
    async getCommoditSpecificationBaseInfo(type_id) {
      let params = {
        type_id: type_id,
        product_id: this.productItem.product_id,
      };

      let res = await GetCommoditSpecificationBaseInfo(params);
      if (res && res.status == 200) {
        this.commoditSpecificationBaseInfo = res.data;

        if (!this.isAdd) {
          this.getCommoditSpecification();
        }
      }
    },
    handerConfirmSaleTime(e) {
      this.productSaleTime = e.value;
      this.form.product_sale_time = this.$u.timeFormat(
        this.productSaleTime,
        "yyyy-mm-dd hh:MM"
      );

      this.showSaleTime = false;
    },
    hadnerShowClassifyListPopup() {
      this.$refs.tkitree._show();
    },
    handerRightPopup() {
      if (this.form.category_name == "") {
        this.$refs.uToast.show({
          message: "请选择分类",
          type: "error",
          duration: 1000,
        });

        return;
      }

      this.showRightPopup = true;
    },
    treeConfirm(list) {
      if (list.length > 1) {
        this.form.category_name = list[1].category_name;
        this.form.category_id = list[1].category_id;
      } else {
        this.form.category_name = list[0].category_name;
        this.form.category_id = list[0].category_id;
      }
      const typeId = list.length > 1 ? list[1].type_id : list[0].type_id;
      this.categoryVirtualEnable =
        list.length > 1
          ? list[1].category_virtual_enable
          : list[0].category_virtual_enable;

      this.typeId = typeId;
      this.getCommoditSpecificationBaseInfo(typeId);
    },
    treeCancel() {
      this.$refs.tkitree._hide();
    },
    handerSpecificationInfoList(specificationInfoList) {
      this.specificationInfoList = specificationInfoList;

      console.log(this.specificationInfoList);
    },
    handerAddAndEditPopup() {
      this.$refs.uForm.validate().then(async (valid) => {
        if (this.primaryImg.length <= 0) {
          this.$refs.uToast.show({
            message: "请选择上传主图",
            type: "error",
            duration: 1000,
          });

          return;
        }

        if (this.specificationInfoList.length <= 0) {
          this.$refs.uToast.show({
            message: "请选择选择规格",
            type: "error",
            duration: 1000,
          });

          return;
        }

        const productItems = this.specificationInfoList.map((item) => {
          const key = String(item.spec_id) || item.spec_item_ids;
          const key2 = String(item.spec_id) + "_" + String(item.spec_item_id);
          const color_img = this.viceImg.map((item) => item.url);
          const mainMColorimg = this.primaryImg.map((item) => item.url);
          let obj = {
            color_img: color_img,
            item_is_default: item.item_is_default,
            item_market_price:
              item.item_market_price_2 || item.item_market_price,
            item_number: item.item_number,
            item_quantity: item.item_quantity_2 || item.item_quantity,
            item_unit_points: "0", //积分
            item_unit_price: item.item_unit_price_2 || item.item_unit_price,
            main_color_img: mainMColorimg.toString(),
            product_spec:
              item.spec_item_id > 0
                ? JSON.stringify([
                    {
                      id: item.spec_id,
                      name: this.commoditSpecificationBaseInfo.specs[0]
                        .spec_name,
                      item: {
                        id: item.spec_item_id,
                        name: item.spec_item_name,
                      },
                    },
                  ])
                : "[]",
          };

          if (this.isAdd) {
            obj.category_id = this.form.category_id;
            obj.siid = String(item.spec_item_id || "");
          }

          if (item.spec_item_name && item.spec_item_id) {
            obj[key] = item.spec_item_name;
            obj[key2] = item.spec_item_id;
          }

          if (!this.isAdd) {
            obj.color_id = 0;
            obj.item_advice_price = 0;
            obj.colorImg = color_img;
            obj.siid = String(item.spec_item_id);
          }

          if (item.item_enable) {
            obj.item_enable = item.item_enable;
          } else {
            obj.item_enable = 1001;
          }

          if (item.item_barcode) {
            obj.item_barcode = item.item_barcode;
          }

          if (item.item_id) {
            obj.item_id = item.item_id;
          }

          return obj;
        });

        const productSpec = this.specificationInfoList.reduce((acc, item) => {
          const existingSpec = acc.find((spec) => spec.id === item.spec_id);

          if (existingSpec) {
            existingSpec.item.push({
              id: item.spec_item_id,
              name: item.spec_item_name,
            });
          } else {
            acc.push({
              id: item.spec_id,
              item: [
                {
                  id: item.spec_item_id,
                  name: item.spec_item_name,
                },
              ],
            });
          }

          return acc;
        }, []);

        console.log(this.form.product_param);

        let params = {
          productObj: {
            assists: {},
            assistsIndex: [],
            brand_id: 0,
            productBase: {
              category_id: this.form.category_id,
              contract_type_ids: [],
              kind_id: this.form.kind_id || 1201,
              product_detail: "",
              product_inventory_lock: this.form.product_inventory_lock,
              product_name: this.form.product_name,
              product_number: this.form.product_number,
              product_param: this.form.product_param || "",
              product_sale_time: this.form.product_sale_time,
              product_service: this.form.product_service || "",
              product_state_id: this.form.product_state_id,
              product_tips: this.form.product_tips,
              product_transport_id: this.form.product_transport_id,
              product_video: this.form.product_video,
              store_category_ids: this.form.store_category_ids || [],
              text_category_id: this.form.category_name,
              transport_type_id: this.form.transport_type_id,
            },
            productDetail: this.productDetail,
            productSpec: productSpec,
            valid: this.isAdd ? {} : this.valid,
          },
          productItems: productItems,
        };

        console.log("未编辑params", params);

        if (!this.isAdd) {
          var productTransportId =
            this.productInfoByPid.shop_product_index.product_transport_id
              .split(",")
              .map((item) => Number(item));

          var voucherAactivityId =
            this.productInfoByPid.shop_product_index.voucher_activity_id;

          params.productObj.productBase = {
            ...params.productObj.productBase,
            category_name: this.form.category_name,
            coupon_type_id: this.form.coupon_type_id || "",
            payment_type_id: this.form.payment_type_id || 0,
            product_buy_limit: this.form.product_buy_limit,
            product_id: this.form.product_id,
            product_transport_id: productTransportId,
            voucher_activity_id:
              voucherAactivityId || Number(voucherAactivityId),
            store_id: this.form.store_id,
          };

          delete params.productObj.productBase.text_category_id;

          params.productObj.productDetail = {
            product_detail: this.form.product_detail || "",
            product_param: "",
            product_service: "",
            product_tags: [],
          };
        }

        console.log(params);

        let res = await UpdateCommodityInfo({
          productObj: JSON.stringify(params.productObj),
          productItems: JSON.stringify(params.productItems),
        });
        // let res = {};
        if (res && res.status == 200) {
          this.$refs.uToast.show({
            message: this.isAdd ? "添加成功" : "修改成功",
            type: "succeed",
            duration: 1000,
            zIndex: 12000,
            position: "top",
          });
          if (this.isAdd) {
            this.form = {
              product_video: "",
              product_buy_limit: undefined,
              product_sale_time: "",
              product_number: "",
              product_name: "", // 商品名称
              kind_id: 1201,
              product_inventory_lock: 1001,
              payment_type_id: 0,
              product_state_id: 1001,
              contract_type_ids: [],
              product_transport_id: [],
              transport_type_id: 38,
              store_category_ids: [],
              product_service: "",
              product_param: "",
              product_detail: "",
              product_id: undefined,
              product_tips: "",
              voucher_activity_id: "",
              category_id: "",
              category_name: "",
              kind_id: 1201,
            };
            this.primaryImg = [];
            this.viceImg = [];
            this.specificationInfoList = [];
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.addAndEditProduct-container {
  width: 100vw;
  height: calc(100vh - 120rpx);
  overflow: auto;

  .nav-bar {
    ::v-deep.uni-navbar__content {
      z-index: 1100;
    }
  }

  .addAndEditProduct-content {
    .u-form {
      background: #f5f6fa;

      .form-item {
        background: #fff;
        padding: 0 40rpx;
      }

      .form-item-margin-top-20 {
        margin-top: 40rpx;
      }

      .form-item-margin-20 {
        margin: 40rpx 0;
      }

      .form-sale-time-item {
        ::v-deep.u-form-item__body__right__content__slot {
          display: flex;
          flex-flow: column;
          align-items: normal;
        }

        .sale-time {
          margin: 40rpx 0;
          background: #eeeeee;
          padding: 20rpx;
          color: #6666;
        }
      }

      .form-item-specification {
        ::v-deep.u-form-item__body__right__content__slot {
          display: flex;
          flex-flow: column;
          align-items: normal;
        }

        .total-content {
          display: flex;
          justify-content: space-between;
          margin: 8px 0 8px 8px;
          font-weight: bold;
        }

        .specification-content {
          background: #f5f6fa;
          border-radius: 16rpx;

          .specification-item {
            display: flex;
            flex-flow: column;
            justify-content: space-between;
            padding: 8px;

            .specification-name {
              margin: 3px 0;
              font-size: 16px;
              font-weight: bold;
            }

            .specification-info {
              display: flex;
              justify-content: space-between;
              height: 96rpx;
              font-size: 24rpx;
              color: #626262;
            }

            .info-item {
              display: flex;
              flex-flow: column;
              justify-content: space-around;
            }
          }
        }
      }
    }

    .tips-content {
      padding: 40rpx 20rpx;
      background: #f5f6fa;

      .tips {
        font-size: 28rpx;
        color: #666666;
      }

      .btn-unfold {
        margin: 52rpx auto 20rpx;
        width: 200rpx;
        font-size: 24rpx;
        height: 60rpx;

        &::after {
          border: none;
        }
      }
    }
  }

  .affirm-popup {
    ::v-deep.u-popup__content {
      border-radius: 16rpx;
    }

    ::v-deep.u-fade-enter-to {
      z-index: 10076 !important;
    }

    .affirm-popup-content {
      width: 600rpx;

      .affirm-popup-title {
        padding: 40rpx;
        text-align: center;
        font-weight: bold;
      }

      .affirm-popup-tips {
        padding: 0 60rpx;
        font-size: 28rpx;
        text-align: center;
      }

      .popup-btn-list {
        display: flex;
        margin: 50rpx;

        .btn-item {
          width: 46%;
          height: 80rpx;
          border-color: #909193;

          &::after {
            border: none;
          }
        }

        .btn-item-2 {
          background: $base-color;
          color: #fff;
          border: none;
        }
      }
    }
  }

  .add-popup {
    ::v-deep.u-popup__content {
      border-radius: 16rpx;
    }

    ::v-deep.u-fade-enter-to {
      z-index: 10076 !important;
    }

    .add-popup-content {
      width: 700rpx;

      .add-popup-title {
        padding: 40rpx;
        text-align: center;
        font-weight: bold;
        font-size: 36rpx;
      }

      .add-tips {
        padding: 0 24rpx;
        text-align: center;
        color: red;
      }

      .u-form {
        margin: 0 40rpx;

        .form-item {
          margin: 28rpx 0;
        }
      }

      .popup-btn-list {
        display: flex;
        margin: 50rpx;

        .btn-item {
          width: 46%;
          height: 80rpx;
          border-color: #909193;

          &::after {
            border: none;
          }
        }

        .btn-item-2 {
          background: $base-color;
          color: #fff;
          border: none;
        }
      }
    }
  }

  .bottom-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    background: #fff;
    border-top: 2rpx solid $uni-border-color;
    z-index: 2;

    .bottom-list {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .bottom-btn-item {
        font-size: 28rpx;
        border-color: $base-color;
        color: #fff;
        background: $base-color;

        .bottom-icon {
          margin-right: 8rpx;
        }

        &::after {
          border: none;
        }
      }
    }
  }

  .loading-page {
    z-index: 1099;
  }
}
</style>
