<template>
  <div>
    <div class="from-content">
      <el-form :model="goodsForm" :rules="goodsRules" ref="goodsForm" label-width="150px" class="demo-ruleForm" label-position="right" v-loading="loading">
        <div class="form-section">
          <h3>基础信息</h3>
          <el-form-item label="福利渠道" class="w-630">{{ enterpriseName }}</el-form-item>
          <el-form-item label="礼品名称" class="w-630" prop="giftName">
            <dm-input :byte-type="1" type="text" v-model="goodsForm.giftName" :maxlength="30" placeholder="请输入礼品名称"></dm-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>销售信息</h3>
          <el-form-item label="礼物信息">
            <el-table :data="goodsForm.tableData" style="width:700px;" class="table-error" :header-cell-class-name="starAdd">
              <el-table-column label="礼品编码" prop="giftNo">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.giftNo'">
                    <el-input style="width:120px;" v-model.trim="scope.row.giftNo" type="text" placeholder="请输入内容" class="mr10"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="库存" prop="stock">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.stock'">
                    <dm-input-number width="170px" v-model="scope.row.stock" :precision="0" :max="999999" controls-position="right" :min="0" placeholder="上传文件后自动填充" disabled></dm-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="礼品条形码" prop="giftBarNo">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.giftBarNo'">
                    <el-input style="width:120px;" v-model.trim="scope.row.giftBarNo" type="text" placeholder="请输入内容" class="mr10"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="礼品成本" class="w-630" prop="costPrice">
            <el-input-number v-model="goodsForm.marketPrice" :min="0" :max="999999" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item prop="marketPrice">
            <template slot="label">
              <el-tooltip open-delay="200" class="item" effect="dark" content="提供给会员作为兑换参考的划线价格" placement="top">
                <span class="undeline-dash">市场价</span>
              </el-tooltip>
            </template>
            <!-- <dm-input-amount v-model="goodsForm.marketPrice" width="480"></dm-input-amount> -->
            <el-input-number v-model="goodsForm.marketPrice" :min="0" :max="999999" :precision="2"></el-input-number>
            <el-popover placement="top-start" width="380" trigger="hover">
              <img src="../../assets/images/eg.png" alt />
              <el-button slot="reference" type="text" style="margin-left:15px;">查看示例</el-button>
            </el-popover>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>图文详情</h3>
          <el-form-item label="礼品主图" required>
            <div class="member-upload-image">
              <span class="tip-warm" style="display:block">图片宽度≥700px，图片宽高比1：1，单张图片大小不超过2MB，至少上传1张，最多上传 5 张</span>
              <div class="member-upload-image">
                <dm-upload-picture :action-url="actionUrl" :image-list="image" :max-image-length="maxlength" accept="image/jpeg, image/jpg, image/png, image/gif" :before-upload="beforeUpload" @uploadOnSuccess="uploadOnSuccess" @deleteImage="deleteImage"></dm-upload-picture>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="礼品详情">
            <dm-editor :width="editorWidth" :value="goodsForm.giftDescrption" @change="handleChange"></dm-editor>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>福利设置</h3>
          <!-- 虚拟 -->
          <el-form-item label="发货内容" required>
            <template>
              <div style="display:flex;">
                <dm-editor width="500" height="300" :value="goodsForm.giftDescrption" @change="handleChange2"></dm-editor>
                <div class="ml20">
                  <p>用户申请履约后，发货内容将自动发送</p>
                  <p>第一步：编辑发货内容，变量使用大括号标记"{}"</p>
                  <p>第一步：保存内容，并下载模板。<el-button type="text">点击下载</el-button></p>
                  <p>第一步：上传模板。</p>
                  <div class="upload-btn">
                    <el-upload class="upload-ele" show-file-list :action="uploadAction" :on-success="uploadFile" with-credentials>
                      <el-button><i class="el-icon-upload2" style="margin-right:5px"></i>点击上传</el-button>
                    </el-upload>
                  </div>
                  <div style="display:flex;justify-content:space-between;width:400px"><span>导入说明：</span><el-button type="text" @click="checkUploadDetail">查看内容</el-button></div>
                  <p>1.填充空缺内容，导出所有项均为必填项;</p>
                  <p>1.请勿导入重复的内容，导入的内容在原来基础上增加库存;</p>
                  <p>1.上传完整仅支持.xlsx .xls文件的导入，填充数据不超过“10万”条;</p>
                </div>
              </div>
              <el-button class="mt10" type="primary" @click="saveDescription">保存</el-button>
            </template>
          </el-form-item>
          <el-form-item label="库存消耗方式" prop="checkList">
            <template>
              <el-tooltip class="tips-content" effect="dark" open-delay="200" popper-class="store-tips" placement="top-start">
                <div slot="content">固定库存：通过占用的方式获得固定可用库存，不会被其他应用/活动所消耗。<br/>实时库存：不占用库存，使用福利中心“可占库存”，与其他应用使用同个库存。</div>
                <i class="el-icon-question" style="color:#1890ff"></i>
              </el-tooltip>
              <el-checkbox-group v-model="goodsForm.checkList" class="ml20" @change="changeStockUse">
                <el-checkbox label="0">固定库存</el-checkbox>
                <el-checkbox label="1">实时库存</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>售后服务</h3>
          <el-form-item prop="refundFlag" label="支持申请退货" required>
            <template>
              <el-tooltip class="tips-content" effect="dark" open-delay="200" popper-class="store-tips" content="若商品不支持退货，则该礼品出库后不支持生成退货单" placement="top-start">
                <i class="el-icon-question" style="color:#1890ff"></i>
              </el-tooltip>
              <el-radio class="ml20" v-model="goodsForm.refundFlag" :label="1">是</el-radio>
              <el-radio v-model="goodsForm.refundFlag" :label="0">否</el-radio>
            </template>
          </el-form-item>
        </div>
        <div class="form-section mb56">
          <h3>权限设置</h3>
          <el-form-item prop="refundFlag" label="操作人权限" required>
            <dm-acc-group-select :etype.sync="goodsForm.operatorAuth" :group-ids.sync="goodsForm.shopCodeList" />
          </el-form-item>
        </div>
        <div class="fixed-btn">
          <dm-perm-button type="primary" @click="submitForm('goodsForm')" v-if="giftId">保存</dm-perm-button>
          <dm-perm-button type="primary" @click="submitForm('goodsForm')" v-else>确认新建</dm-perm-button>
          <el-button plain @click="goBack">返回</el-button>
        </div>
      </el-form>
      <div class="anchor-link">
        <div class="link-item" :class="linkIndex === 0 ? 'link-item-active' : ''" @click="jump(0)">基础信息</div>
        <div class="link-item" :class="linkIndex === 1 ? 'link-item-active' : ''" @click="jump(1)">销售信息</div>
        <div class="link-item" :class="linkIndex === 2 ? 'link-item-active' : ''" @click="jump(2)">图文信息</div>
        <div class="link-item" :class="linkIndex === 3 ? 'link-item-active' : ''" @click="jump(3)">兑换设置</div>
        <div class="link-item" :class="linkIndex === 4 ? 'link-item-active' : ''" @click="jump(4)">售后服务</div>
        <div class="link-item" :class="linkIndex === 5 ? 'link-item-active' : ''" @click="jump(5)">权限设置</div>
      </div>
    </div>
    <check-upload-detail v-if="dialogVisible"></check-upload-detail>
  </div>
</template>
<script>
import { request } from '../../utils/request';
// import { deepClone } from '../../utils/index';
import api from '@/api/gift.js';
import uploadUrl from '@/api/common.js';
const {  giftGet, giftUpdate, giftSave } = api;
import checkUploadDetail from './module/check-upload-detail';
export default {
  components: {
    // importCoupon
    checkUploadDetail,
  },
  data() {
    let marketPriceValidator = (rule, value, callback) => {
      let reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
      if (value) {
        if (!reg.test(Number(value))) {
          return callback(new Error('市场价必须为正数'));
        } else {
          if(Number(value) > 9999999){
            return callback(new Error('市场价最大为7位数'));
          }
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      uploadUrl: uploadUrl,
      linkIndex: 0,
      bread: [
        {
          breadName: '礼品管理'
        },
        {
          breadPath: '/gift-manage/virtual-gift',
          breadName: '虚拟礼品'
        },
        {
          breadName: '新建礼品'
        }
      ],
      goodsForm: {
        giftName: '', // 礼品名称
        marketPrice: '', // 礼品市场价
        giftImages: '', // 礼品主图URL，分割
        giftDescrption: '', // 礼品详情
        checkList: [],
        refundFlag: 0,
        operatorAuth: '', // 操作人权限
        deliveryType: [], // 配送方式 1物流发货 2门店自提 3文本券码
        stockUseType: '', // 库存使用类型（0:占用,1:动态 , 2占用+动态）
        shopCodeList: '', // 门店code
        tableData: [
          {
            giftNo: '',
            stock: undefined,
            giftBarNo: ''
          }
        ]
      },
      goodsRules: {
        giftName: [ { required: true, message: '请输入礼品名称', trigger: 'blur' } ],
        marketPrice: [ { validator: marketPriceValidator, trigger: 'blur' } ],
        refundFlag: [ { required: true, message: '请选择是否支持退款', trigger: 'change' } ],
        deliveryType: [ { required: true, message: '请选择配送方式', trigger: 'change' } ],
        checkList: [ { required: true, message: '请选择库存消耗方式', trigger: 'change' } ]
      },
      giftId: '',
      editorWidth: 900,
      // 图片墙数据
      // projectName: 'welfare', // 当前项目名(必传参数)
      // wxFlag: '1', // '1': 表示需要返回微信图片地址(可选参数),插件内已默认 '1'
      actionUrl: '/api-plug/upload-images', // 必选参数，上传的相对地址 String 类型,切勿硬编码写死地址
      maxlength: 5, // 图片数量 默认 5
      // uploadAction: window.location.origin + '/api-marketing/upload/upload-image?requestProject=marketing',
      uploadAction: 'https://four.gicdev.com/api-marketing/upload/upload-image?requestProject=marketing',
      openStorePick: 0,
      btnLoading: false,
      loading: false,
      enterpriseName: '', // 商户名称
      handleData: {
        giftSkuCostPrice: '',
        stock: undefined,
        giftSkuCode: '',
        skuBarCode: ''
      },
      dialogVisible: false,
      description: ''
    };
  },
  mounted() {
    this.$emit('updateBread', this.bread);
    this.$emit('showAside', true);
    this.getLoginUser();
    this.giftId = this.$route.query.giftId;
    if (this.giftId) {
      this.bread[2].breadName = '编辑礼品';
      this.getMess();
    }
    // this.getOpenStorePick();
    this.$nextTick(function() {
      window.addEventListener('scroll', this.onScroll, true);
    });
  },
  methods: {
    checkUploadDetail(){
      this.dialogVisible = true;
    },
    uploadFile(file){
      console.log(file);
    },
    // 表头添加必填标识符
    starAdd(obj){
      if(obj.column.label === '库存' || obj.column.label === '成本价(元)') {
        return 'star';
      }
    },
    handleChange2(value){
      this.description = value;
      console.log(this.goodsForm.giftDescrption);
    },
    saveDescription(){
      console.log(this.description);
      let index = this.description.indexOf('{'); // 字符出现的位置
      let indexCopy;
      let index2 = this.description.indexOf('}'); // 字符出现的位置
      // let index3Copy = index2;
      let num2 = 0; // 这个字符出现的次数
      let num = 0; // 这个字符出现的次数
      while(index !== -1) {
        console.log(index); // 打印字符串出现的位置
        indexCopy = index;
        num++; // 每出现一次 次数加一
        index = this.description.indexOf('{', index + 1); // 从字符串出现的位置的下一位置开始继续查找
        console.log(index, indexCopy);
        console.log(index - indexCopy == 1);
        if(index - indexCopy == 1){
          this.$message.error('{}不能嵌套出现');
        }
      }
      while(index2 !== -1) {
        console.log(index2); // 打印字符串出现的位置
        num2++; // 每出现一次 次数加一
        index2 = this.description.indexOf('}', index2 + 1); // 从字符串出现的位置的下一位置开始继续查找
      }
      console.log(num, num2);
      if(num !== num2 || num > 3 || num2 > 3){
        this.$message.error('请填写正确的格式');
      }
    },
    changeDelivery(value){
      console.log(value);
    },
    // 处理库存消耗方式
    changeStockUse(value){
      if(value.length > 1){
        this.goodsForm.stockUseType = 2;
      }else{
        this.goodsForm.stockUseType = value[0];
      };
    },
    // 获取商户信息
    getLoginUser(){
      request({ url: '/gic-auth-web/user/get-login-user' }).then(res => {
        this.enterpriseName = res.result.enterpriseName;
      });
    },
    onScroll() {
      let scroll = document.documentElement.scrollTop || document.body.scrollTop;
      let jump = document.querySelectorAll('.form-section');
      jump.forEach((item, index) => {
        if (scroll >= item.offsetTop) {
          // 滚动到对应的锚记改变样式
          this.linkIndex = index;
        }
      });
    },
    jump(num) {
      let index = Number(num);
      this.linkIndex = index;
      // 用 class="d_jump" 添加锚点
      let jump = document.querySelectorAll('.form-section');
      let total = jump[index].offsetTop;
      let distance = document.documentElement.scrollTop || document.body.scrollTop;
      // let distance = 200;
      // 平滑滚动，时长500ms，每10ms一跳，共50跳

      let step = total / 50;

      if (total > distance) {
        smoothDown();
      } else {
        let newTotal = distance - total;
        step = newTotal / 50;
        smoothUp();
      }
      function smoothDown() {
        if (distance < total) {
          distance += step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothDown, 10);
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
      function smoothUp() {
        if (distance > total) {
          distance -= step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothUp, 10);
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
    },
    // getOpenStorePick() {
    // let params = {
    //   giftId: this.giftId,
    //   checkStoreList: 1
    // };
    // request
    //   .get('/api-integral-mall/pickup/get-pickup-config', { params })
    //   .then(res => {
    //     if (res.data.code === '0000') {
    //       this.openStorePick = res.data.result.openStorePick;
    //     } else {
    //       this.$message.error(res.data.message);
    //     }
    //   })
    //   .catch(error => {
    //     this.$message.error({
    //       duration: 1000,
    //       message: error.message
    //     });
    //   });
    // console.log(111);
    // },
    getMess() {
      let params = {
        id: this.giftId
      };
      this.$emit('updateLoading');
      giftGet(params)
        .then(res => {
          if (res.code === '0000') {
            let resResult = res.result;
            this.goodsForm.changeDelivery = resResult.changeDelivery; // 兑换方式
            this.goodsForm.giftName = resResult.giftName; // 礼品名称
            this.goodsForm.tableData.giftNo = resResult.giftNo;
            this.tableData.stock = resResult.stock;
            this.tableData.giftBarNo = resResult.giftBarNo;
            this.goodsForm.marketPrice = resResult.marketPrice; // 市场价
            let img = resResult.giftImages.split(',');
            // this.goodsForm.giftImages = [];
            if (img.length) {
              for (let item of img) {
                this.image.push({
                  url: item
                });
              }
            } // 礼品主图
            this.goodsForm.giftDescrption = resResult.giftDescrption; // 礼品详情
            this.goodsForm.refundFlag = resResult.refundFlag; // 是否支持退货
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        }).finally(() => this.$emit('updateLoading'));
      console.log(222);
    },
    // 上传前
    beforeUpload(file) {
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('请上传小于2MB的图片');
        return false;
      }
      if (file.width < 700 || file.width / file.width != 1 / 1) {
        this.$message.error('请上传宽度≥700px，宽高比1：1的图片');
        return false;
      }
      return true;
    },
    // 上传成功 返回的图片对象 里面有图片 大小 类型 等相关信息
    uploadOnSuccess(obj) {
      // 目前返回两个参数 {res:res,file:file}
      obj.file.url = obj.res.result[0].downloadUrl;
      // obj.file.imageType = 1;
      this.image.push(obj.file);
      let handelImage = [];
      this.image.forEach((item, index) =>{
        handelImage[index] = item.url;
      });
      this.goodsForm.giftImages = handelImage.join('');
    },
    // 删除图片 返回图片列表的索引 你可以根据这个索引去找对应图片的id
    deleteImage(i) {
      this.image.splice(i, 1);
      let handelImage = [];
      this.image.forEach((item, index) =>{
        handelImage[index] = item.url;
      });
      this.goodsForm.giftImages = handelImage.join('');
    },
    handleChange(val) {
      this.goodsForm.giftDescrption = val;
    },
    goBack() {
      this.$router.push({ path: '/gift-manage/virtual-gift' });
    },
    // 保存
    submitForm(goodsForm) {
      if(this.btnLoading) return;
      if (this.image.length === 0) {
        this.$message.error('请上传主图');
        return false;
      }
      this.$refs[goodsForm].validate(valid => {
        if (!valid){
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        }else{
          this.btnLoading = true;
          this.$emit('updateLoading');
          let params = {
            // giftId: this.giftId,
            giftType: 1, // 实物礼品
            // shopId: '', // 门店id
            giftName: this.goodsForm.giftName, // 礼品名称
            marketPrice: this.goodsForm.marketPrice, // 市场价
            costPrice: this.goodsForm.tableData[0].costPrice, // 成本价
            stock: this.goodsForm.tableData[0].stock, // 库存
            giftNo: this.goodsForm.tableData[0].giftNo, // 礼品编码
            giftBarNo: this.goodsForm.tableData[0].giftBarNo, // 礼品条形码
            giftImages: this.giftImages, // 礼品主图
            giftDescrption: this.goodsForm.giftDescrption, // 礼品详情
            refundFlag: this.goodsForm.refundFlag, // 是否支持退货
            giftSpecInfo: JSON.stringify(this.goodsStandardInfo),
            skuList: '',
            operatorAuth: this.goodsForm.operatorAuth, // 操作人权限
            deliveryType: this.goodsForm.deliveryType, // 兑换方式
          };
          this.btnLoading = true;
          if (this.giftId) {
            params.giftId = this.giftId;
            giftSave(params).then(res =>{
              if (res.code === '0000') {
                this.$router.push({ path: '/gift-manage/real-gift-detail' });
                this.btnLoading = false;
              } else {
                this.btnLoading = false;
                this.$message.error(res.message);
              }
            }).finally(() => this.$emit('updateLoading'));
          }else{
            params.giftId = '';
            giftUpdate(params).then(res =>{
              if (res.code === '0000') {
                this.$router.push({ path: '/gift-manage/real-gift-detail' });
                this.btnLoading = false;
              } else {
                this.btnLoading = false;
                this.$message.error(res.message);
              }
            }).finally(() => this.$emit('updateLoading'));
          }
        }
      });
    }
  },
};
</script>
<style lang="less" scoped>
.upload-btn {
  height: 40px;
  border: 1px dashed rgba(192, 196, 204, 1);
  display: inline-block;
  font-size: 14px;
  color: #c0c4cc;
  cursor: pointer;
  margin-right: 10px;
  width: 250px;
  border-radius: 4px;
}
.upload-btn .el-icon-upload2 {
  font-size: 18px;
  color: #c0c4cc;
}
.upload-btn:hover {
  border-color: #1890ff;
}
.upload-ele .el-button {
  border: none;
  color: #c0c4cc;
}
.upload-ele .el-button--small {
  padding: 0;
}
.w-630 {
  width: 630px;
}
.mb56 {
  margin-bottom: 56px;
}
.from-content {
  position: relative;
  .demo-ruleForm {
    // margin-bottom: 40px;
    .form-section {
      // margin-bottom: 60px;
      padding: 30px 20px;
      h3 {
        color: #303133;
        font-size: 14px;
        font-weight: 700;
        margin-bottom: 20px;
        margin-left: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #dfdfdf;
      }
      .tip-warm {
        color: #909399;
        font-size: 12px;
        i {
          color: #faad14;
          margin-right: 5px;
        }
      }
    }
    .fixed-btn {
      width: 100%;
      height: 56px;
      position: fixed;
      bottom: 0px;
      left: 200px;
      background: #fff;
      border-top: 1px solid #e4e7ed;
      text-align: center;
      margin-left: -100px;
      z-index: 2;
      font-size: 0px;
      .el-button {
        margin-top: 12px;
      }
    }
  }
  .anchor-link {
    width: 120px;
    position: fixed;
    right: 24px;
    top: 180px;
    background: #fff;
    .link-item {
      height: 24px;
      line-height: 24px;
      color: #606266;
      font-size: 12px;
      border-left: 2px solid #ebeef5;
      padding-left: 18px;
      cursor: pointer;
    }
    .link-item-active {
      border-left: 2px solid #2d5aea;
      color: #2d5aea;
    }
  }
}

.ml20 {
  margin-left: 20px;
}
.mr10 {
  margin-right: 10px;
}
.tips-content {
  position: absolute;
  left: -4px;
  top: 8px;
}
.store-tips {
  width: 200px;
  position: absolute;
  left: -10px;
}
/* 规格值 */
</style>
<style>
.table-error .el-form-item__error {
  display: none !important;
}
.damolish .el-form-item__label::after {
  content: "";
}
.damolish .el-tooltip__popper {
  width: 245px;
}
table th.star div::before {
  content: '*';
  color: red;
}
.right-border {
  border-right: 1px solid #ebeef5;
}
.mopney-input span {
  display: none !important;
}
.from-content .see-btn {
  color: #909399;
  margin-left: 15px;
}
.from-content .see-btn:hover {
  color: #2f54ed;
}
</style>
