<template>
  <el-form
    :model="form"
    ref="queryForm"
    size="small"
    :inline="true"
    label-width="120px"
    :rules="rules"
  >
    <el-row>
      <el-col :span="24">
        <el-form-item prop="lookSalesVolume">
          <span slot="label">展示销量</span>
          <el-input
            v-model="form.lookSalesVolume"
            placeholder="请输入展示销量"
            clearable
            @input="passValue"
          />
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item prop="unit">
          <span slot="label">计量单位</span>
          <el-select
            v-model="form.unit"
            placeholder="请选择"
            @change="passValue"
          >
            <el-option
              v-for="item in measure"
              :key="item.dictLabel"
              :label="item.dictLabel"
              :value="item.dictLabel"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <span slot="label"><span class="required">*</span> 商品规格</span>
          <el-button @click="addSpecification" type="primary"
            >添加规格</el-button
          >
          <el-table :data="form.skuList" style="width: 100%; margin-top: 20px">
            <el-table-column prop="name" label="规格名称" width="140">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.skuSpecsList[0].specsName"
                  placeholder="请输入规格名称"
                  clearable
                  maxlength="8"
                  @input="passValue"
                  show-word-limit
                />
              </template>
            </el-table-column>
            <el-table-column prop="address" label="规格内容" width="140">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.skuSpecsList[0].specsValue"
                  placeholder="规格内容"
                  clearable
                  maxlength="8"
                  show-word-limit
                  @input="passValue"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="预计库存" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.predictStocks"
                  placeholder="预计库存"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix"> {{ form.unit }} </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="实际库存" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.stock"
                  placeholder="实际库存"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix"> {{ form.unit }} </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="起批量" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.skuPriceList[0].minPurchase"
                  placeholder="起批量"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix">
                    {{ form.unit }}
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="收购价" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.skuCost.purchaseFee"
                  placeholder="收购价"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="人工费" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.skuCost.laborFee"
                  placeholder="人工费"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="代办费" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.skuCost.agencyFee"
                  placeholder="代办费"
                  clearable
                  @input="passValue"
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="材料费" width="140">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  @input="passValue"
                  v-model="scope.row.skuCost.materialFee"
                  placeholder="材料费"
                  clearable
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>

            <el-table-column
              prop="presaleTotalPrice"
              label="预售总价"
              width="140"
              v-if="saleModel == 2"
            >
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  @input="passValue"
                  v-model="scope.row.skuPriceList[0].presaleTotalPrice"
                  placeholder="预售总价"
                  clearable
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="预售定金"
              width="140"
              v-if="saleModel == 2"
            >
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  @input="passValue"
                  v-model="scope.row.skuPriceList[0].downPayPrice"
                  placeholder="预售定金"
                  clearable
                >
                  <template slot="suffix"> {{ form.unit }}/元 </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="商品单价" width="100">
              <template slot-scope="scope">
                {{ computePrice(scope.row) }}元/{{ form.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color: red"
                  @click="removeSpecification(scope.row, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="margin-top: 20px">
        <el-form-item>
          <span slot="label"><span class="required">*</span> 商品属性</span>
          <div class="main">
            <div style="padding-top: 20px">
              <el-form-item label="包装方式" prop="packing">
                <el-select
                  v-model="form.packing"
                  placeholder="请选择包装方式"
                  @change="passValue"
                >
                  <el-option
                    v-for="item in package"
                    :key="item.dictLabel"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="shippingTimeDesc">
                <span slot="label">发货时间</span>
                <el-select
                  v-model="form.shippingTimeDesc"
                  placeholder="请选择发货时间"
                  @change="passValue"
                >
                  <el-option label="付款24小时之内" value="付款24小时之内" />
                  <el-option label="付款36小时之内" value="付款36小时之内" />
                  <el-option label="付款48小时之内" value="付款48小时之内" />
                  <el-option label="付款72小时之内" value="付款72小时之内" />
                </el-select>
              </el-form-item>

              <template v-if="salesCategory == 1">
                <el-form-item>
                  <span slot="label">产地</span>
                  <el-cascader
                    v-model="form.producerIds"
                    :options="areaoptions"
                    @change="handleChange"
                    ref="cascader"
                    :props="propsarea"
                    collapse-tags
                  ></el-cascader>
                </el-form-item>
                <el-form-item prop="producerAddrDetail">
                  <span slot="label">详细地址</span>
                  <el-input
                    @input="passValue"
                    v-model="form.producerAddrDetail"
                    placeholder="请输入产地详细地址"
                    clearable
                  >
                  </el-input>
                </el-form-item>
                <el-form-item prop="squareMeasureUnit">
                  <span slot="label">面积单位</span>
                  <el-select
                    v-model="form.squareMeasureUnit"
                    placeholder="请选择面积单位"
                    @change="passValue"
                  >
                    <el-option label="平方米" value="平方米"> </el-option>
                    <el-option label="公顷" value="公顷"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="squareMeasure">
                  <span slot="label">面积</span>
                  <el-input
                    @input="passValue"
                    v-model="form.squareMeasure"
                    placeholder="请输入面积"
                    clearable
                  >
                    <template slot="suffix">
                      {{ form.squareMeasureUnit }}</template
                    >
                  </el-input>
                </el-form-item>
                <el-form-item prop="yield">
                  <span slot="label">产量单位</span>

                  <el-select
                    v-model="form.yieldUnit"
                    placeholder="请选择产量单位"
                    @change="passValue"
                  >
                    <el-option label="千克" value="千克"> </el-option>
                    <el-option label="吨" value="吨"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="yields">
                  <span slot="label">产量</span>
                  <el-input
                    @input="passValue"
                    v-model="form.yields"
                    placeholder="请输入产量"
                    clearable
                  >
                    <template slot="suffix">{{ form.yieldUnit }}</template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="variety">
                  <span slot="label">品种</span>
                  <el-input
                    @input="passValue"
                    v-model="form.variety"
                    placeholder="请输入品种名称"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </template>
            </div>

            <el-form-item
              label="自定义属性"
              v-if="form.props && form.props.length > 0"
            >
              <div
                style="
                  width: 100%;
                  display: flex;
                  flex-direction: row;
                  flex-flow: wrap;
                  justify-content: center;
                "
              >
                <div
                  class="item"
                  v-for="(item, index) in form.props ? form.props : []"
                  :key="index"
                >
                  <el-input
                    v-model="item.name"
                    placeholder="请输入属性名称"
                    clearable
                    maxlength="8"
                    show-word-limit
                    style="width: 200px"
                  />
                  <el-input
                    v-model="item.value"
                    placeholder="请输入属性值"
                    clearable
                    maxlength="8"
                    show-word-limit
                    @input="passValue"
                    style="width: 200px"
                  />
                  <i
                    class="el-icon-delete"
                    size="22"
                    style="color: red"
                    @click="removeAttribute(item, index)"
                  ></i>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="item1" style="width: 180px">
            <span @click="addattribute" style="cursor: pointer">
              <i class="el-icon-plus" size="22"></i>自定义添加商品属性</span
            >
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="merchantClassifyIds">
          <span slot="label">店铺内所属分类</span>
          <el-cascader
            :filterable="true"
            v-model="form.merchantClassifyIds"
            ref="formCascader"
            :placeholder="
              form.merchantClassifyName
                ? form.merchantClassifyName
                : '请选择分类'
            "
            :props="categoryprops"
            @change="cascaderChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="margin-top: 20px">
        <el-form-item prop="freeShipping">
          <span slot="label">运费</span>
          <div class="main1">
            <el-radio-group
              v-model="form.freeShipping"
              class="radios"
              @change="passValue"
            >
              <el-radio :label="0" :value="0"
                >双方协商后卖家进行修改，买家和订单一起支付</el-radio
              >
              <el-radio :label="1" :value="1"
                >全国包邮，由卖家承担运费</el-radio
              >
            </el-radio-group>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="margin-top: 20px">
        <el-form-item prop="shippingAddrId">
          <span slot="label"> 发货地址</span>
          <el-select
            v-model="form.shippingAddrId"
            placeholder="请选择"
            style="width: 300px"
            @change="passValue"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="
                item.defaultTag == 1 ? '默认-' + item.address : item.address
              "
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-button type="text" @click="areaAdd" style="margin-left: 10px">
            没有所需地址?前去添加</el-button
          >
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="shareRate">
          <span slot="label">分享比例</span>
          <el-input-number
            v-model="form.shareRate"
            :min="0"
            :max="100"
            placeholder="请输入分享比例"
            :controls="false"
            @change="passValue"
          >
          </el-input-number
          >%
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="returnVoucherRatio">
          <span slot="label"
            >返券比例(%)
            <el-tooltip
              effect="dark"
              content="返券比例:用户下单该商品后，交易完成后可获得商品金额的X%的代金券奖励，该代金券只可在本店铺使用"
              placement="top-start"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input-number
            v-model="form.returnVoucherRatio"
            :min="0"
            :max="100"
            placeholder="请输入返券比例"
            :controls="false"
            @change="passValue"
          >
          </el-input-number
          >%
        </el-form-item>
      </el-col>
    </el-row>
    <Amap ref="mapOpen" @address="Mapaddress"></Amap>
  </el-form>
</template>

<script>
import cityJson from "@/assets/city.json";
import { getMerchantClassifyList } from "@/api/sort/index.js";
import { getStoreInfo } from "@/api/common/index";
import { getCityTreeNew } from "@/api/manage/material.js";
import Amap from "@/components/Map/map.vue";
import { getDict } from "@/api/common/index.js";
import { dxAddressList } from "@/api/manage/address";
export default {
  props: ["data", "saleType", "saleModels", "salesCategory"],
  components: { Amap },
  data() {
    return {
      form: {
        expressType: 0,
        unit: "斤",
        props: [],
        freeShipping: 0,
        lookSalesVolume: "",
        shippingAddrBean: {
          addr: "",
          addrDetail: "",
          cityCode: "",
          countyCode: "",
          latitude: "",
          longitude: "",
          provinceCode: "",
        },
        shippingAddr: "",
        skuList: [],
        packing: "",
        shippingTimeDesc: "",
        merchantClassifyId: "",
        merchantClassifyIds: [],
        merchantClassifyName: "",
        shippingAddrId: "",
        yields: "",
      },
      addr: "",
      measure: [],
      package: [],
      rules: {
        freeShipping: [
          { required: true, message: "请选择运费方式", trigger: "blur" },
        ],
        props: [
          { required: true, message: "商品属性不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "计量单位不能为空", trigger: "blur" },
        ],
        shippingTimeDesc: [
          { required: true, message: "发货时间不能为空", trigger: "blur" },
        ],
        skuList: [{ required: true, message: "规格不能为空", trigger: "blur" }],
        packing: [
          { required: true, message: "包装方式不能为空", trigger: "blur" },
        ],
        shippingAddrId: [
          { required: true, message: "请选择地址", trigger: "blur" },
        ],
        merchantClassifyIds: [
          { required: true, message: "店铺所属分类不能为空", trigger: "blur" },
        ],
      },
      propsarea: {
        label: "name",
        value: "code",
        children: "childList",
      },
      shopInfo: {},
      saleType: undefined,
      sj: true,
      skuIds: [],
      saleModel: 1,
      categoryprops: {
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.categoryLazyLoad,
        label: "label",
        value: "value",
      },
      options: [],
      areaoptions: [],
    };
  },
  watch: {
    //监听文件url改变时重新赋值
    saleModels(newVal, oldVal) {
      this.saleModel = newVal;
      this.$forceUpdate();
    },
  },
  mounted() {
    this.getArea();
    this.getInfo();
    this.getdictImpl();
    this.getAreaList();
  },
  methods: {
    getArea() {
      console.log(cityJson);
      this.areaoptions = cityJson;
    },
    handleChange(val) {
      const cascader = this.$refs.cascader;
      const selectedLabels = cascader.getCheckedNodes();
      this.form.producerAddr = selectedLabels[0].pathLabels.join("");
    },

    areaAdd() {
      this.$router.push({ path: "/manage/manage/address/index" });
    },
    getAreaList() {
      dxAddressList().then((res) => {
        if (res.code == 200) {
          this.options = res.data;
          let defaults = this.options.filter((item) => {
            // 根据搜索文本过滤，不区分大小写
            return item.defaultTag == 1;
          });
          this.form.shippingAddrId = defaults[0].id;
        }
      });
    },
    categoryLazyLoad(node, resolve) {
      let level = node.level;
      if (!node.data) {
        getMerchantClassifyList({ classifyType: 1, isDefault: 1 }).then(
          (res) => {
            //接口
            const nodes = Array.from(res.data).map((item, index) => ({
              value: item.id,
              label: `${item.classifyName}`,
              leaf: level >= 2,
            }));
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes);
          }
        );
      } else if (level == 1) {
        getMerchantClassifyList({
          parentId: node.data.value,
          classifyType: 1,
        }).then((res) => {
          const nodes = Array.from(res.data).map((item) => ({
            value: item.id,
            label: `${item.classifyName}`,
            leaf: level >= 2,
            // level: 2,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else {
        resolve({});
      }
    },
    cascaderChange(val) {
      const dom = document.getElementsByClassName("el-radio is-checked");
      //这里我把dom打出来看了 最后一个选项才是我选中的节点 即[length-1] 有的博主写的是 第一个元素 即[0] 大家自行尝试
      let radioDom = dom[dom.length - 1];
      const brother = radioDom.nextElementSibling;
      let nodes = this.$refs.formCascader.getCheckedNodes();
      this.form.merchantClassifyName = nodes[0].label;
      this.form.merchantClassifyIds = val;
      this.form.merchantClassifyId = JSON.stringify(val);
      brother.click();
      // this.form.merchantClassifyId = `["${this.form.merchantClassifyId.join('')}"]`;
      this.passValue();
    },
    getFormInfo(record) {
      // 基础属性赋值
      const {
        shippingAddrId,
        merchantClassifyName,
        saleModel,
        shippingAddr: addr,
        expressType,
        shareRate,
        merchantClassifyId,
        lookSalesVolume,
        unit,
        packing,
        shippingTimeDesc,
        freeShipping,
        skuList,
        returnVoucherRatio,
        producerAddr,
        producerAddrDetail,
        squareMeasure,
        squareMeasureUnit,
        variety,
        producerIds,
        yieldUnit,
        props = [], // 默认空数组避免后续判断
      } = record;

      // 更新表单数据
      this.form = {
        producerIds: JSON.parse(producerIds).map(String),
        ...this.form, // 保留原有属性
        producerAddr,
        yieldUnit,
        squareMeasure,
        producerAddrDetail,
        squareMeasureUnit,
        variety,
        shippingAddrId: JSON.stringify(shippingAddrId),
        merchantClassifyName,
        returnVoucherRatio,
        expressType,
        shareRate,
        merchantClassifyIds: merchantClassifyId,
        merchantClassifyId,
        lookSalesVolume,
        unit,
        shippingAddr: addr,
        packing,
        shippingTimeDesc,
        freeShipping: freeShipping,
        skuList,
        props, // 已默认处理空值情况
        shippingAddrBean: {
          addr,
          addrDetail: record.shippingAddrBean?.addrDetail,
          cityCode: record.cityCode,
          countyCode: record.countyCode,
          latitude: record.latitude,
          longitude: record.longitude,
          provinceCode: record.provinceCode,
        },
      };
      this.form.yields = record.yield;
      console.log('zzz',this.form);

      // 独立处理特殊属性
      this.saleModel = saleModel;
      this.addr = addr;
    },
    compilatePrice(data) {
      if (data.price) {
        return data.price.toFixed(2);
      } else if (data.originalPrice) {
        return data.originalPrice.toFixed(2);
      } else if (data.originalPrice && data.price) {
        return data.price.toFixed(2);
      }
    },
    formvalidate() {
      let that = this;
      return new Promise((resolve) => {
        that.$refs.queryForm.validate((valid, row) => {
          if (valid) {
            resolve(valid);
          } else {
            for (const key in row) {
              for (let index = 0; index < row[key].length; index++) {
                this.$message.error(row[key][index].message);
                return;
              }
            }
            resolve(valid);
          }
        });
      });
    },
    getInfo() {
      getStoreInfo().then((res) => {
        if (res.code == 200) {
          this.shopInfo = res.data;
        }
      });
    },
    getdictImpl() {
      getDict("stockUnit").then((res) => {
        if (res.code == 200) {
          this.measure = res.data;
        }
      });
      getDict("packType").then((res) => {
        if (res.code == 200) {
          this.package = res.data;
        }
      });
    },
    computePrice(data) {
      if (
        data.skuCost.purchaseFee &&
        data.skuCost.laborFee &&
        data.skuCost.agencyFee &&
        data.skuCost.materialFee
      ) {
        return (
          Number(data.skuCost.purchaseFee) +
          Number(data.skuCost.laborFee) +
          Number(data.skuCost.agencyFee) +
          Number(data.skuCost.materialFee)
        ).toFixed(2);
      } else {
        return 0;
      }
    },

    passValue() {
      this.form.skuList.forEach((e) => {
        e.skuPriceList.forEach((a) => {
          e.presaleTotalPrice = a.presaleTotalPrice;
          e.downPayPrice = a.downPayPrice;
          a.price = this.computePrice(e);
          a.originalPrice = this.computePrice(e);
          a.lowestPrice = this.computePrice(e);
        });
      });
      this.$emit("updateValue", this.form);
    },

    Mapaddress(data) {
      this.form.shippingAddr = data.pname + data.cityname + data.adname;
      this.form.shippingAddrBean.addr = data.address;
      // this.form.shippingAddrBean.addrDetail = data.name ? data.name : undefined;
      this.form.shippingAddrBean.cityCode = data.cityCode;
      this.form.shippingAddrBean.countyCode = data.adcode;
      if (data.location) {
        this.form.shippingAddrBean.latitude = data.location.lat;
        this.form.shippingAddrBean.longitude = data.location.lng;
      }
      this.form.shippingAddrBean.provinceCode = data.pcode;
      this.addr = data.address;
      this.$refs.mapOpen.closeMap();
      // this.passValue();
    },
    selectAddr() {
      this.$refs.mapOpen.loadMap();
    },
    addattribute() {
      if (this.form.prop?.length > 0) {
        this.form.props.push({
          name: "",
          id: "",
          value: "",
        });
      } else {
        this.form.prop = [];
        this.form.props.push({
          name: "",
          id: "",
          value: "",
        });
      }
    },
    removeAttribute(record, index) {
      this.form.props.splice(index, 1);
      this.passValue();
    },
    removeSpecification(record, index) {
      console.log("record", record.id);
      this.skuIds.push(record.id);
      this.form.skuList.splice(index, 1);
      this.$emit("skuRemove", this.skuIds);
    },
    addSpecification() {
      if (!this.form.skuList) {
        this.form.skuList = [];
      }
      this.form.skuList.push({
        stock: undefined,
        weight: undefined,
        sj: true,
        skuCost: {
          purchaseFee: undefined,
          laborFee: undefined,
          agencyFee: undefined,
          materialFee: undefined,
        },
        skuSpecsList: [
          {
            specsId: "0",
            specsName: "",
            specsValue: "",
          },
        ],
        skuPriceList: [
          {
            minPurchase: undefined,
            maxPurchase: undefined,
            price: undefined,
            originalPrice: undefined,
            lowestPrice: 1,
          },
        ],
      });
    },
  },
};
</script>
<style>
.el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
.el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
</style>
<style scoped>
/deep/ .el-radio-group {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 50px;
}
.item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
  margin-right: 10px;
}
.main1 {
  background: #f1f1f1;
  min-height: 80px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  padding: 0px 20px;
}
.main {
  width: 58vw;
  background: #f1f1f1;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  /* display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  padding: 20px 20px 0px 20px; */
}
</style>
