<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rulesThis"
    ref="ruleForm"
    :size="'mini'"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="1" class="dtitle">
        <ul style="padding: 150px 0 0 0">
          <li>基</li>
          <li>础</li>
          <li>信</li>
          <li>息</li>
        </ul>
      </el-col>
      <el-col :span="23" class="dmain">
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品分类" prop="a1">
              <el-cascader
                v-model="ruleForm.a1"
                style="width: 100%"
                filterable
                placeholder="商品分类"
                clearable
                :options="catOptions"
                :props="{ expandTrigger: 'hover', checkStrictly: true }"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品品牌" prop="a2">
              <el-select
                style="width: 100%"
                v-model="ruleForm.a2"
                clearable
                placeholder="商品品牌"
              >
                <el-option
                  v-for="item in a2Options"
                  :key="item.id"
                  :label="item.brand_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="重量" prop="a3">
              <el-input
                placeholder="重量"
                v-model="ruleForm.a3"
                type="number"
                :min="0"
                :max="9999999999.99"
                :step="2"
              >
                <template slot="append">g</template>
              </el-input>
            </el-form-item>

            <el-form-item label="是否定制" prop="a4">
              <el-select
                v-model="ruleForm.a4"
                filterable
                clearable
                style="width: 100%"
                placeholder="是否定制"
              >
                <el-option
                  v-for="group in options1"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否库存品" prop="a5">
              <el-select
                v-model="ruleForm.a5"
                filterable
                clearable
                style="width: 100%"
                placeholder="是否库存品"
              >
                <el-option
                  v-for="group in options4"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="a6">
              <el-select
                v-model="ruleForm.a6"
                filterable
                clearable
                style="width: 100%"
                placeholder="供应商"
              >
                <el-option
                  v-for="group in supplierOptions6"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="销售权限" prop="a7">
              <el-select
                v-model="ruleForm.a7"
                filterable
                clearable
                style="width: 100%"
                placeholder="销售权限"
              >
                <el-option
                  v-for="group in options3"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="税点" prop="a8">
              <el-select
                v-model="ruleForm.a8"
                filterable
                clearable
                style="width: 100%"
                placeholder="税点"
              >
                <el-option
                  v-for="group in supplierOptions4"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="商品名称" prop="b1">
              <el-input
                placeholder="请输入商品名称"
                v-model="ruleForm.b1"
              ></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品单位" prop="b2">
                  <el-input
                    placeholder="商品单位"
                    v-model="ruleForm.b2"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="专属类型" prop="b3">
                  <el-select
                    v-model="ruleForm.b3"
                    filterable
                    clearable
                    style="width: 100%"
                    placeholder="专属类型"
                  >
                    <el-option
                      v-for="group in options2"
                      :key="group.id"
                      :label="group.name"
                      :value="group.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="贵金属种类" prop="b4">
                  <el-select
                    v-model="ruleForm.b4"
                    filterable
                    clearable
                    style="width: 100%"
                    placeholder="销售权限"
                  >
                    <el-option
                      v-for="group in []"
                      :key="group.id"
                      :label="group.name"
                      :value="group.id"
                    />
                  </el-select> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="启用实时金价" prop="b5">
                  <el-select
                    v-model="ruleForm.b5"
                    filterable
                    clearable
                    style="width: 100%"
                    placeholder="启用实时金价"
                  >
                    <el-option
                      v-for="group in options5"
                      :key="group.id"
                      :label="group.name"
                      :value="group.id"
                    />
                  </el-select> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="定制起订量" prop="b6">
                  <el-input
                    placeholder="定制起订量"
                    v-model="ruleForm.b6"
                    type="number"
                    :min="0"
                    :max="9999999999"
                    :step="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="定制工期" prop="b7">
                  <el-input
                    placeholder="定制工期"
                    v-model="ruleForm.b7"
                    type="number"
                    :min="0"
                    :max="9999999999"
                    :step="0"
                  >
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="售后说明" prop="b8">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="售后说明"
                v-model="ruleForm.b8"
              >
              </el-input>
            </el-form-item>

            <el-form-item label="工艺说明" prop="b9">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="工艺说明"
                v-model="ruleForm.b9"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="商品备注" prop="bb1">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="商品备注"
                v-model="ruleForm.bb1"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <el-row class="ddiv">
      <el-col :span="1" class="dtitle">
        <ul>
          <li>规</li>
          <li>格</li>
          <li>信</li>
          <li>息</li>
        </ul>
      </el-col>
      <el-col :span="23" class="dmain" style="padding-left: 18px">
        <el-table :data="tableData" :size="'mini'" border style="width: 100%">
          <el-table-column prop="index" label="序号"> </el-table-column>
          <el-table-column prop="name" label="规格类型"> </el-table-column>
          <el-table-column prop="address" label="规格值"> </el-table-column>
          <el-table-column fixed="right">
            <template slot="header" slot-scope="scope">
              <span>操作</span>
              <el-button :size="'mini'" class="fr">添加规格类型</el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="text"
                size="small"
                >新建规格值</el-button
              >
              <el-button
                @click="handleClick(scope.row)"
                type="text"
                size="small"
                >修改规格值</el-button
              >
              <el-button type="text" size="small">移除规格类型</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </el-form>
</template>
   <script>
import asyncRequest from "@/apis/service/goodStore/goodsCost";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import { options1, options2, options3, options4, options5 } from "../columns";
export default {
  name: "goodsCostAdd",
  mixins: [resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "goodsCostAdd"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      size: "small",
      rulesThis: this.rules,
      activeName: "1",
      loading: false,
      tableData: [],
      options1: options1,
      options2: options2,
      options3: options3,
      options4: options4,
      options5: options5,
      supplierOptions4: [
        { id: "0", name: "0%" },
        { id: "1", name: "1%" },
        { id: "3", name: "3%" },
        { id: "6", name: "6%" },
        { id: "9", name: "9%" },
        { id: "13", name: "13%" },
      ],
      supplierOptions6: [
        { id: "0", name: "供应商1" },
        { id: "1", name: "供应商1" },
      ],

      ruleForm: {},

      rules: {
        supplier: [
          {
            required: true,
            message: "供应商联系人",
            trigger: "change",
          },
        ],
        image: [
          {
            required: true,
            message: "商品主图",
            trigger: "change",
          },
        ],
        a1: [
          {
            required: true,
            message: "商品分类",
            trigger: "change",
          },
        ],
        a2: [
          {
            required: true,
            message: "商品品牌",
            trigger: "change",
          },
        ],
        good_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        unit: [
          {
            required: true,
            message: "请输入商品单位",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      ruleForm: {},
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    handleClick(row) {
      console.log(row);
    },
    async initData() {
      this.loading = true;
      let res = await asyncRequest.detail({ id: this.id });
      this.loading = false;
      if (res.code === 0) {
        await this.resetForm(res.data);
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            a1: "",
            a2: "",
            a3: "",
            a4: "",
            a5: "",
            a6: "",
            a7: "",
            a8: "",
            b1: "2018春秋新款V领修身丝绒西装女 双排扣复古极简中长款工装外套",
            b2: "",
            b3: "",
            b4: "",
            b5: "",
            b6: "",
            b7: "",
            b8: "",
            b9: "",
            bb1: "",
          };
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let change = false;
          this.mock.forEach((v1) => {
            if (v1.change && v1.change.length > 0) {
              change = true;
            }
          });
          if (!change) {
            this.ruleForm.spec = "规格！";
            return;
          } else {
            this.ruleForm.spec = "";
            let table = false;
            let hasnot = false;
            let stock = [];
            this.right.specList.forEach((v1) => {
              if (v1) {
                v1.forEach((v2) => {
                  if (v2 && v2.limit && v2.limit.length > 0) {
                    let list = [];
                    v2.limit.forEach((v3) => {
                      if (v3.num != 0 && v3.price != 0) {
                        table = true;
                        list.push(v3);
                      }
                      if (
                        (v3.num != 0 && v3.price == 0) ||
                        (v3.num == 0 && v3.price !== 0)
                      ) {
                        hasnot = true;
                      }
                    });
                    if (list.length > 0) {
                      let model = Object.assign({}, v2);
                      model.limit = list;
                      stock.push(model);
                    }
                  }
                });
              }
            });

            if (hasnot) {
              this.ruleForm.table =
                "起订量与成本价需成对填写，未成对请设为零！";
            } else {
              if (!table) {
                this.ruleForm.table = "至少填写一堆起订量与成本价！";
              } else {
                this.ruleForm.table = "";
                this.loading = true;
                let obj = JSON.parse(JSON.stringify(this.ruleForm));
                obj.stock = stock;
                obj.a1 = obj.a1[obj.a1.length - 1];
                obj.image = obj.image.join();
                //split(",");
                console.log(obj);
                let res = {};
                if (this.id === "add") {
                  delete obj["id"];
                  res = await asyncRequest.add(obj);
                } else {
                  res = await asyncRequest.update(obj);
                }
                this.loading = false;
                if (res.code === 0) {
                  let title = this.id === "add" ? "添加成功" : "修改成功";
                  this.$notify.success({
                    title,
                    message: "",
                  });
                  // 刷新
                  this.$emit("refresh");
                }
              }
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // groupChange($event, index, item) {
    //   this.$set(this.mock, index, item);
    //   this.actionSpecList();
    // },
    // actionSpecList() {
    //   // this.leftS = "0px";
    //   this.left.header = [];
    //   this.left.middle = [];
    //   this.left.specList = [];
    //   console.log(this.mock);
    //   console.log(this.right.specList);
    //   this.mock.forEach((v1) => {
    //     if (
    //       v1.change &&
    //       v1.change.length > 0 &&
    //       v1.child &&
    //       v1.child.length > 0
    //     ) {
    //       this.left.header.push({
    //         spec_id: v1.spec_id,
    //         spec_name: v1.spec_name,
    //       });
    //       let arr = [];
    //       let changeList = v1.change;
    //       changeList.forEach((v2) => {
    //         let index = v1.child.findIndex((v3) => v2 === v3.id);
    //         if (index !== -1) {
    //           let x = {
    //             spec_id: v1.spec_id,
    //             spec_name: v1.spec_name,
    //             id: v1.child[index].id,
    //             spec_value: v1.child[index].spec_value,
    //           };
    //           arr.push(x);
    //         }
    //       });
    //       this.left.middle.push(arr);
    //     }
    //   });
    //   let lang = this.left.header.length;
    //   this.leftS = lang * 70 + "px";
    //   if (this.left.middle.length > 1) {
    //     this.left.specList = this.doExchange(this.left.middle);
    //   } else if (this.left.middle.length === 0) {
    //     this.left.specList = [];
    //   } else {
    //     let list1 = [];
    //     this.left.middle.forEach((v1) => {
    //       if (v1) {
    //         v1.forEach((v2) => {
    //           let list2 = [];
    //           list2.push(v2);
    //           list1.push(list2);
    //         });
    //       }
    //     });
    //     this.left.specList = list1;
    //   }
    //   this.right.header = [];
    //   for (let i = 0; i < this.ladderNum; i++) {
    //     this.right.header.push(this.headLadder);
    //   }
    //   this.right.specList = [];
    //   this.left.specList.forEach((v1) => {
    //     let arr = [];
    //     let model = {
    //       specid: [],
    //       limit: [],
    //     };
    //     v1.forEach((v2) => {
    //       model.specid.push(v2.id);
    //     });
    //     for (let i = 0; i < this.ladderNum; i++) {
    //       let bodyLadder = {
    //         num: 0,
    //         price: 0,
    //       };
    //       model.limit.push(bodyLadder);
    //     }
    //     arr.push(model);
    //     this.right.specList.push(arr);
    //   });
    //   console.log(this.right.specList);
    // },

    // closeLadder(index) {
    //   console.log(index);
    // },
    // async handleChange(type) {
    //   if (this.ruleForm.a1 !== this.olda1 && this.olda1.length === 0) {
    //     await this.specByCat();

    //     if (this.step === 0 && !type) {
    //       this.step = 1;
    //     }
    //   } else if (
    //     this.ruleForm.a1 !== this.olda1 &&
    //     this.olda1.length > 0
    //   ) {
    //     await this.$confirm(
    //       "分类修改会影响该商品规格与价格！",
    //       "确定要修改？",
    //       {
    //         confirmButtonText: "确定",
    //         cancelButtonText: "取消",
    //         type: "warning",
    //       }
    //     )
    //       .then(async () => {
    //         await this.specByCat();
    //         if (this.step === 0) {
    //           this.step = 1;
    //         }
    //       })
    //       .catch(() => {
    //         this.ruleForm.a1 = this.olda1;
    //       });
    //   } else {
    //     if (this.step === 0 && !type) {
    //       this.step = 1;
    //     }
    //   }
    // },
    // //  商品种类ID换取规格值
    // async specByCat(type) {
    //   console.log("准备拉取！");
    //   this.mock = [];
    //   this.$set(this.mock);
    //   let list = this.ruleForm.a1;
    //   let res = await asyncRequest.specByCat({ a1: list[list.length - 1] });
    //   if (res.code === 0) {
    //     this.dealWitHInitMock(res.data, type);
    //     this.olda1 = list;
    //   } else if (res.code !== 101 && res.code !== 102) {
    //     this.ruleForm.a1 = this.olda1;
    //   }
    // },
    // //  规格属性值新建
    // async specinfoadd(id, value) {
    //   console.log(id, value);
    //   let list = this.ruleForm.a1;
    //   let model = {
    //     a1: list[list.length - 1],
    //     specid: id,
    //     spec_value: value,
    //   };
    //   let res = await asyncRequest.specinfoadd(model);
    //   if (res.code === 0) {
    //     await this.specByCat(true);
    //   }
    // },
    // dealWitHInitMock(list, type) {
    //   console.log(list, type);
    //   if (!type) {
    //     this.mock = [];
    //     console.log("12345678");
    //     console.log(this.mock);

    //     this.left.header = [];
    //     this.left.specList = [];
    //     this.right.header = [];
    //     this.right.specList = [];
    //     list.map((v1) => {
    //       v1.value = "";
    //       v1.change = [];
    //       return v1;
    //     });
    //     this.mock = list;
    //     console.log(this.mock);
    //     this.mock.forEach((v3, i) => {
    //       this.$set(this.mock, i, v3);
    //     });
    //   } else {
    //     let arr = JSON.parse(JSON.stringify(this.mock));
    //     list.map((v1) => {
    //       v1.value = "";
    //       let index = arr.findIndex((v2) => v2.spec_id === v1.spec_id);
    //       if (index !== -1) {
    //         v1.change = arr[index].change;
    //       }
    //       return v1;
    //     });
    //     this.mock = list;
    //     this.mock.forEach((v3, i) => {
    //       this.$set(this.mock, i, v3);
    //     });
    //   }
    // },
    // async getAlla2() {
    //   const res = await asyncRequest.brandAll({});
    //   if (res.code === 0 && res.data) {
    //     this.a2Options = res.data;
    //   }
    // },
    // async getAllCat() {
    //   const res = await asyncRequest.catAll({});
    //   if (res.code === 0 && res.data) {
    //     let list = res.data;
    //     list.map((v1) => {
    //       v1.value = v1.id;
    //       v1.label = v1.cat_name;
    //       if (v1.child && v1.child.length > 0) {
    //         v1.child.map((v2) => {
    //           v2.value = v2.id;
    //           v2.label = v2.cat_name;
    //           if (v2.child && v2.child.length > 0) {
    //             v2.child.map((v3) => {
    //               v3.value = v3.id;
    //               v3.label = v3.cat_name;
    //               return v3;
    //             });
    //             v2.children = v2.child;
    //           }
    //           return v2;
    //         });
    //         v1.children = v1.child;
    //       }

    //       return v1;
    //     });
    //     this.catOptions = list;
    //   }
    // },
    // async getAllSupplier() {
    //   const res = await asyncRequest.supplierAll({});
    //   if (res.code === 0 && res.data) {
    //     let list = res.data;
    //     this.supplierOptions = list;
    //   }
    // },
    //图片上传失败
    UploadErrorEvent() {
      this.$message.error("图片上传失败!");
      this.$refs.ruleForm.validateField("image");
    },
    closeImg(index) {
      this.ruleForm.image.splice(index, 1);
      this.$refs.ruleForm.validateField("image");
    },
    //图片上传成功
    UploadSuccessEvent(data) {
      console.log(data);
      this.ruleForm.image.push(data.url);
      this.$message.success("图片上传成功!");
      this.$refs.ruleForm.validateField("image");
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      console.log(file);
      let isJPG = false;
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/bmp" ||
        file.type === "image/jpeg" ||
        file.type === "image/gif"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    doExchange(arr) {
      let len = arr.length;
      // 当数组大于等于2个的时候
      if (len >= 2) {
        // 第一个数组的长度
        let len1 = arr[0].length;
        // 第二个数组的长度
        let len2 = arr[1].length;
        // 2个数组产生的组合数
        let lenBoth = len1 * len2;
        //  申明一个新数组
        let items = new Array(lenBoth);
        // 申明新数组的索引
        let index = 0;
        for (let i = 0; i < len1; i++) {
          for (let j = 0; j < len2; j++) {
            if (arr[0][i] instanceof Array) {
              items[index] = arr[0][i].concat(arr[1][j]);
            } else {
              items[index] = [arr[0][i]].concat(arr[1][j]);
            }
            index++;
          }
        }
        let newArr = new Array(len - 1);
        for (let i = 2; i < arr.length; i++) {
          newArr[i - 1] = arr[i];
        }
        newArr[0] = items;
        return this.doExchange(newArr);
      } else {
        return arr[0];
      }
    },
  },
  watch: {},
};
</script>
   <style lang="scss" scoped>
.goodsCostAdd {
  .goodsCostAdd-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16fpx;
      text-align: left;
    }
  }
}
</style>
   