<template>
  <div class="app-main-height">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="22" :lg="10" :xl="10">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="店铺图标">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeUpload1"
              :file-list="ruleForm.icon"
              :on-remove="handleRemove1"
              :limit="1"
              accept=".jpg, .jpeg, .png"
              :on-exceed="handleExceed"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <P class="text"
              >请保证图片尺寸为328*328,格式为jpg / jpeg / png的图片</P
            >
          </el-form-item>
          <el-form-item label="店铺名称">
            <span>{{ ruleForm.merchantsName || merchantsName }}</span>
          </el-form-item>
          <el-form-item label="公司地址" prop="address">
            <el-input
              v-model.trim="ruleForm.address"
              placeholder="请输入店铺地址"
              size="small"
            />
          </el-form-item>
          <el-form-item label="店铺主图">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeUpload"
              :file-list="ruleForm.image"
              :on-remove="handleRemove"
              :limit="1"
              accept=".jpg, .jpeg, .png"
              :on-exceed="handleExceed"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <P class="text"
              >请保证图片尺寸为680*226,格式为jpg / png / bpm的图片</P
            >
          </el-form-item>
          <el-form-item label="客服电话" prop="customerServicePhone">
            <el-input
              v-model.trim="ruleForm.customerServicePhone"
              placeholder="请输入客服电话"
              size="small"
            />
          </el-form-item>
          <el-form-item label="添加主推商品" class="add_el-form-item__content">
            <el-select
              v-model="addGoods.classificationID"
              size="small"
              @change="getGoodsByClassification(addGoods.classificationID)"
            >
              <el-option
                v-for="(item, index) in goodsType"
                :key="index"
                :value="item.goodsClassificationID"
                :label="item.goodsClassificationName"
              />
            </el-select>
            <el-select
              v-model="goodsName.goodsId"
              size="small"
              @change="getGoodsname(goodsName.goodsId)"
            >
              <el-option
                v-for="(item, index) in goods"
                :key="index"
                :value="item.goodsId"
                :label="item.goodsName"
              />
            </el-select>
            <span class="el-button--text" @click="hanleAdd">添加</span>
          </el-form-item>
          <div class="list">
            <ul v-if="list">
              <li v-for="(item, index) in goodsList" :key="index">
                {{ index + 1 }}、{{ item.goodsName }}
                <span class="el-button--text" @click="hanleremove(item)"
                  >删除</span
                >
                <span
                  v-if="index !== 0"
                  class="el-button--text"
                  @click="upClick(index)"
                  >上移</span
                >
                <span
                  v-if="index !== goodsList.length - 1"
                  class="el-button--text"
                  @click="downClick(index)"
                  >下移</span
                >
              </li>
            </ul>
          </div>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :xs="24" :sm="24" :md="22" :lg="14" :xl="10">
        <div class="img">
          <img src="../../assets/images/back.png" style="width: 100%" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { isNumber } from "@/utils/validate";
export default {
  name: "Form",
  data() {
    const validateServicePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入客服电话"));
      } else if (!isNumber(value)) {
        callback(new Error("只能输入数字和-符号，最多12位"));
      } else {
        callback();
      }
    };

    return {
      dialogImageUrl: "",
      dialogVisible: false,
      list: [],
      goods: [],
      goodsType: [],
      addGoods: {
        classificationID: "",
        classificationName: "",
      },
      goodsList: [],
      goodsName: {
        goodsId: "",
        goodsName: "",
      },
      ruleForm: {
        icon: [],
        address: "",
        customerServicePhone: "",
        region: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        image: [],
      },
      rules: {
        address: [
          { required: true, message: "请输入公司地址", trigger: "blur" },
        ],
        customerServicePhone: [
          {
            required: true,
            trigger: "blur",
            validator: validateServicePhone,
          },
        ],
        region: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "change",
          },
        ],
        delivery: [
          { required: true, message: "请填写活动形式", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      merchantsName: "merchantsName",
      merchantsId: "merchantsId",
    }),
  },

  created() {
    this.init();
  },
  methods: {
    init() {
      return Promise.all([this.getMerchants(), this.getgoodsType()]);
    },
    // 上传
    beforeUpload(e) {
      const isLt50M = e.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      }
      const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
      const fd = new FormData();
      // fd.append('avatar_file', e)
      // fd.append('avatar_data', avatar_data)
      fd.append("file", e);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        res.url = res.imgurl;
        this.dialogImageUrl = res.url;
        this.ruleForm.image.push(res);
      });
    },
    beforeUpload1(e) {
      const isLt50M = e.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      }
      const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
      const fd = new FormData();
      // fd.append("avatar_file", e);
      // fd.append("avatar_data", avatar_data);
      fd.append("file", e);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        // res.url = res.imgurl;
        this.dialogImageUrl = res.url;
        this.ruleForm.icon.push(res);
      });
    },

    // 保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editMerchants();
        } else {
          return false;
        }
      });
    },
    // 获取店铺首页信息
    getMerchants() {
      const params = {
        type: "getMerchantsIndex",
        data: {
          merchantsID: this.merchantsId,
        },
      };
      this.$http.post(this.$api.getMerchantsIndex, params).then((res) => {
        if (res) {
          console.log("获取店铺首页信息", res.goodsList);
          this.goodsList = res.goodsList;
          this.ruleForm = res;
        }
      });
    },
    // 修改店铺首页信息
    editMerchants() {
      console.log("修改店铺首页信息", this.goodsList);
      this.ruleForm.goodsList = this.goodsList;
      const params = {
        type: "editMerchantsIndex",
        data: this.ruleForm,
      };
      this.$http.post(this.$api.editMerchantsIndex, params).then((res) => {
        if (!res) {
          this.$nextTick(() => {
            this.getMerchants();
            this.$baseMessage("修改成功", "success");
          });
        }
      });
    },
    // 添加主推商品
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传1张`);
    },
    handlePictureCardPreview(file, fileList) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片删除
    handleRemove(file, fileList) {
      const index = this.ruleForm.image.findIndex((item) => {
        return item.uid === file.uid;
      });
      this.ruleForm.image.splice(index, 1);
    },
    // 图片删除
    handleRemove1(file, fileList) {
      const index = this.ruleForm.icon.findIndex((item) => {
        return item.uid === file.uid;
      });
      this.ruleForm.icon.splice(index, 1);
    },
    hanleAdd() {
      if (
        this.addGoods.classificationID === "" ||
        this.goodsName.goodsId === ""
      ) {
        this.$baseMessage("请选择主推商品", "error");
        return false;
      }

      if (this.goodsList && this.goodsList.length > 0) {
        const goodsIdArr = [];
        this.goodsList.forEach((item) => {
          goodsIdArr.push(item.goodsID);
        });
        if (goodsIdArr.indexOf(this.goodsName.goodsId) > -1) {
          return this.$baseMessage("该商品已添加，请重新选择", "error");
        } else {
          this.goodsList.push({
            goodsID: this.goodsName.goodsId,
            goodsName: this.goodsName.goodsName,
          });
        }
      } else {
        this.goodsList.push({
          goodsID: this.goodsName.goodsId,
          goodsName: this.goodsName.goodsName,
        });
      }
    },
    hanleremove(name) {
      const index = this.goodsList.findIndex((item) => {
        return item === name;
      });
      this.goodsList.splice(index, 1);
    },
    // 获取商品分类
    getgoodsType() {
      const params = {
        type: "getMerchGoodsClassification",
        data: {
          merchantsId: this.merchantsId,
        },
      };
      this.$http.post(this.$api.getGoodsClassification, params).then((res) => {
        this.goodsType = res.goodsClassifications;
      });
    },
    // 根据分类选择商品
    getGoodsByClassification(id) {
      const params = {
        type: "getGoodsMerchClassification",
        data: {
          merchantsId: this.merchantsId,
          classificationsId: id,
          state: "1",
        },
      };
      this.$http.post(this.$api.getGoodsClassification, params).then((res) => {
        this.goods = res.goods;
        this.goodsName.goodsId = "";
      });
    },
    // 根据商品id获取商品名称
    getGoodsname(id) {
      this.goods.find((item) => {
        if (item.goodsId === id) {
          this.goodsName = JSON.parse(JSON.stringify(item));
          return;
        }
      });
    },
    // 上移
    upClick(index) {
      const newArr = this.swapItems(this.goodsList, index, index - 1);
      this.goodsList = newArr;
    },
    // 下移
    downClick(index) {
      const newArr = this.swapItems(this.goodsList, index, index + 1);
      this.goodsList = newArr;
    },
    swapItems(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-button {
  display: block;
  margin-bottom: 20px;
  margin-top: 8px;
}
.el-upload--picture-card {
  position: relative;
  img {
    position: absolute;
    left: 0;
  }
}
.addlist {
  line-height: 50px;
  label {
    cursor: pointer;
    margin-left: 10px;
  }
}
.add_el-form-item__content {
  .el-form-item__content {
    position: inherit !important;
    display: flex;
    .el-select {
      margin-right: 15px;
    }
  }
}
.list {
  line-height: 30px;
}
.el-button--text {
  cursor: pointer;
}
.img {
  margin-left: 50px;
}
</style>

