<!--
 * @Author: wj 1454560336@qq.com
 * @Date: 2023-11-24 14:39:54
 * @LastEditors: wenjie 1454560336@qq.com
 * @LastEditTime: 2024-11-08 11:53:02
 * @FilePath: \admin-manage\src\views\operationManage\goodsManage\goodsDetail.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div class="addGoods app-container">
    <el-form
      :model="setQuery"
      :rules="rules"
      v-loading="loading"
      label-width="170px"
      disabled
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="基本信息">
          <el-form-item label="商品类型："  prop="goodsType">
            <el-select
              v-model="setQuery.goodsType"
              class="item-width-300"
              placeholder="请选择商品类型"
            >
              <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 label="商品名称：" prop="goodsName">
            <el-input
              v-model="setQuery.goodsName"
              class="item-width-300"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品描述：" prop="goodsDescribe">
            <el-input
              v-model="setQuery.goodsDescribe"
              class="item-width-300"
            ></el-input>
          </el-form-item>

          <el-form-item label="商品分类：" prop="goodsCateId">
            <el-cascader
              class="item-width-300"
              v-model="setQuery.goodsCateId"
              :show-all-levels="false"
              placeholder=""
              :options="typeOptions"
              :props="{ value: 'id', label: 'cateName', children: 'child', emitPath: false }"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="市场价：" prop="marketPrice">
            <el-input
              type="number"
              v-model="setQuery.marketPrice"
              class="item-width-300"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

        <template v-if="setQuery.prePlatformType && mode=='audit'">
          <el-form-item label="商品操作平台商品信息：">
            <div class="platformType">{{filterMasterName(setQuery.prePlatformType)}}</div>
          </el-form-item>
           <el-form-item label="售价：" prop="platformPrice">
            <el-input
              type="number"
              v-model="setQuery.platformPrice"
              class="item-width-300"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </template>


        <el-form-item v-if="mode=='detail'" label="商品上架平台商品信息：">
          <el-checkbox-group v-model="setQuery.platformType" prop="platformType">
            <div class="flex" v-for="(item,index) in setQuery.prices" :key="index" ><el-checkbox :label="item.platformType">{{filterMasterName(item.platformType) }}</el-checkbox> 
            <el-form-item  >
              <el-input type="number" v-model="setQuery.prices[index].price" class="item-width-300 ml10">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            </div>
          </el-checkbox-group>
        </el-form-item>


          <el-form-item label="售价：" v-else prop="realPrice">
            <el-input
              type="number"
              v-model="setQuery.realPrice"
              class="item-width-300"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-form-item label="库存：" prop="stockNum">
            <el-input
              type="number"
              v-model.number="setQuery.realStockNum"
              class="item-width-300"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="排序：" prop="goodsSort">
            <el-input
              type="number"
              v-model.number="setQuery.goodsSort"
              class="item-width-300"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="商品图片：" prop="goodsPath">
            <Upload
              width="100px"
              height="100px"
              type="goodsPath"
              :imgUrl="setQuery.goodsPath"
              @uploadEnd="uploadEnd"
            ></Upload>
          </el-form-item>
           <!-- <el-form-item label="退款服务：">
            <el-radio-group v-model="setQuery.refundType">
              <el-radio :label="1">自动退款</el-radio>
              <el-radio :label="3">人工审核退款</el-radio>
              <el-radio :label="2">不支持退款</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-tab-pane>

        <el-tab-pane label="商品规格" name="商品规格">
           <el-form-item :label="item.attrName == 'validDay'?'有效期':  item.attrName" v-for="(item, index) in setQuery.attrs" :key="'attrs' + index" :prop="'attrs.' + index + '.attrValue'" >
                <el-input
                v-if="item.attrName == 'validDay'"
                placeholder="有效期不能超过90天"
                v-model="item.attrValue"
                class="item-width-300 ml20 "
              >
              </el-input>
              <el-input
                v-else
                placeholder="请输入属性名称,多行用回车换行"
                type="textarea"
                v-model="item.attrValue"
                 :maxlength="500"
                class="item-width-300 ml20 textarea"
              >
              </el-input>
               <el-checkbox
                class="ml20"
                v-model="item.status"
                :true-label="1"
                :false-label="2"
                v-if="index>1 "
              ></el-checkbox>
          </el-form-item>
          <!-- <el-form-item label="商品属性：">
            <div
              class="item"
              v-for="(item, index) in setQuery.attrs"
              :key="'attrs' + index"
            >
              <el-input
                placeholder="请输入属性名称"
                v-model="item.attrName"
                class="item-width-150"
              >
              </el-input>
              <el-input
                placeholder="请输入属性名称,多行用回车换行"
                type="textarea"
                v-model="item.attrValue"
                class="item-width-300 ml20 textarea"
              >
              </el-input>
              <el-checkbox
                class="ml20"
                v-model="item.status"
                :true-label="1"
                :false-label="2"
              ></el-checkbox>
              <i class="icon el-icon-plus"></i>
              <i class="icon el-icon-minus"></i>
            </div>
          </el-form-item> -->

          <el-form-item label="商品规格：">
            <div
              class="item"
              v-for="(item, index) in setQuery.specs"
              :key="'specs' + index"
            >
              <el-input
                placeholder="请输入属性名称"
                v-model="item.specName"
                class="item-width-150"
              >
              </el-input>
              <div class="box">
                <div class="" v-for="(i, d) in setQuery.specs[index].specValues" :key="d">
                  <el-input
                    placeholder="请输入属性名称"
                    v-model="i.specValue"
                    class="item-width-300 ml20"
                  >
                  </el-input>
                  <el-checkbox
                    class="ml20"
                    v-model="i.status"
                    :true-label="1"
                    :false-label="2"
                  ></el-checkbox>
                  <el-button class="add1" type="text"
                    >+添加属性</el-button
                  >
                  <el-button class="add1 red" type="text"
                    >-删除属性</el-button
                  >
                </div>
              </div>
                <i
                  class="add icon el-icon-plus"
   
                ></i>
                <i
                  class="remove icon el-icon-minus"
                
                ></i>
            </div>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="商品详情">
          <el-form-item label="商品详情：" prop="goodsDetail">
            <!-- <div style="border: 1px solid #ccc; width: 500px">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="editorMode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="setQuery.goodsDetail"
                :defaultConfig="editorConfig"
                :mode="editorMode"
                @onCreated="onCreated"
              />
            </div> -->
              <div style="border: 1px solid #ccc; width: 800px;border-radius:4px;padding:0 15px;min-height:60px;" v-html="setQuery.goodsDetail">
              </div>
          </el-form-item>
          
        </el-tab-pane>
        <el-tab-pane label="其他信息" name="其他信息">
          <el-form-item label="销量：" prop="saleNum">
            <el-input
              type="number"
              v-model.number="setQuery.saleNum"
              class="item-width-300"
            >
            </el-input>
          </el-form-item>

          <!-- <el-form-item label="库存预警：" prop="stockThresholdNum">
            <el-input
              type="number"
              v-model.number="setQuery.stockThresholdNum"
              class="item-width-300"
            >
            </el-input>
          </el-form-item> -->
        </el-tab-pane>
         <el-tab-pane v-if="$route.query.mode != 'detail'" label="商品配置" name="商品配置">
           <el-form
            :model="setQuery"
            ref="setQuery"
            :rules="rules"
            v-loading="loading"
            label-width="170px"
          >
          <!-- <el-form-item label="商品税费：" prop="taxRate">
            <el-input
              type="number"
              :disabled="false"
              v-model.number="setQuery.taxRate"
              class="item-width-300"
            >
             <template slot="append">%</template>
            </el-input>
          </el-form-item>
           <el-form-item label="提现手续费：" prop="withdrawalRate">
            <el-input
              type="number"
              v-model.number="setQuery.withdrawalRate"
              class="item-width-300"
            >
             <template slot="append">‰</template>
            </el-input>
          </el-form-item>

          <el-form-item label="商品购买设置：">
            <el-table
              :data="setQuery.goodsSets"
              tooltip-effect="dark"
              border
              style="width: 600px"
            >
              <el-table-column
                align="center"
                label="人员类型"
                prop="setMealId"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.setMealId | filterMeal(that) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="shopName"
                align="center"
                label="购买设置"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-checkbox
                    :true-label="2"
                    :false-label="1"
                    v-model="scope.row.buySet"
                    >限制购买</el-checkbox
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="shopName"
                align="center"
                label="限购数量"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.buyNum"
                    :maxlength="8"
                    size="small"
                    class="item-width-100"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="shopName"
                align="center"
                label="优惠价格"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.buyPrice"
                    :maxlength="8"
                    size="small"
                    class="item-width-100"
                  >
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item> -->
            <el-form-item label="分账规则：" prop="shareId">
            <el-select
              v-model="setQuery.shareId"
              class="item-width-300"
              placeholder="请选择分账规则"
            >
              <el-option
                v-for="item in ruleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <template v-if="mode == 'audit'">
           <el-form-item label="价格标签：">
            <el-radio-group  v-model="showGoodsLabel">
              <el-radio :label="1">展示标签</el-radio>
              <el-radio :label="2">不展示标签</el-radio>
            </el-radio-group>
            <div v-if="showGoodsLabel == 1">
               <el-radio-group  v-model="labelId">
                <el-radio v-for="item in labelList" :key="item.id" :label="item.id">{{item.labelName}}</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          </template>

           <el-form-item v-if="mode == 'audit'" label="审核意见：" prop="checkDetail">
            <el-input
              type="textarea"
              placeholder="请输入审核意见"
              v-model="setQuery.checkDetail"
              maxlength="400"
              :rows="6"
              class="item-width-500"
              show-word-limit
            >
            </el-input>
          </el-form-item>
       </el-form>

        </el-tab-pane>
      </el-tabs>
    </el-form>

    <div class="btn-group" v-if="mode == 'audit'">
      <el-button  type="danger" :loading="loading"  @click="save(3)">拒 绝</el-button>
      <el-button type="primary" :loading="loading"  @click="save(2)">通过</el-button>
    </div>
    <div class="btn-group" v-else-if="mode == 'edit'">
      <el-button   :loading="loading"  @click="">取消</el-button>
      <el-button type="primary" :loading="loading"  @click="save()">保存</el-button>
    </div>
  </div>
</template>

<script>
import { goodsSet, detail, getData,check,getLabelList } from "@/api/goods";

import {getRuleList } from "@/api/rule";
import { requestUploadImg, finishUploadImg,getSetMealNameAndId } from "@/api/common";
import Upload from "@/components/Upload";
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import OSS from "ali-oss";
export default Vue.extend({
  components: {
    Upload,
    Editor,
    Toolbar,
  },
  data() {
    return {
      that:this,
      showGoodsLabel:1,
      labelId:0,//标签id
      labelList:[],//标签列表
      activeName: "基本信息",
      editor: null,
      editorMode: "default", // or 'simple'
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            // 自定义上传
            customUpload(file, insertFn) {
              // file 即选中的文件
              requestUploadImg({
                fineName: file.name,
                operate: "OTHER",
              }).then((res) => {
                if (res.state == "Success") {
                  const client = new OSS({
                    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                    region: res.content.endPoint.split(".")[0],
                    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
                    accessKeyId: res.content.token.accessKeyId,
                    accessKeySecret: res.content.token.accessKeySecret,
                    // 填写Bucket名称。
                    bucket: res.content.bucket,
                    stsToken: res.content.token.securityToken,
                  });

                  client
                    .multipartUpload(res.content.paths[0].join("/"), file)
                    .then((r) => {
                      // 上传完成
                      finishUploadImg([{ path: res.content.paths[0] }]).then(
                        (msg) => {
                          if (msg.state == "Success") {
                            let url =
                              "http://" +
                              res.content.bucket +
                              "." +
                              res.content.endPoint +
                              "/" +
                              res.content.paths[0].join("/");
                            insertFn(url, "", "");
                          }
                        }
                      );
                    })
                    .catch((err) => {
                      console.log(err); //上传失败之后
                    });
                }
              });
            },
          },
        },
      },
      mode: "add",
      loading: false,
      setQuery: {
        attrs: [
          {
            attrName: "",
            attrValue: "",
            status: 2,
          },
        ],
        goodsCateId: "",
        goodsDescribe: "",
        goodsDetail: "",
        goodsId: "",
        goodsName: "",
        goodsPath: "1",
        goodsSort: 0,
        goodsType: "",
        marketPrice: 0,
        realPrice: 0,
        saleNum: 0,
        shopId: localStorage.getItem("epid"),
        specs: [
          {
            specName: "",
            specValues: [
              {
                specValue: "",
                status: 2,
              },
            ],
          },
        ],
        stockNum: 0,
        stockThresholdNum: 0,
        syncEnable: 0,
        syncRang: "",
        validRang: 0,
        taxRate:0,
        withdrawalRate:0,
        shareId:'',
        goodsSets:[],
        refundType:1
      },
      rules: {
        taxRate: [
          { required: true, message: "请输入商品税费", trigger: "blur" },
        ],
        withdrawalRate: [
          { required: true, message: "请输入提现手续费", trigger: "blur" },
        ],
        shareId: [{ required: true, message: "请输入分账规则", trigger: "change" }],
          checkDetail: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
       
       
      },
      options: [
        {
          value: "801",
          label: "研学商品",
        },
        {
          value: "802",
          label: "虚拟商品充值",
        },
        {
          value: "803",
          label: "餐饮商品",
        },
      ],
      typeOptions: [],
      ruleOptions:[],
      mealOption: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  filters: {
    filterMeal: function (val, that) {
      let msg;
      that.mealOption.map((item) => {
        if (val == item.value) {
          msg = item.label;
        } else if (val === 0) {
          msg = "无套餐";
        }
      });
      return msg;
    },
  },
  methods: {

    add(index, key) {
      //最外层的index，属性名，内部输入框的index
      let obj;
      if (key == "attrs") {
        obj = {
          specName: "",
          specValue: "",
          status: 2,
        };
      } else if (key == "specs") {
        obj = {
          specName: "",
          specValues: [
            {
              specValue: "",
              status: 2,
            },
          ],
        };
      } 
      this.setQuery[key].splice(index + 1, 0, obj);
    },
    add1(index, d) {
      this.setQuery.specs[index].specValues.splice(d + 1, 0, {
        specValue: "",
        status: 2,
      });
    },
    remove1(index, d) {
      if (this.setQuery.specs[index].specValues.length == 1) return;
      this.setQuery.specs[index].specValues.splice(d, 1);
    },
    remove(index, key) {
      if (this.setQuery[key].length == 1) return;
      this.setQuery[key].splice(index, 1);
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      if (this.mode == "detail") {
        this.editor.disable();
      }
    },
    uploadEnd(val) {
      this.setQuery[val.type] = val.url;
    },

    save(applyState) {
       if(applyState == 2){
        this.setQuery.checkDetail = this.setQuery.checkDetail || '通过'
        // this.rules = {
        //   shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
        //    taxRate: [
        //   { required: true, message: "请输入商品税费", trigger: "blur" },
        //   ],
        //   withdrawalRate: [
        //     { required: true, message: "请输入提现手续费", trigger: "blur" },
        //   ],
        // }
      }else if(applyState == 3){
        if(this.setQuery.checkDetail == '通过'){
          this.setQuery.checkDetail = ''
        }
        // this.rules = {
        //   checkDetail: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
        //   shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
        //   taxRate: [
        //   { required: true, message: "请输入商品税费", trigger: "blur" },
        //   ],
        //   withdrawalRate: [
        //     { required: true, message: "请输入提现手续费", trigger: "blur" },
        //   ],
        // }
      }
      this.$nextTick(()=>{

        this.$refs.setQuery.validate((v) => {
          if (v) {
            this.loading = true;
                  // this.check(applyState)
  
            let {goodsSets,goodsId,shareId,shopId,taxRate,withdrawalRate} = this.setQuery
            let obj = {
                // "goodsCouponSets":goodsSets,
                "goodsId": goodsId,
                "shareId": shareId,
                "shopId":shopId,
                "taxRate": 0,
                "withdrawalRate": 0
            }
            goodsSet(obj).then((res) => {
              this.loading = false;
              if (res.state == "Success") {
                if(this.mode == 'audit'){
                  this.check(applyState)
                }else{
                   this.$notify({
                      title: '成功',
                      message: '操作成功',
                      type: 'success'
                    });
                    this.$router.push('/operationManage/goodsManage/index')
                }
              }
            });
          }else{
            this.activeName = '商品配置'
          }
        });
      })

    },
    // 审核
     check(applyState){
      check({ 
            "goodsId":this.$route.query.id,
            "applyState": applyState,
            "labelId":this.showGoodsLabel == 1? this.labelId:null,
            "checkDetail": this.setQuery.checkDetail,
            "checkUserId": localStorage.getItem('epid'),
            }).then(res=>{
              this.loading = false
              if(res.state == 'Success'){
                this.$notify({
                    title: '成功',
                    message: '操作成功',
                    type: 'success'
                  });
                  this.$router.push('/operationManage/goodsManage/index')
              }
            })
    },
    // 获取套餐
    getSetMealNameAndId() {
      return new Promise((resolve, reject) => {
        getSetMealNameAndId().then((res) => {
          if (res.state == "Success") {
            for (const key in res.content) {
              if (Object.hasOwnProperty.call(res.content, key)) {
                this.mealOption.push({
                  label: res.content[key],
                  value: key,
                });
              }
            }
            this.mealOption.push({
              label:'无套餐',
              value:0
            })

            resolve();
          }
        });
      });
    },
    // 获取商品分类
    getData() {
      getData().then((res) => {
        if (res.state == "Success") {
          this.typeOptions = res.content.map(e=>{
            try{
              e.child.map(
              r=>{
                delete r.child
                return r
              }
            )
            }catch(e){
              console.log(e);
            }
            return e
          });
        }
      })
    },
    // 规则
    getRuleList() {
      getRuleList({currentPage:1,pageSize:999}).then((res) => {
        if (res.state == "Success") {
          res.content.records.map(item=>{
            this.ruleOptions.push({
              label:item.shareRule,
              value:item.id
            })
          })
        }
      });
    },

    // 商品详情
    get() {
      this.loading = true;
      detail({
        goodsId: this.$route.query.id,
        resource: this.mode == 'audit'? 3:1,
        // shopId: localStorage.getItem("epid"),
      }).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.setQuery = res.content;
          this.setQuery.prices = JSON.parse(this.setQuery.prices)
          if(this.setQuery.prices){
            this.setQuery.platformType = []
            this.setQuery.prices.map(item=>{
              if(item.platformType == this.setQuery.prePlatformType){
                this.setQuery.platformPrice = item.price
              }
              if(item.status == 2){
                this.setQuery.platformType.push(Number(item.platformType) )
              }
            })
          }
          this.labelId = Number(res.content.goodsLabelId) || this.labelList[0].id
          this.setQuery.goodsCateId = Number(this.setQuery.goodsCateId);
            // 初始化购买设置
            if (!this.setQuery.goodsSets.length) {
                this.setQuery.goodsSets = [];
                this.mealOption.map((item) => {
                this.setQuery.goodsSets.push({
                    buyNum: 0,
                    buyPrice: this.setQuery.realPrice,
                    buySet: 1,
                    setMealId: item.value,
                });
                });
            }
        }
      });
    },
    // 获取标签列表
    getLabelList(){
      getLabelList({
        currentPage: 1,
        pageSize: 99,}).then(res=>{
        if(res.state == 'Success'){
          this.labelList = res.content.records
        }
      })
    },
  },
  created() {
    this.options = []
    let goodsTypeObj = JSON.parse(sessionStorage.getItem('goodsTypeObj'))
    for (const key in goodsTypeObj) {
      if (Object.hasOwnProperty.call(goodsTypeObj, key)) {
        this.options.push({
          label:goodsTypeObj[key],
          value:key
        })
      }
    }
    this.getRuleList()
    this.getData();
    this.getLabelList()
    this.mode = this.$route.query.mode || "add";
    this.getSetMealNameAndId().then(() => {
      if (this.$route.query.id) {
        this.get();
      }
    });
  },
});
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

<style lang="scss" >
@import "@/styles/element-variables";
.addGoods {
  padding-bottom: 40px;
  .platformType{
    font-size: 14px;
    color: #606266;
  }
  .flex{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .ml20{
      margin-left: 20px;
    }
    .textarea textarea{
      height: 40px;
    }
    .icon {
      font-size: 18px;
      font-weight: bold;
      margin-left: 10px;
      cursor: pointer;
    }
    .box {
    }
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  

}
</style>