<template>
  <view class="product-add-wrapper">
    <view class="headers">
      <headersVue headerTitle="添加商品" @headerJump="headerJump"></headersVue>
      <view class="headers-title">
        <view class="content"> 该功能仅支持单规格商品快速添加，可在PC端编辑 </view>
      </view>
    </view>
    <view class="content-wrrapper">
      <uploadVue
        formItemTitle="商品封面"
        :maxLimit="1"
        @changeFiles="changeFilesfengmian"
      ></uploadVue>
      <uploadVue
        formItemTitle="商品轮播图"
        @changeFiles="changeFileslunbotu"
      ></uploadVue>

      <view class="form-box">
        <view class="form-item-box">
          <view class="form-box-txt">商户商品分类</view>
          <view
            class="form-box--arae"
            @click="handleClick"
            :class="[classification.name == '' ? 'classification' : '']"
          >
            {{ classification.name || "请选择商品分类" }}
          </view>
          <uni-icons
            type="right"
            size="26"
            class="icon-boxx"
            color="#333"
          ></uni-icons>
        </view>
        <view class="form-item-box">
          <view class="form-box-txt">平台商品分类</view>
          <view
            class="form-box--arae"
            @click="handleClickpingtai"
            :class="[pingtaifeilei.name == '' ? 'classification' : '']"
          >
            {{ pingtaifeilei.name || "平台商品分类" }}
          </view>
          <uni-icons
            type="right"
            size="26"
            class="icon-boxx"
            color="#333"
          ></uni-icons>
        </view>
        <view class="form-item-box">
          <view class="form-box-txt mustBox">商品名称</view>
          <view class="form-box--arae">
            <input
              type="text"
              v-model="formData.store_name"
              placeholder="请输入商品名称"
              :adjust-position="false"
              class="placeholder-class"
            />
          </view>
        </view>
        <view class="form-item-box">
          <view class="form-box-txt mustBox">商品单位</view>
          <view class="form-box--arae">
            <input
              type="text"
              v-model="formData.unit_name"
              placeholder="请输入单位"
              :adjust-position="false"
              class="placeholder-class"
            />
          </view>
        </view>
        <view class="form-item-box">
          <view class="form-box-txt">品牌选择</view>
          <view class="form-box--arae">
            <uni-data-select
              v-model="formData.brand_id"
              placeholder="请选择品牌"
              :localdata="brandData"
              :clear="true"
            ></uni-data-select>
          </view>
        </view>
        <view class="form-item-box">
          <view class="form-box-txt mustBox">运费模板</view>
          <view class="form-box--arae">
            <uni-data-select
              v-model="formData.temp_id"
              placeholder="请选择运费模板"
              :localdata="shippingList"
              :clear="true"
            ></uni-data-select>
          </view>
        </view>
        <view v-if="shippingList.length == 0" class="tips-messge">运费模板为空，请在后台添加运费模板</view>
      </view>
      <view
        class="form-box mr-t"
        v-for="(item, index) in attrValue"
        :key="index"
      >
        <view
          class="form-item-box"
          v-for="(its, idx) in item.modules"
          :key="idx"
          v-if="its.isshow"
        >
          <template v-if="its.isshow">
            <view class="form-box-txt" :class="[its.ismust ? 'mustBox' : '']">{{
              its.title
            }}</view>
            <view class="form-box--arae">
              <input
                v-if="its.form_type == 'input'"
                :type="its.type"
                v-model="item.modules[idx].value"
                :adjust-position="false"
                :placeholder="`请输入${its.title}`"
                class="placeholder-class"
              />
            </view>
          </template>
        </view>
      </view>
      <view class="business-box pb15">
        <view class="business-box-txt">商品简介 </view>
        <view class="business-box--arae">
          <textarea
            @blur="bindTextAreaBlur"
            v-model="formData.store_info"
            placeholder="输入商品简介"
            :maxlength="-1"
            :adjust-position="false"
            auto-height
            class="araebox"
          />
        </view>
      </view>
      <view class="business-box pb15">
        <view class="business-box-txt">商品详情 </view>
        <customEditor :value="formData.content" @input="changeTextHandle"/>
      </view>
    </view>
    <view class="btn-list">
      <!-- <view class="btn quxiao"> 保存草稿 </view> -->
      <view class="btn primary" @click="handleSubmit"> 发布商品 </view>
    </view>
    <cascadePicker
      ref="picker"
      :title="cascadePicker.title"
      :layer="cascadePicker.layer"
      :data="cascadePicker.data"
      @callback="pickerCallback"
    />
    <cascadePicker
      ref="pickerpingtai"
      :title="cascadepintaiPicker.title"
      :layer="cascadepintaiPicker.layer"
      :data="cascadepintaiPicker.data"
      @callback="pickerCallbackpintai"
    />
  </view>
</template>

<script>
//添加商品
import headersVue from "../components/headers/headers.vue";
import uploadVue from "./components/upload.vue";
import cascadePicker from "../components/cascade-picker.vue";
import { reNameKeys } from "@/utils/index";
import customEditor from "@/components/editor.vue";
import {
  getGoodsClass,
  getBrandSelect,
  shippingListApi,
  getGoodsClassCategory,
  uploadFile,
  addProduct,
} from "@/commit/product.js";
export default {
  components: {
    headersVue,
    uploadVue,
    cascadePicker,
    customEditor,
  },
  data() {
    return {
      cascadeData: [], //商户商品分类
      pingtaifeiData: [], //平台商品分类：
      cascadePicker: {
        title: "选择商户商品分类",
        layer: null,
        data: [],
      },
      cascadepintaiPicker: {
        title: "选择平台商品分类",
        layer: null,
        data: [],
      },
      classification: {
        //商户商品分类
        name: "",
        id: "",
      },
      pingtaifeilei: {
        //平台商品分类：
        name: "",
        id: "",
      },
      formData: {
        store_name: "", //商品名称
        mer_cate_id: [], //商户商品分类：
        cate_id: "", //平台商品分类：
        brand_id: "", //品牌选择：
        keyword: "", //商品关键字：
        unit_name: "", //单位：
        store_info: "", //商品简介：
        image: "", //商品封面图：
        temp_id: "", //运费模板：
        slider_image: [], //商品轮播图：
        couponData: [], //优惠券：
        content: "", //商品详情：
        sort: 0, //排序：
        extension_type: "0", //是否单独设置：
        is_good: 0, //商品推荐：0 1
        is_gift_bag: 0, //是否包邮：0 1
        give_coupon_ids: [], //优惠券：
        // checkboxGroup: [], //商品推荐：0单规格 1 多规格
        stock_num: "", //商品库存
        unit_name: "", //单位
        share_num: "",
        shares_num: "",
        share_is: "0",
        spec_type: "0",
        type: 1,
        unit_name: "",
        attr: [],
        commission: "",
        pension: "",
        pension_is: "0",
        pension_num: "",
      },
      selectData: [],
      brandData: [],
      shippingList: [], //运费模板
      attrValue: [
        {
          modules: [
            {
              title: "商品售价",
              props: "price",
              value: "",
              type: "digit",
              ismust: true,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品成本价",
              value: "",
              props: "cost",
              type: "digit",
              ismust: true,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品原价",
              value: "",
              props: "ot_price",
              type: "digit",
              ismust: true,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品库存",
              value: "",
              props: "stock",
              type: "number",
              ismust: true,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品编号",
              value: "",
              props: "bar_code",
              type: "text",
              ismust: false,
              form_type: "input",
              isshow: true,
            },
            {
              title: "重量（KG）",
              value: "",
              props: "weight",
              type: "digit",
              ismust: false,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品体积(m³)",
              value: "",
              props: "volume",
              type: "digit",
              ismust: false,
              form_type: "input",
              isshow: true,
            },
            {
              title: "商品图片",
              value: "",
              props: "image",
              type: "",
              ismust: false,
              form_type: "file",
              isshow: false,
            },
          ],
        },
      ],
    };
  },
  async onLoad() {
    await this.initData();
  },
  onShow() {},
  methods: {
    async initData() {
      await this.getBrandSelectData();
      await this.getShippingListData();
      await this.getGoodsClassData();
      await this.getGoodsClassCategoryData();
    },
    async getGoodsClassData() {
      try {
        const res = await getGoodsClass();
        if (res.data.status == 200) {
          const data = res.data.data || [];
          this.cascadeData = reNameKeys(data);
        }
      } catch (error) {}
    },
    async getBrandSelectData() {
      //  { value: 0, text: "篮球" },
      try {
        const res = await getBrandSelect();
        if (res.data.status == 200) {
          const data = res.data.data || [];
          console.log(data, "品牌数据");
          this.brandData = data.map((item) => {
            return {
              value: item.brand_id || "",
              text: item.brand_name || "",
              ...item,
            };
          });
        }
      } catch (error) {}
    },
    async getShippingListData() {
      try {
        const res = await shippingListApi();
        if (res.data.status == 200) {
          const data = res.data.data || [];
          console.log(data, "运费模板");
          this.shippingList = data.map((item) => {
            return {
              value: item.shipping_template_id || "",
              text: item.name || "",
              // ...item,
            };
          });
        }
      } catch (error) {}
    },
    async getGoodsClassCategoryData() {
      try {
        const res = await getGoodsClassCategory();
        if (res.data.status == 200) {
          const data = res.data.data || [];
          this.pingtaiData = reNameKeys(data);
        }
      } catch (error) {}
    },

    headerJump() {
      uni.redirectTo({
        url: "/shop/productManagementModule/productManagement",
      });
    },
    // picker多级联动回调
    pickerCallback(e) {
      const { data } = e;
      const lastItem = data[data.length - 1];
      this.selectData = data || [];
      console.log(lastItem, "pickerCallback回調");
      this.formData.mer_cate_id.push(lastItem.id);
      this.classification = lastItem || {};
    },
    handleClick() {
      const _this = this;
      _this.cascadePicker.data = _this.cascadeData;
      _this.$refs.picker.open().then(function () {
        console.log("打开成功");
      });
    },
    handleClickpingtai() {
      //pingtai
      const _this = this;
      _this.cascadepintaiPicker.data = _this.pingtaiData;
      _this.$refs.pickerpingtai.open().then(function () {
        console.log("打开成功");
      });
    },
    pickerCallbackpintai(e) {
      const { data } = e;
      const lastItem = data[data.length - 1];
      this.selectData = data || [];
      console.log(lastItem, "pickerCallbackpintai");
      this.pingtaifeilei = lastItem || {};
    },
    bindTextAreaBlur(e) {
      console.log(e.detail.value);
    },
 async   handleSubmit() {
      if (this.formData.image == "") {
        uni.showToast({
          title: "请上传商品封面图",
          icon: "none",
        });
        return;
      }
      if (this.formData.slider_image.length == 0) {
        uni.showToast({
          title: "请上传商品轮播图",
          icon: "none",
        });
        return;
      }
      if (this.formData.store_name == "") {
        uni.showToast({
          title: "请填写商品名称",
          icon: "none",
        });
        return;
      }
      if (this.formData.unit_name == "") {
        uni.showToast({
          title: "请填写商品单位",
          icon: "none",
        });
        return;
      }
      if(!this.formData.temp_id || this.formData.temp_id == ""){
        uni.showToast({
          title: "请选择运费模板",
          icon: "none",
        });
        return

      }
      const dataList = (this.attrValue[0] && this.attrValue[0].modules) || [];
      const dataNew = dataList.map((item, index) => {
        return {
          tips: dataList[index].title,
          props: dataList[index].props,
          isEmpty:
            dataList[index].ismust &&
            (dataList[index].value == "" ||
              dataList[index].value == undefined ||
              dataList[index].value == null),
          value: dataList[index].value || "",
        };
      });
      const data = dataNew.some((item) => item.isEmpty);
      if (data) {
        uni.showToast({
          title: "请填写完所有必填项",
          icon: "none",
        });
        return;
      }
      if (this.formData.store_info == "") {
        uni.showToast({
          title: "请填写商品简介",
          icon: "none",
        });
        return;
      }
      let attrValueData = dataNew.map((item, index) => {
        let parmas = {};
        if ([item.props] == "image") {
          Object.assign(parmas, { image: this.formData.image });
        } else {
          Object.assign(parmas, { [item.props]: item.value });
        }
        return parmas;
      });
      // 使用 reduce 方法合并数组中的对象
      const mergedObject = attrValueData.reduce((acc, current) => {
        return { ...acc, ...current };
      }, {});

      // 转换为包含合并后对象的数组
      const result = [mergedObject];
      const newParams = { ...this.formData, attrValue: result };
      uni.showLoading({
        title: "数据提交中...",
      })
      try {
         const res = await addProduct(newParams);
         if(res.data.status == 200){
            uni.showToast({
              title:  "数据提交成功",
              icon: "none",
            });
            uni.redirectTo({
              url:'./productManagement'
            })
         }else{
          uni.showToast({
              title:  res.data.message,
              icon: "none",
            });

         }
         uni.hideLoading();
         uni.hideToast()
      } catch (error) {
        
      }finally{
        uni.hideLoading();
      }
    },
    changeFilesfengmian(data) {
      const pathsArr = data.fileList || [];
      const paths = pathsArr.map((item) => item.path).join("") || "";
      this.formData.image = paths;
    },
    changeFileslunbotu(data) {
      const pathsArr = data.fileList || [];
      this.formData.slider_image = [];
      pathsArr.forEach((item) => {
        this.formData.slider_image.push(item.path);
      });
    },
    changeTextHandle(data){
      // console.log(data)
      this.formData.content = data;
    }
  },
};
</script>
<style>
page {
  background-color: #f7f8fc;
  height: 100%;
}
</style>
<style lang="scss" scoped>
.product-add-wrapper {
  height: 100%;
  overflow: hidden;
  .headers {
    .headers-title {
      display: flex;
      align-items: center;
      width: 100%;
      background: #fff9ed;
      padding: 16px 20rpx;
      margin-top: 88rpx;
      .content {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 26rpx;
        color: #ff6010;
      }
    }
  }
}
.content-wrrapper {
  height: calc(100% - 350rpx);
  overflow-y: auto;
  padding-bottom: 60rpx;
  .business-box {
    width: calc(100% - 0rpx);
    // border: 2rpx solid #f00;
    margin: 26rpx 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
    padding: 32rpx 32rpx 0;
    box-sizing: border-box;
    background-color: #ffffff;
    min-height: 250rpx;
    .business-box-txt {
      width: 100%;
      font-weight: 600;
      font-size: 30rpx;
      color: #333333;
      margin-bottom: 20rpx;
      &::after {
        content: "*";
        color: #f00;
        padding-left: 10rpx;
      }
    }
    .upload-boxx {
      padding: 19rpx 0 !important;
    }
    .business-box--arae {
      width: 100%;
      //  border: 2rpx solid #f00;
      background: #f8f8f8;
      border-radius: 9rpx;
      min-height: 208rpx;
      .araebox {
        padding: 20rpx 18rpx 20rpx 26rpx;
        width: calc(100% - 46rpx);
        height: 100%;
      }
    }
  }
}

.btn-list {
  background-color: #fff;
  display: flex;
  gap: 26rpx;
  user-select: none;
  padding: 15rpx 26rpx 0rpx;
  height: 126rpx;
  .btn {
    flex: 1;
    flex-shrink: 0;
    height: 78rpx;
    border-radius: 8rpx;
    font-weight: 400;
    font-size: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .quxiao {
    border: 1rpx solid #999999;
    color: #333333;
  }
  .primary {
    color: #ffffff;
    background: #1f7cff;
  }
}
.form-box {
  min-height: 158rpx;
  background: #ffffff;
  //   border: 2rpx solid #f00;
  padding: 0 32rpx;
  .form-item-box {
    display: flex;
    align-items: center;
    padding: 26rpx 0 18rpx;
    border-bottom: 2rpx solid #f8f8f8;
    position: relative;
    &:last-child {
      border-bottom: none;
    }
    .icon-boxx {
      position: absolute;
      right: -26rpx;
      top: 28rpx;
    }
    .form-box-txt {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 30rpx;
      color: #333333;
      //   height: 100%;
      line-height: 42rpx;

      width: 230rpx;
      flex-shrink: 0;
    }
    .form-box--arae {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      font-weight: 400;
      font-size: 30rpx;
      color: #333333;
      flex: 1;
      padding-right: 20rpx;
      &.classification {
        color: #999;
      }
    }
  }
}
.mustBox {
  &::after {
    content: "*";
    color: #f00;
    padding-left: 10rpx;
  }
}
.placeholder-class {
  width: 100%;
  font-weight: 400;
  font-size: 30rpx;
  color: #333333;
  text-align: right;
  padding: 0rpx 0rpx 0rpx 15rpx;
  outline: none;
  border: none;
  background: none;
  /deep/.uni-input-placeholder {
    color: #999;
  }
}
.mr-t {
  margin-top: 26rpx;
}
.pb15 {
  padding-bottom: 25rpx !important;
}
.tips-messge{
  padding-bottom: 15rpx;
  color: #ff6010;
}
</style>
