<template>
  <div class="app-container">
    <el-card class="box-card">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
 </el-card>

    <el-card>
      <i class="el-icon-tickets">商品信息数据列表</i>
    </el-card>

    <el-card class="box-card">
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品描述" align="center" prop="productDesc">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title="商品描述"
            width="500"
            trigger="click">
            <div v-html="scope.row.productDesc"></div>
            <el-button slot="reference" type="text">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="type" />
      <el-table-column label="冗余字段" align="center" prop="typeIds" />
      <el-table-column label="商品主图" align="center" prop="img">
          <template slot-scope="scope">
            <img :src="scope.row.img" alt="加载失败" width="80px" height="80px"/>
          </template>
      </el-table-column>
      <el-table-column label="商品轮播图" align="center" prop="carouselImages" >
        <template slot-scope="scope">
          <img :src="scope.row.carouselImages" alt="加载失败" width="80px" height="80px"/>
        </template>
      </el-table-column>
      <el-table-column label="品牌信息" align="center" prop="brand" />

      <el-table-column label="品牌状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="上架"
            inactive-text="下架"
            inactive-value="0"
            active-value="1"
            @change="updateInfoStatus(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="规格信息" align="center" prop="ruleId" />
      <el-table-column label="0：添加商品信息 1：添加规格信息 2：添加描述信息" align="center" prop="step"/>
      <el-table-column label="商品描述" align="center" prop="productDesc">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title="商品描述"
            width="500"
            trigger="click">
            <div v-html="scope.row.productDesc"></div>
            <el-button slot="reference" type="text">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-steps :active="active" finish-status="success">
          <el-step title="添加商品信息"> </el-step>
          <el-step title="添加规格信息"></el-step>
          <el-step title="添加描述信息"></el-step>
        </el-steps>
        <div v-show="active == 0">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入商品名称" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="品牌信息" prop="brandId">
                  <el-select v-model="form.brand" placeholder="请选择品牌" clearable>
                    <el-option v-for="item in brandList" :label="item.name" :value="item.id" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="分类" prop="brand">

                  <el-cascader
                    v-model="form.type"
                    :options="typeList"
                    :props="{ expandTrigger: 'hover' ,value:'catId',label:'name',children:'childrenList'}"
                    @change="handleChange"></el-cascader>
                </el-form-item>
              </div>
            </el-col>

          </el-row>
          <el-form-item label="商品主图" prop="img">
            <image-upload v-model="form.img" placeholder="请输入商品主图" :limit="1" :is-show-tip="false"/>
          </el-form-item>
          <el-form-item label="商品轮播图" prop="carouselImages">
            <image-upload v-model="form.carouselImages" placeholder="请输入内容" :limit="1" :is-show-tip="false"/>
          </el-form-item>
        </div>

        <div v-show="active == 1">
          <el-form-item label="规格信息" prop="ruleId">
            <el-select v-model="form.rule" placeholder="请选择规格" v-on:change="changeRuleInfoListByRuleId" clearable>
              <el-option v-for="item in ruleList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form ref="form" :model="skuFormTemplate" label-width="80px">

            <el-row>
              <el-col :span="5">
            <el-form-item label="商品库存">
              <el-input-number v-model="skuFormTemplate.stock" :min="1" :max="99999" style="width: 100px" ></el-input-number>
            </el-form-item>
              </el-col>

         <el-col :span="5">
            <el-form-item label="商品价格">
              <el-input-number v-model="skuFormTemplate.price" :min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>
         </el-col>

         <el-col :span="5">
            <el-form-item label="商品进价">
              <el-input-number v-model="skuFormTemplate.purchasePrice":min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>
         </el-col>

            <el-form-item label="商品售价">
              <el-input-number v-model="skuFormTemplate.sellingPrice":min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>

            <el-form-item label="规格图片">
              <ImageUpload v-model="skuFormTemplate.image" :limit="1"></ImageUpload>
            </el-form-item>

           <el-col :span="5">
            <el-form-item label="编号">
              <el-input-number v-model="skuFormTemplate.number":min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>
           </el-col>

           <el-col :span="5">
            <el-form-item label="重量">
              <el-input-number v-model="skuFormTemplate.weight":min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>
           </el-col>

           <el-col :span="5">
            <el-form-item label="体积">
              <el-input-number v-model="skuFormTemplate.volume":min="1" :max="99999" style="width: 100px"></el-input-number>
            </el-form-item>
           </el-col>

           <el-col :span="5">
            <el-button type="primary" @click="onSubmit">立即同步</el-button>
            <el-button type="warning" @click="onClear">取消</el-button>
           </el-col>
            </el-row>
          </el-form>



          <template>
            <el-table
              :data="tableBodyTemplate"
              style="width: 100%">
              <el-table-column v-for="column in tableColumnHeaderTemplate" :key="column.prop"
                :prop="column.prop"
                :label="column.label">
                <template slot-scope="scope">
                  <el-input-number v-if="column.prop.indexOf('image') == -1 && column.prop.indexOf('xxx') == -1"
                                   v-model="scope.row[column.prop]" :min="1" :max="9999999999" label="描述" style="width: 120px" ></el-input-number>
                  <ImageUpload v-else-if="column.prop.indexOf('image') > -1 " v-model="scope.row[column.prop]" :limit="1" style="width: 120px "></ImageUpload>
                  <span v-else>{{scope.row[column.prop]}}</span>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </div>


        <div v-show="active==2">
          <el-button @click="pc = true; move =false">商品描述</el-button>
          <editor v-if="pc" v-model="form.productDesc" :min-height="150"/>
        </div>


      </el-form>
      <el-button style="margin-top: 12px;" @click="step" :disabled="active <1">上一步</el-button>
      <el-button style="margin-top: 12px;" @click="next" :disabled="active >= 2">下一步</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-card>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/product/info";
import ImageUpload from "@/components/ImageUpload"
import {listBrand} from "@/api/product/brand"
import { listRule } from "@/api/product/rule"
import {listAll7 } from "@/api/product/type"
import data from "@/views/system/dict/data.vue";
import item from "@/layout/components/Sidebar/Item.vue";


export default {
  components:{ImageUpload},
  name: "Info",
  data() {
    return {
      options: [{
        value: '',
        label: '',
        children: [{
          value: '',
          label: '',
        }]
      }],
      muliple:true,
      //富文本
      pc:true,
      move:false,
      typeList: [],
      type: null,
      children: [{}],
      tableColumnHeaderTemplate:[],
      tableBodyTemplate:[],
      active: 0,
      rule: [],
      ruleAttrList:[],
      brandList:[],
      ruleList:[],
      tableData:[],
      MallProductInfoList: [],
      stepsMap: {
        0: '添加商品信息',
        1: '添加规格信息',
        2: '添加描述信息',
      },
      skuFormTemplate:{
        'stock': '0',
        'price': '0',
        purchasePrice: '0',
        sellingPrice: '0',
        image: '',
        number: '0',
        weight: '0',
        volume: '0'},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      brandName: null,
      ruleName: null,
      // 商品信息表格数据
      infoList: [],

      //商品品牌名称
      name: null,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        step: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // brandId: [
        //   { required: true, message: "商品品牌不能为空", trigger: "blur" }
        // ]
      }
    };
  },
  created() {
    this.getList();
    this.initBrandListInfo();
    this.initRuleListInfo();
    this.initTypeListInfo();
  },
  methods: {

    handleChange(){

    },

    updateInfoStatus(params) {
      console.log(params)
      const {id, status} = params
      this.updateInfoById({id, status})
    },


    onSubmit() {
      this.settingsOrnClear(true)
    },

    onClear() {
      this.settingsOrnClear();
    },

    settingsOrnClear(flag){
      for (let skuFormTemplateKey in this.skuFormTemplate) {
        this.tableBodyTemplate.forEach(item=>{
          for (let itemKey in item) {
            if(skuFormTemplateKey===itemKey){
              if(flag){
                item[itemKey]=this.skuFormTemplate[skuFormTemplateKey]
              }else{
                item[itemKey]=''
              }
            }
          }
        });
      }
    },

    changeRuleInfoListByRuleId(object) {
      this.tableColumnHeaderTemplate = [];
      this.tableBodyTemplate = [];
      let ruleInfo = this.ruleList.find(item => object == item.id);
      if (!ruleInfo) {
        return;
      }

      let ruleAttrJson;
      try {
        ruleAttrJson = JSON.parse(ruleInfo.ruleAttr);
      } catch (error) {
        console.error('Error parsing ruleAttr JSON:', error);
        return;
      }

      ruleAttrJson.forEach((ruleAttr, index) => {
        this.tableColumnHeaderTemplate.push({'prop': `xxx${index}`, 'label': ruleAttr.ruleType});
      });

      const cartesian = (ruleAttrJson, index, current) => {
        if (index === ruleAttrJson.length) {
          this.tableBodyTemplate.push({...current});
          return;
        }
        for (let i = 0; i < ruleAttrJson[index].ruleAttrList.length; i++) {
          const updatedCurrent = {...current}; // Create a copy of current object
          updatedCurrent[`xxx${index}`] = ruleAttrJson[index].ruleAttrList[i];
          current['image'] = '';
          cartesian(ruleAttrJson, index + 1, updatedCurrent);
        }
      };

      cartesian(ruleAttrJson, 0, {});

      this.tableBodyTemplate.forEach(item=>{
        let sku = [];
        for (let itemKey in item) {
          if(itemKey.indexOf("xxx") > -1){
            sku.push(item[itemKey])
          }
        }
        sku = sku.join(',');
        item['sku'] = sku;
      })

      this.tableColumnHeaderTemplate.push(
        {prop:'stock',label:'商品库存'},
        {prop:'price',label:'商品价格'},
        {prop:'purchasePrice',label:'商品进价'},
        {prop:'sellingPrice',label:'商品售价'},
        {prop:'image',label:'商品图片'},
        {prop:'number',label:'编号'},
        {prop:'weight',label:'重量'},
        {prop:'volume',label:'体积'},
      )
    },

    /** 查询商品类型**/
    initTypeListInfo() {
      listAll7().then(
        res => {
          if (res.code == 200) {
            this.typeList = res.data
          }
        }
      )
    },

    /**查询商品规格**/
    initRuleListInfo() {
      let  params = {
        status: 0
      };
      listRule(params).then(res =>{
        if(200 == res.code){
          this.ruleList = res.data.list;
        }
      });
    },
    /**查询品牌表**/
    initBrandListInfo() {
      let  params = {
        status: 0
      };
      listBrand(params).then(res =>{
        if(200 == res.code){
          this.brandList = res.data.list;
        }
      });
    },
    // 上一步
    step() {
      this.active--;
    },
    // 下一步
    next() {
      this.active++;
    },

    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        let productInfoList = response.data.list;
        productInfoList.forEach(item => {
          let num = item.step;
          item.step = this.switchStepByNum(num)
        })
        this.infoList = productInfoList;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 根据num切换step
    switchStepByNum(num) {
      if (num == null || num == '' || num == undefined) {
        this.$modal.msgError("num is NULL");
        return;
      }

      for (let stepsMapKey in this.stepsMap) {

        if (num == stepsMapKey) {
          return this.stepsMap[stepsMapKey];
        }
      }
    },
     // * 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        productDesc: null,
        type: null,
        typeIds: null,
        img: null,
        carouselImages: null,
        commentCount: null,
        collectCount: null,
        brand: null,
        status: null,
        unit: null,
        keywords: null,
        ruleId: null,
        brandId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        step: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        let typeList = [];
        let data = response.data;
        this.active = Number(data.step);
        let ruleId = data.ruleId;
        this.changeRuleInfoListByRuleId(ruleId);
        if(data.skuInfoList !=null && data.skuInfoList.length > 0){
          data.skuInfoList.forEach(item => {
            if (item.sku !== null) {
              let skuArray = item.sku.split(',');
              for (let i = 0; i < skuArray.length; i++) {
                item[`xxx${i}`] = skuArray[i];
              }
            }
          });
        }

        this.tableBodyTemplate=data.skuInfoList;

        this.form = data;
        let typeAttr = data.typeIds.split(",")
        typeAttr.forEach(item => {
          typeList.push(item * 1)
        });
        this.form.type = typeList
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let typeIds = this.form.type.join(',');
            let type = this.form.type[this.form.type - 1];
            this.form.typeIds = typeIds;
            this.form.type = type;
            this.form.step = this.active

          this.form["skuInfoList"] = this.tableBodyTemplate;
          if (this.form.id != null) {
           this.updateInfoById(this.form)
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    updateInfoById(data) {
      updateInfo(data).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
