<template>
  <div class="auditGoods app-container">
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      v-loading="loading"
      label-width="170px"
    >

    <el-form-item  label="商品名称：">
           <Upload disabled width="100px" height="100px" type="goodsImg" :imgUrl="setQuery.goodsImg" @uploadEnd="uploadEnd"></Upload>
      </el-form-item>
      <el-form-item label="商品名称：" prop="goodsName">
        <el-input
        disabled
          v-model="setQuery.goodsName"
          class="item-width-300"
        ></el-input>
      </el-form-item>
       <el-form-item  label="商品类型：" prop="goodsType">
        <el-select disabled 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>

       <template v-if="setQuery.goodsType == 1">
        <el-form-item  label="优惠券类型：" prop="goodsCode">
        <el-select disabled v-model="setQuery.goodsCode" class="item-width-300" placeholder="请选择优惠券类型">
            <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
      </el-form-item>
    

      <el-form-item  v-if="setQuery.goodsCode == 102 " label="立减额度：" prop="discount">
        <el-input
        disabled
          v-model.number="setQuery.discount"
          :maxlength="18"
          class="item-width-300"
        >
        <template slot="append">元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item  v-else-if="setQuery.goodsCode == 103" label="折扣率：" prop="discount">
        <el-input
        disabled
          v-model.number="setQuery.discount"
          :maxlength="18"
          class="item-width-300"
        >
        <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item  v-else-if="setQuery.goodsCode == 104" label="满减规则：" prop="discount">
        <el-input
        disabled
          v-model.number="setQuery.condition"
          :maxlength="18"
          class="item-width-150"
        >
        </el-input>
        减
         <el-input
         disabled
          v-model.number="setQuery.discount"
          :maxlength="18"
          class="item-width-100"
        >
        </el-input>
      </el-form-item>
      </template>

      <!-- 研学 -->
      <template v-else-if="setQuery.goodsType == 6">
        <el-form-item label="研学栏目：" prop="columnId">
          <el-cascader
            disabled
            class="item-width-300"
            v-model="setQuery.columnId"
            show-all-levels
            :options="columnOptions"
            :props="{ value: 'id', label: 'columnName', children: 'pages' }"
            clearable
          ></el-cascader>
        </el-form-item>
      </template>

     
      <el-form-item  label="售价：" prop="realPrice">
        <el-input
        disabled
          v-model.number="setQuery.realPrice"
          :maxlength="18"
          class="item-width-300"
        >
        <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item  label="库存：" v-if="setQuery.goodsCode == 101" prop="exchangeCodeDataCode">
        <el-select disabled v-model="setQuery.exchangeCodeDataCode" class="item-width-300" placeholder="请选择库存">
            <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
      </el-form-item>
       <el-form-item  label="库存：" v-else prop="stockCount">
        <el-input
        disabled
          v-model.number="setQuery.stockCount"
          :maxlength="18"
          class="item-width-300"
        >
        </el-input>
      </el-form-item>

      <template v-if="setQuery.goodsCode == 102 || setQuery.goodsCode == 103 || setQuery.goodsCode == 104">
          <el-form-item disabled label="有效期限制：" prop="validType">
            <el-radio disabled v-model="setQuery.validType" :label="1">不限制</el-radio>
            <el-radio disabled v-model="setQuery.validType" :label="2">限制</el-radio>
            <div v-show="setQuery.validType == 2">
              <el-date-picker
              disabled
              v-model="date1"
              type="datetimerange"
              class="item-width-400"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
              </el-date-picker>
            </div>
          </el-form-item>

          <el-form-item disabled label="使用限制时间：" prop="shopName">
          <div class="tabs">
            <div class="tab" v-for="(item,index) in tabs" :class="[setQuery.useType == index+1?'active':'']" :key="item" @click="handleTab(index+1)">{{item}}</div>
          </div>
            <el-date-picker
            disabled
            v-show="setQuery.useType == 2"
            v-model="date"
            type="datetimerange"
            class="item-width-400"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
            </el-date-picker>

              <el-select
              disabled
                v-show="setQuery.useType == 3 || setQuery.useType == 4"
                v-model="setQuery.day"
                clearable
                filterable
                class="item-width-400"
                placeholder="请选择">
                <el-option
                v-for="item in nums"
                :key="item"
                :label="(nums == 7 ?'每周':'每月') + item + (nums == 31 ?'号':'')"
                :value="item">
                </el-option>
            </el-select>

          </el-form-item>

          <el-form-item  label="过期自动退：" prop="advent">
            <el-radio disabled v-model="setQuery.advent" :label="1">是</el-radio>
            <el-radio disabled v-model="setQuery.advent" :label="2">否</el-radio>
          </el-form-item>

          <el-form-item  label="支付抵扣限制：" prop="useMethod">
            <el-radio disabled v-model="setQuery.useMethod" :label="1">线上和线下</el-radio>
            <el-radio disabled v-model="setQuery.useMethod" :label="2">仅线上</el-radio>
            <el-radio disabled v-model="setQuery.useMethod" :label="3">仅线下</el-radio>
          </el-form-item>

          <el-form-item disabled label="优惠券适用商品范围：" prop="useRangeType">
            <el-radio disabled v-model="setQuery.useRangeType" :label="1">全部商品</el-radio>
            <el-radio disabled v-model="setQuery.useRangeType" :label="2">指定商品</el-radio>
          </el-form-item>

          <template v-if="setQuery.useRangeType == 2 && setQuery.useMethod != 3">
           <el-table
          :data="tableData"
          tooltip-effect="dark"
          border
          v-loading="tableLoading"
          style="width: 100%"
        >
          <el-table-column
            align="center"
            label="商品名称"
            prop="goodsName"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="goodsType"
            align="center"
            label="类型"
            show-overflow-tooltip
          >
          <template slot-scope="scope">
            {{scope.row.goodsType == 1?'优惠券':'研学'}}
          </template>
          </el-table-column>
          <el-table-column
            prop="discountContent"
            align="center"
            label="所属店铺"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column prop="address" align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-box">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="query.currentPage"
            :page-sizes="[10]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
          </template>

         
      </template>


      <!-- 研学 -->
      <template v-if="setQuery.goodsType == 6">
        <el-form-item label="使用限制时间：" prop="shopName">
          <div class="tabs">
            <div
              class="tab"
              v-for="(item, index) in tabs"
              :class="[setQuery.useType == index + 1 ? 'active' : '']"
              :key="item"
              @click="handleTab(index + 1)"
            >
              {{ item }}
            </div>
          </div>
          <el-date-picker
            v-show="setQuery.useType == 2"
            v-model="date"
            disabled
            type="datetimerange"
            class="item-width-400"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
          >
          </el-date-picker>

          <el-select
            v-show="setQuery.useType == 3 || setQuery.useType == 4"
            v-model="setQuery.day"
            clearable
            filterable
            class="item-width-400"
            placeholder="请选择"
          >
            <el-option
              v-for="item in nums"
              :key="item"
              :label="
                (nums == 7 ? '每周' : '每月') + item + (nums == 31 ? '号' : '')
              "
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="研学商品顶部图：" prop="studyItem">
          <div class="notice">
            (图片支持jpg, png, bmp格式，建议上传100kb~500kb大小文件)
          </div>
          <Upload
            type="studyItem"
            id="studyItem"
            width="300px"
            height="200px"
            disabled
            uploadType="GOODS_INFO"
            :imgUrl="setQuery.studyItem"
            @uploadEnd="uploadEnd"
          ></Upload>
        </el-form-item>
      </template>

      <el-form-item label="商品详情：" prop="goodsDescribe">
        <!-- <div style="border: 1px solid #E4E7ED; width: 500px;border-radius:4px;padding:0 15px;min-height:60px;" v-html="setQuery.goodsDescribe">
        </div> -->
        <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.goodsDescribe"
            :defaultConfig="editorConfig"
            :mode="editorMode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>

    <el-form-item label="商品购买设置：">
        <el-table
      :data="setQuery.details"
      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="form.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>

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

    </el-form>

    <div class="btn-group" v-if="mode != 'detail'">
       <el-button  type="danger" :loading="loading"  @click="save(3)">拒 绝</el-button>
     <el-button type="primary" :loading="loading"  @click="save(2)">通过</el-button>
    </div>
  </div>
</template>

<script>
import {allCouponByShop,get,getGoodsCoupon,search,goodsCouponSet,check } from '@/api/goods'
import {getSetMealNameAndId} from '@/api/common'
import { getData } from "@/api/study";
import {getRuleList } from "@/api/rule";
import Upload from '@/components/Upload';
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import OSS from "ali-oss";
import { requestUploadImg, finishUploadImg } from "@/api/common";
export default Vue.extend( {
    components: {
        Upload,
        Editor,
        Toolbar
    },
  data() {
    return {
      editor: null,
      editorMode: "default", // or 'simple'
      mode:'add',
      that:this,
        nums:7,
        value2:'',
        tabs:['不限制','自定义时间','每周','每月'],
        tab:0,
        date:'',
        date1:'',
        loading:false,
        tableLoading:false,
        tableData:[],
        columnOptions: [],
        ruleOptions:[],
        imgList:[],
        query:{
          shopId:localStorage.getItem('epid'),
          currentPage:1,
          pageSize:10,
        },
        total:0,
        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); //上传失败之后
                    });
                }
              });
            },
          },
        },
      },
      setQuery: {
        "advent": 1,
        "condition": 0,
        "day": 0,
        "discount": 0,
        "exchangeCodeDataCode": "",
        "goodsCode": "",
        "goodsDescribe": "",
        "goodsId": "",
        "goodsImg": "",
        "goodsName": "",
        "goodsType": "",
        "goodsWeight": 0,
        "realPrice": 0,
        "shopId": localStorage.getItem('epid'),
        "stockCount": 0,
        "useEndTime": "",
        "useMethod": 1,
        "useRange": "",
        "useRangeType": 1,
        "useStartTime": "",
        "useType": 1,
        "validEndTime": "",
        "validStartTime": "",
        "validType": 1,
        "shareId":0,
      },
      form:{
        shareId:'',
          checkDetail:''
      },
      rules: {
        checkDetail: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
        shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
      },
      options: [
        {
          value: "1",
          label: "优惠券",
        },
        {
          value: "6",
          label: "研学",
        },
        {
          value: "5",
          label: "商品",
        },
      ],
      options1: [
        // {
        //   value: "102",
        //   label: "立减券",
        // },
        // {
        //   value: "103",
        //   label: "折扣券",
        // },
        // {
        //   value: "104",
        //   label: "满减券",
        // },
        // {
        //   value: "101",
        //   label: "兑换码",
        // },
      ],
      options2: [],
      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]);
            }
          }]
        },
    };
  },
  watch: {
    
    // 使用限制时间
    date(val) {
      if(val){
        this.setQuery.useStartTime = val[0]
        this.setQuery.useEndTime = val[1]
      }else{
        this.setQuery.useStartTime = ''
        this.setQuery.useEndTime = ''
        
      }
    },
    // 有效期时间
    date1(val) {
      if(val){
        this.setQuery.validStartTime = val[0]
        this.setQuery.validEndTime = val[1]
      }else{
        this.setQuery.validStartTime = ''
        this.setQuery.validEndTime = ''
        
      }
    },

  },
  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: {
     onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    // 获取研学栏目
    getData() {
      getData().then((res) => {
        if (res.state == "Success") {
          this.columnOptions = res.content;
        }
      });
    },
    uploadEnd(val){
      this.setQuery[val.type] = val.url
    },
    handleSizeChange(val) {
      this.query.currentPage = 1;
      this.query.pageSize = val;
      this.allCouponByShop()

    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.allCouponByShop()
    },
    handleTab(val){
      if(this.mode == 'detail') return
        this.setQuery.useType = val
        this.setQuery.day = ''
        val == 3?this.nums =7:this.nums =31
    },
    save(applyState) {
      if(applyState == 2){
        this.form.checkDetail = this.form.checkDetail || '通过'
        this.rules = {
          shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
        }
      }else{
        this.rules = {
          checkDetail: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
          shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
        }
      }
      
      this.$refs.form.validate((v) => {
        if (v) {
          this.loading = true
          this.goodsCouponSet().then(res=>{
            this.check(applyState)
          })
        }
      });
    },
    // 获取兑换码库存
    getCode() {
      search({currentPage:1,pageSize:999}).then((res) => {
        if (res.state == "Success") {
          res.content.records.map(item=>{
              this.options2.push({
                label:item.exchangeCodeDataName +`(${item.totalNum})`,
                value:item.exchangeCodeDataId
              })
          })
        }
      });
    },
    // 获取优惠券类型
    getGoodsCoupon(){
      getGoodsCoupon().then(res=>{
        if (res.state == "Success") {
          for (const key in res.content) {
            if (Object.hasOwnProperty.call(res.content, key)) {
                this.options1.push({
                  label:res.content[key],
                  value:key
                }) 
            }
          }
        }
      })
    },
    // 所有商品
    allCouponByShop(){
      this.tableLoading = true
      allCouponByShop(this.query).then(res=>{
        this.tableLoading = false
        if (res.state == "Success") {
          this.tableData = res.content
        }
      })
    },
     // 商品详情
    get(){
      this.loading = true
      get({goodsId:this.$route.query.id,shopId:this.$route.query.shopId}).then(res=>{
      this.loading = false
          if(res.state == 'Success'){
            this.setQuery = res.content
            this.setQuery.shopId = localStorage.getItem('epid')
            // 使用时间为自定义时
            if(this.setQuery.useType == 2){
              this.date = [this.setQuery.useStartTime,this.setQuery.useEndTime]
            }
            // 限制有效期
            if(this.setQuery.validType == 2){
              this.date1 = [this.setQuery.validStartTime,this.setQuery.validEndTime]
            }
            this.setQuery.exchangeCodeDataCode = this.setQuery.exchangeCodeDataId
            this.form.shareId = this.setQuery.shareId 
            // 初始化购买设置
            if(!this.setQuery.details){
              this.setQuery.details = []
              this.mealOption.map(item=>{
                this.setQuery.details.push({
                    "buyNum": 0,
                    "buyPrice": this.setQuery.realPrice,
                    "buySet": 1,
                    "setMealId": item.value
                })
              })
            }
          }
      })
    },
    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.unshift({
              label:'无套餐',
              value:0
            })
            resolve()
          }
        })
      })
    },
    // 商品购买配置
    goodsCouponSet(){
      return new Promise((resolve,reject)=>{
        goodsCouponSet({goodsCouponSets:this.setQuery.details,goodsId:this.$route.query.id,shopId:this.$route.query.shopId}).then(res=>{
              this.loading = true
              if(res.state == 'Success'){
                resolve()
              }
            })
      })
      
    },
    check(applyState){
      
      check({ 
            "applyState": applyState,
            "shareId": this.form.shareId,
            "checkDetail": this.form.checkDetail,
            "goodsDescribe":this.setQuery.goodsDescribe,
            "checkUserId": localStorage.getItem('epid'),
            "goodsId": this.$route.query.id}).then(res=>{
              this.loading = false
              if(res.state == 'Success'){
                this.$notify({
                    title: '成功',
                    message: '操作成功',
                    type: 'success'
                  });
                  this.$router.push('/operationManage/goodsAudit/index')
              }
            })
    },
    // 规则
    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
            })
          })
        }
      });
    },
  },
    created () {
      this.mode = this.$route.query.mode || 'add'
      this.getCode()
      this.getData();
      this.getGoodsCoupon()
      this.getRuleList()
      this.getSetMealNameAndId().then(()=>{
        if(this.$route.query.id){
          this.get()
        }
      })
    },
});
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
@import '@/styles/element-variables';
.auditGoods {
  padding-bottom: 40px;
  .btn-group{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .tabs{
    display:flex;
    border-radius: 4px;
    margin-bottom: 10px;
    cursor: pointer;
    .tab{
        width: 90px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border: 1px solid #f1f1f1;
    }
  }
  .active{
    color: $--color-primary;
    border: 1px solid $--color-primary!important;
    background: #d1d3fa;
    border-radius: 4px;
  }

  .notice{
    font-size: 12px;
    color: #ccc;
  }

}
</style>