<template>
  <div class="execution">
    <basic-container v-loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div ref="oneDiv">
          <div class="zm_info_header">
            <p>编辑商品信息</p>
          </div>
          <p></p>
          <el-form-item required label="商品名称 :"  prop="goodsName" label-width="100px" style="float: left">
            <el-input  v-model="form.goodsName"  style="float: right;width: 50%;float: left"></el-input>
          </el-form-item>
          <el-form-item :initDropDownBox="initDropDownBox" required label="商品分类 :" prop="classifyId" label-width="100px" >
            <!-- 下拉 -->
            <el-select v-model="form.classifyId">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item required label="商品规格 :" prop="spec" label-width="100px">
            <el-button type="primary" @click="addSpec">添加规格</el-button>
            <el-dialog
              title="添加规格" :visible.sync="dialogVisible" width="40%"
              :before-close="handleClose">
              <el-form ref="addSpecForm" :model="addSpecForm" :rules="rules" label-width="100px">
                <el-form-item label="选择规格名称" prop="specName">
                  <avue-select v-model="specName" @change="getSpecValue" placeholder="选择规格名称" type="tree" :dic="dic" ></avue-select>
                </el-form-item>
                <el-form-item label="选择规格值" prop="specValue">
                  <el-checkbox-group v-model="specValue" size="medium">
                    <el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
              <!-- 底部 -->
              <span slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="loading" @click="addSpec_submit()" style="width: 200px; height: 40px;display:block;margin:0 auto;" >确认添加</el-button>
              </span>
            </el-dialog>
          </el-form-item>
          <div class="custom-table" v-show="tableShow">
            <el-table :data="tableData3" border style="width: 100%;border: 1px solid #6b6b6b" ref="myTable">
              <!-- 动态列 -->
              <el-table-column
                v-for="(item, index) in dynamicColumns"
                :key="index"
                :label="item.label"
                :prop="item.prop">

                <template slot-scope="scope">
                  <span>{{scope.row[item.label]}}</span>
                </template>
              </el-table-column>


              <el-table-column prop="date" label="售卖价格" width="180"> </el-table-column>
              <el-table-column prop="name" label="图片" width="180"> </el-table-column>
              <el-table-column prop="address" label="商品库存"> </el-table-column>
              <el-table-column prop="operate" label="操作">
                <el-button type="primary" size="mini" style="background-color: white;border: 0px;color: blue" @click="deleteRow">删除</el-button>
              </el-table-column>
            </el-table>
          </div>

          <el-form-item required label="商品列表图 :" prop="goodsImage" label-width="100px" >
            <div class="upload">
              <uploader ref="uploader"/>
              <span class="sug" style="color:#2bb673;float: left;line-height: 50px;font-size: small;margin-right: 5%;font-size: 15px;">
          建议尺寸525*525
          </span>
            </div>
          </el-form-item>
          <el-form-item required label="商品详情图 :" prop="goodsImageDetail" label-width="100px" >
            <div class="upload">
              <uploader ref="uploader"/>
              <span class="sug" style="color:#2bb673;float: left;line-height: 50px;font-size: small;margin-right: 5%;font-size: 15px;">
          建议尺寸525*525
          </span>
            </div>
          </el-form-item>
          <el-form-item label="商品视频 :" prop="videoPath" label-width="100px">
            <div class="upload" >
              <uploader ref="uploader"/>
              <span class="sug" style="color:#2bb673;float: left;line-height: 50px;font-size: small;margin-right: 5%;font-size: 15px;">
          上传视频，仅支持MP4格式
          </span>
            </div>
          </el-form-item>
          <el-form-item required label="商品详情 ："  prop="imgArticle" label-width="100px">
            <editor :imgArticle="initContent" height="300px" @changed="onEditorChanged" />
          </el-form-item>
          <el-button type="primary" :loading="loading" @click="nextStep" style="width: 200px; height: 40px;display:block;margin:0 auto;" >下一步</el-button>
        </div>
        <div ref="twoDiv" style="display: none">
          <div class="zm_info_header">
            <p>编辑售卖信息</p>
          </div> <p></p>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item required label="虚拟销售量 :" prop="virtualSales" label-width="100px">
              <el-input-number  v-model="form.virtualSales"  style="float: right;width: 50%;float: left"></el-input-number>
              <span>展示销量=虚拟销量+实际销量</span>
            </el-form-item>
            <el-form-item required label="实名认证 :"  prop="isVerified" label-width="100px">
              <el-radio v-model="form.isVerified" label="1">是</el-radio>
              <el-radio v-model="form.isVerified" label="2">否</el-radio>
              <span>实名认证 通过才能购买此商品</span>
            </el-form-item>
            <el-form-item required label="A币支付 :"  prop="isAPay" label-width="100px">
              <el-radio v-model="form.isAPay" label="1">是</el-radio>
              <el-radio v-model="form.isAPay" label="2">否</el-radio>
              <span>可以使用A币支付</span>
            </el-form-item>
            <el-form-item required label="上传视频 :" prop="isUploadVideo" label-width="100px" >
              <el-radio v-model="form.isUploadVideo" label="1">是</el-radio>
              <el-radio v-model="form.isUploadVideo" label="2">否</el-radio>
              <span>上传购买视频才能购买此商品</span>
            </el-form-item>
            <el-form-item required label="电子合同 :" prop="isElectronicContract" label-width="100px" >
              <el-radio v-model="form.isElectronicContract" label="1">是</el-radio>
              <el-radio v-model="form.isElectronicContract" label="2">否</el-radio>
              <span>需要签署电子合同</span>
            </el-form-item>
            <el-form-item required label="是否发货 :" prop="isLogistics" label-width="100px">
              <el-radio v-model="form.isLogistics" label="1">是</el-radio>
              <el-radio v-model="form.isLogistics" label="2">否</el-radio>
            </el-form-item>
            <el-form-item required label="推广员佣金 ："  prop="commissionRate" label-width="100px">
              <el-input-number  v-model="form.commissionRate"  style="float: right;width: 50%;float: left"></el-input-number>
              <span>%</span>
            </el-form-item>
          </el-form>

          <el-row>
            <el-button size="medium" type="primary" :loading="loading" @click="previous" >上一步</el-button>
            <el-button size="medium" type="primary" :loading="loading" @click="onSubmit" >提交</el-button>
          </el-row>
        </div>
      </el-form>
    </basic-container>
  </div>
</template>

<script>
  import {addObj, delObj, fetchList} from '@/api/mall/mallgoods'
  import {ZmMixin} from '@/mixins/ZmMixin.js'
  import {tableOption} from "@/const/crud/mall/mallGoodsAddSpecs";
  export default {
    mixins: [ZmMixin],
    components: {
      'uploader': () => import('@/components/uploader.vue'),
      'editor': () => import('@/components/ckeditor/index.vue'),
    },
    data() {
      return {
        tableShow:false,// 规格表格隐藏
        specName:'',
        specValue:[],// 存放多选之动态标签的选中结果集
        isEditHeader: false,
        isEdit: true,
        tableData3: [],
        propArr:[], // 生成dynamicColumns时的记录
        dynamicColumns: [], // 存放动态列
        dic:[],// 规格名称
        dialogVisible: false,//弹窗
        isRow: '', //这里存储点击删除时，该按钮所处的行数
        searchForm: {},
        tableData: [],
        tableLoading: false,
        tableOption: tableOption,
        options:[],
        value: '请选择分类',
        radio:'0',
        classifyId: [],
        cities: [],// 多选之动态标签-全部规格值
        dynamicTags: [],// 多选之动态标签
        editing: false,
        saving: false,
        loading: false,
        info: {},
        addSpecForm:{specName:'',specValue:''},
        form: {
          goodsId:0,//商品ID
          goodsListId:0,//商品列表ID

          goodsName:'商品名称',// 商品名称
          classifyId:1,// 商品分类 直播商品
          virtualSales:520,// 虚拟销售量
          isVerified:0,// 实名认证
          isAPay:0,// A币支付
          isUploadVideo:0,// 上传视频
          isElectronicContract:0,// 电子合同
          isLogistics:0,// 是否发货
          commissionRate:5,// 推广员佣金

          // 规格
          specValues:'全套声卡',//添加规格-规格值
          sellingPrice:200.00,//售卖价格
          image:'http://image',//图片
          stock:1000,//库存

          goodsImageList:'http://list-image',// 商品列表图
          goodsImageDetails:'http://details-image', // 商品详情图
          goodsVideo:'http://video',// 商品视频
          goodsDetails:'<p>123</p>', // 商品详情

        },
        rules: {},
      }
    },
    mounted() {},
    computed: {
      initDropDownBox(){
        this.$axios.get("/general/mallClassify/dropDownBox").then(e =>{
          this.options=Object.values(e.data)
        })
      }
    },
    created(){
      this.tableData.forEach(item=>{
        if(item.custom){
          item.custom = JSON.parse(item.custom);
          Object.keys(item.custom).forEach(key => {
            if(this.propArr.indexOf(key) === -1){
              this.propArr.push(key);
              this.dynamicColumns.push({ prop: key, label: key});
            }
          })
        }else{
          item.custom = {};
        }
      })
    },// 动态表格
    methods: {
      deleteRow(index) {
        this.tableData3.splice(index, 1);
      },
      submit() {
        let arr = [];
        this.tableData.forEach(data => {
          let temp = {};
          temp.name = data.name;
          let obj = {};
          this.dynamicColumns.forEach(col => {
            // 仅把有效的列提交
            if (data.custom[col.prop]) {
              obj[col.prop] = data.custom[col.prop];
            }
          });
          if (JSON.stringify(obj) !== "{}") {
            temp.custom = JSON.stringify(obj);
          }
          arr.push(temp);
        });
        console.log(JSON.stringify(arr))
      },
      // 添加规格-提交
      addSpec_submit(){
        // 1.规格表格显示
        this.tableShow=true

        let specId = this.specName
        this.$axios.get("/general/mallGoodsSpec/querySpecNameById",{
          params:{specId:specId}
        }).then(response => {
          // 2.获取规格名称和规格值
          console.log("规格名称:"+response.data.data+",   规格值:"+this.specValue
            +"规格值长度："+this.specValue.length)

          // 3. 动态生成表格
          this.dynamicColumns.push({
            prop: response.data.data,
            label: response.data.data
          });

          let temp = {
            date: "2016-05-02",
            name: "http://image",
            address: "1518",
            custom: '',
            operate:'删除',

          }
          // response.data.data:this.specValue

          temp[response.data.data] = this.specValue

          this.tableData3= [temp]


        }, error => {
          console.log('错误', error.message)
        })

        // 3.关闭对话框
        this.dialogVisible = false
      },
      handleCloseTag(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },
      // 下拉框值变更事件：获取规格值
      getSpecValue(val){
        if(val!==undefined && val!==''){
          this.$axios.get("/general/mallGoodsSpecValue/multiSelectButton",{
            params:{specId:val}
          }).then(response => {
            this.cities=Object.values(response.data)
            return response.data
          }, error => {
            console.log('错误', error.message)
          })
        }
      },
      // 关闭对话框
      handleClose(done) {done();},
      //这个删除按钮主要控制点击删除按钮后的弹窗显示，然后存储你点击按钮的当前行
      deleteData(row, $index) {
        this.isShowDeleteDialog = !this.isShowDeleteDialog
        this.isRow = row.num
      },
      /** 鼠标移入cell */
      handleCellEnter (row, column, cell, event) {
        row.isEdit = true
      },
      /** 鼠标移出cell */
      handleCellLeave (row, column, cell, event) {
        row.isEdit = false
      },
      // 添加规格-对话框
      addSpec(){
        // 1.打开对话框
        this.dialogVisible = true
        // 2.加载所有规格名称
        this.$axios.get("/general/mallGoodsSpec/dropDownBox").then(e =>{
          this.dic=Object.values(e.data)
        })

      },
      // 上一步
      previous(){
        this.$refs.twoDiv.style.display='none'
        this.$refs.oneDiv.style.display='block'
      },
      // 下一步
      nextStep(){
        this.$refs.oneDiv.style.display='none'
        this.$refs.twoDiv.style.display='block'
      },
      // 提交
      onSubmit() {
        console.log(JSON.stringify(this.form))
        addObj(this.form).then(r => {
          this.loading = false
          this.$emit('success')
          this.$message.success('添加成功')
        }).catch(e => {
          this.loading = false
        })
      },
      // Editor
      onEditorChanged(html) {
        this.form.imgArticle = html
      },
      //-----------------
      getList(params) {
        this.tableLoading = true
        fetchList(Object.assign({
        }, params, this.searchForm )).then(response => {
          this.tableData = response.data.data.records
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading=false
        })
      },
      // 刷新事件
      refreshChange() {
        this.getList()
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm('是否确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          this.$message.success('删除成功')
          this.getList(this.page)
        })
      },
    }
  }
</script>

<style scoped>
  .custom-table{
    border: 1px solid #6b6b6b;
    background-color: #6b6b6b;
  }
  .item{width: 200px;}
  .el-input__inner{
    height: 24px!important;
  }
  .txt{
    line-height: 24px;
    padding: 0 9px;
    box-sizing: border-box;
  }
  .zm_info_header {
    padding: 10px 16px;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
    font-weight: 700;
    background: #dedede;
  }
  .zm_info_body .zm_info_row:not(:first-child) {
    margin-top: 10px;
  }
  span{
    color: #f5094e;
  }
  thead{border: 1px solid #6b6b6b;}
  td{
    border: 1px solid #6b6b6b;
    margin: 10px;
    padding: 10px;
  }
</style>
