<template>
  <div class="addEquities app-container" v-loading="loading1">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      label-width="230px"
    >
      <el-form-item label="权益名称：" prop="equityName">
        <el-input
          v-model="setQuery.equityName"
          :maxlength="15"
          class="item-width-300"
        ></el-input>
      </el-form-item>
      <el-form-item label="权益图标：" prop="equityImg">
        <Upload
          type="equityImg"
          id="equityImg"
          width="250px"
          height="150px"
          uploadType="OTHER"
          :imgUrl="setQuery.equityImg"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>
      <el-form-item label="权益描述：" prop="equityDetail">
        <el-input
          type="text"
          placeholder="请输入权益描述"
          v-model="setQuery.equityDetail"
          class="item-width-500"
        >
        </el-input>
      </el-form-item>

      <template v-if="setQuery.equityType == 2">
         <el-form-item label="权益说明：" prop="equityMsg">
          <el-input
            type="textarea"
            placeholder="请输入权益说明"
            v-model="setQuery.equityMsg"
            :maxlength="400"
            :rows="6"
            class="item-width-500"
            show-word-limit
          >
          </el-input>
      </el-form-item>
        <el-form-item label="关联服务：">
        <el-radio-group v-model="setQuery.bindService" @input="changeService">
          <!-- <el-radio :label="1">满减券</el-radio> -->
          <el-radio :label="2">小桔加油券</el-radio>
          <el-radio :label="3">品类权限</el-radio>
          <el-radio :label="4">视频权益</el-radio>
          <el-radio :label="5">抽奖</el-radio>
        </el-radio-group>
        </el-form-item>
        <template v-if="setQuery.bindService ==2">
          <el-form-item label="选择优惠券：" prop="bindContent">
            <el-input
            v-if="setQuery.bindContent"
            v-model="couponName"
            class="item-width-300"
            disabled
          ></el-input>
          <el-button class="ml10" @click="handleChoose(1)">{{setQuery.bindContent?'切换':'选择优惠券'}}</el-button>
          </el-form-item>
          <el-form-item label="限制核销后才能再次领取：">
            <el-checkbox v-model="setQuery.getFlag" :true-label="1" :false-label="2" ></el-checkbox>
          </el-form-item>
        </template>

           <template v-if="setQuery.bindService ==5">
          <el-form-item label="选择抽奖活动：" prop="bindContent">
            <el-input
            v-if="setQuery.bindContent"
            v-model="couponName"
            class="item-width-300"
            disabled
          ></el-input>
          <el-button class="ml10" @click="handleChoose(2)">{{setQuery.bindContent?'切换':'选择抽奖活动'}}</el-button>
          </el-form-item>

           <el-form-item label="抽奖次数：" prop="givenNum">
              <el-input
                  size="small"
                  type="number"
                  v-model.number="setQuery.givenNum"
                  :maxlength="10"
                  class="item-width-300"
              >
                <template slot="append">次</template>
              </el-input>
          </el-form-item>
          
        </template>
          <el-form-item label="赠送数量：" prop="claimNum" v-if="setQuery.bindService ==2 ||setQuery.bindService ==4">
            <div class="item">
              <div class="label">限制每人</div>
                <el-select v-model="setQuery.claimType" size="small" class="item-width-100" placeholder="">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <div class="label">领取</div>
              <el-input
                  size="small"
                  type="number"
                  v-model.number="setQuery.claimNum"
                  :maxlength="10"
                  class="item-width-100"
              >
                <template slot="append">次</template>
              </el-input>
            </div>
          </el-form-item>
        <el-form-item label="选择品类：" prop="bindContent" v-if="setQuery.bindService ==3">
          <el-tree
            v-loading="loadingTree"
              :data="data"
              :props="{
                label: 'cateName',
                children: 'child'
              }"  
              ref="tree"
              node-key="id"
              show-checkbox
              @check-change="handleCheckChange">
          </el-tree>
        </el-form-item>

          <el-form-item label="权益内容：" prop="equityContent"  v-if="setQuery.bindService ==4">
          <el-table
            :data="setQuery.equityContent"
            tooltip-effect="dark"
            border
            style="width: 500px"
          >
          <el-table-column
              align="center"
              label="图标"
              prop="icon"
              show-overflow-tooltip
              width="150px"
            >
            <template slot-scope="scope">
              <img class="icon" :src="scope.row.icon" alt="">
            </template>
            </el-table-column>
        
            <el-table-column
              align="center"
              label="权益"
              prop="equityName"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column align="center" label="操作" width="100px">
              <template slot-scope="scope">
                <!-- <el-button type="text" size="small" @click="handleEdit(scope.row)"
                  > 编辑</el-button
                > -->
                <el-button type="text" size="small" @click="handleDel(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" size="small" @click="handleAdd">+添加</el-button>
          </el-form-item>

      </template>

     

    </el-form>

    <div class="btn-group">
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >确 定</el-button
      >
    </div>



    <el-dialog :title="title" width="550px" :visible.sync="dialogFormVisible1">

    <el-form label-width="130px" :model="form"
      ref="form"
      :rules="rules1">

       <el-form-item label="视频会员"  prop="pid">
         <el-select v-model="form.pid" size="small" class="item-width-300" placeholder="请选择">
            <el-option
              v-for="item in goodsData"
              :key="item.pid"
              :label="item.title"
              :value="item.pid">
              <img style="float: left; width:30px;height:30px;border-radius:50%;" :src="item.cover&&item.cover[0]" alt="">
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.title }}</span>
            </el-option>
          </el-select>
        </el-form-item>
       
    </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible1 = false">取 消</el-button>
    <el-button type="primary" :loading="btnLoading1" @click="save1">确 定</el-button>
  </div>
</el-dialog>



    <el-dialog title="选择优惠券" width="70%" :visible.sync="dialogTableVisible">
      
      <div class="search">
        <div>
            <el-input
            v-model="couponQuery.couponName"
            size="small"
            clearable
            placeholder="请输入优惠券名称"
            class="item-width-200 "
            ></el-input>
            
            <el-button
            class="ml10"
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleSearch"
        >
            搜索
        </el-button>
        </div>
    </div>
        <el-table
      :data="tableData"
      tooltip-effect="dark"
      border
      v-loading="loading2"
      style="width: 100%"
    >
      <el-table-column
        align="center"
        label="选择"
        prop="setMealCode"
        show-overflow-tooltip
      >
       <template slot-scope="scope">
         <el-radio v-model="setQuery.bindContent" :label="scope.row.id" @input="selectCoupon(scope.row.couponName)"></el-radio>
        </template>
      </el-table-column>
      <el-table-column
        prop="couponName"
        align="center"
        label="优惠券名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="surplusNum"
        align="center"
        label="剩余数量"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="useNum"
        align="center"
        label="已使用"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        align="center"
        label="创建时间"
        show-overflow-tooltip
      >
      </el-table-column>
    </el-table>
    <div class="page-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="couponQuery.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="couponQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    </el-dialog>


    <el-dialog title="选择抽奖" width="70%" :visible.sync="dialogTableVisible1">
      
      <div class="search">
        <div>
            <el-input
            v-model="query.raffleName"
            size="small"
            clearable
            placeholder="请输入活动名称"
            class="item-width-200 "
            ></el-input>
            
            <el-button
            class="ml10"
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleSearch1"
        >
            搜索
        </el-button>
        </div>
    </div>
        <el-table
      :data="tableData1"
      tooltip-effect="dark"
      border
      v-loading="loading2"
      style="width: 100%"
    >
      <el-table-column
        align="center"
        label="选择"
        prop="setMealCode"
        show-overflow-tooltip
      >
       <template slot-scope="scope">
         <el-radio v-model="setQuery.bindContent" :label="scope.row.id" @input="selectCoupon(scope.row.raffleName)"></el-radio>
        </template>
      </el-table-column>
      <el-table-column
        prop="raffleName"
        align="center"
        label="活动名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="surplusNum"
        align="center"
        label="活动时间"
        show-overflow-tooltip
      >
       <template slot-scope="scope">
        <div v-if="scope.row.raffleCycle == 1">
          {{scope.row.startTime}} 至 {{scope.row.endTime}}
        </div>
        <div v-else>
          {{scope.row.raffleCycleContent | filterDate}}
        </div>
        
        </template>
      </el-table-column>
      <el-table-column
        prop="useNum"
        align="center"
        label="展示状态"
        show-overflow-tooltip
      >
      <template slot-scope="scope">
        {{scope.row.raffleState == 1 ? '展示' : '不展示'}}
      </template>
      </el-table-column>
      
    </el-table>
    <div class="page-box">
      <el-pagination
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        background
        :current-page="query.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="couponQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    </el-dialog>


  </div>
</template>

<script>
import {getLuckyDrawList} from '@/api/luckyDraw.js'
import { editEquity,getEquity } from "@/api/equity";
import { getCouponList } from "@/api/coupon";
import {getData,getGoodsList} from '@/api/goods'
import Upload from "@/components/Upload";

export default {
    components: {
        Upload,
    },
  data() {
    return {
      couponName:'',
      loading: false,
      loading1: false,
      loading2: false,
      loadingTree: false,
      btnLoading1: false,
      dialogTableVisible: false,
      dialogTableVisible1: false,
      dialogFormVisible1: false,
      query: {
        enable:1,
        raffleName:'',
        "status":'',
        "state":'',
        "currentPage": 1,
        "pageSize": 10,
      },
      tableData: [],
      tableData1: [],
      title: "",
      total: 0,
      data:[],
        typeOptions:[
        {
          label:'每月',
          value:1
        },
        {
          label:'最多',
          value:2
        }
      ],
      form:{
        pid:'',
      },
      setQuery: {
        claimType: 1,
        claimNum:1,
        givenNum:1,
        getFlag:1,
        "setMealCode":'',
        "bindContent": "",
        "bindService": 2,
        equityContent:[],
        "equityDetail": "",
        "equityImg": "",
        "equityName": "",
        "equityType": 0,
        "givenNum": 1,
        "showType": 1,
        "status": 1
      },
      couponQuery: {
         couponName:'',
        startTime:'',
        endTime:'',
        couponType: '',
        status:'2',
        currentPage: 1,
        pageSize: 10,
      },
      goodsData:[],
      rules1:{
          pid: [
          { required: true, message: "请选择", trigger: "change" },
        ],
         equityName: [
          { required: true, message: "请输入权益", trigger: "blur" },
        ],
      }
    };
  },
  computed: {
    rules() {
      if(this.setQuery.equityType == 2){
        if(this.setQuery.bindService == 4){
           return  {
              equityName: [
                { required: true, message: "请输入权益名称", trigger: "blur" },
              ],
              equityImg: [
                { required: true, message: "请上传权益图片", trigger: "change" },
              ],
              equityDetail: [
                { required: true, message: "请输入权益描述", trigger: "blur" },
              ],
              equityMsg: [
                { required: true, message: "请输入权益说明", trigger: "blur" },
              ],
              equityContent: [
                { required: true, message: "请选择", trigger: "change" },
              ],
              claimNum: [
                { required: true, message: "请选择", trigger: "blur" },
                { type:'number',min:1, message: "最小数量为1", trigger: "blur" },
              ],
            }
          }else{
              
              return  {
              equityName: [
                { required: true, message: "请输入权益名称", trigger: "blur" },
              ],
              equityImg: [
                { required: true, message: "请上传权益图片", trigger: "change" },
              ],
              equityDetail: [
                { required: true, message: "请输入权益描述", trigger: "blur" },
              ],
              equityMsg: [
                { required: true, message: "请输入权益说明", trigger: "blur" },
              ],
              bindContent: [
                { required: true, message: "请选择", trigger: "change" },
              ],
              claimNum: [
                { required: true, message: "请选择", trigger: "blur" },
                { type:'number',min:1, message: "最小数量为1", trigger: "blur" },
              ],
              givenNum: [
                { required: true, message: "请选择", trigger: "blur" },
                { type:'number',min:1, message: "最小数量为1", trigger: "blur" },
              ],
            }
          }

      }else{
          return  {
        equityName: [
          { required: true, message: "请输入权益名称", trigger: "blur" },
        ],
        equityImg: [
          { required: true, message: "请上传权益图片", trigger: "change" },
        ],
        equityDetail: [
          { required: true, message: "请输入权益描述", trigger: "blur" },
        ],
      }
      }
    }
  },
  filters: {
    filterDate: function(value) {
      let arr = ['','周一','周二','周三','周四','周五','周六','周日']
      let str = ''
      let list = value.split(',')
      list.map(item=>{
        str = str + arr[item] +'、'
      })
      return str;
    }
  },
  watch: {
    'setQuery.bindService'(val) {
      if(val==3&&!this.data.length){
        this.getData()
      }
    }
  },
  methods: {
    handleAdd(){
      this.title = '添加'
      this.form = {
        icon:'',
        equityName:''
      }
      this.dialogFormVisible1 = true
    },
    handleEdit(row){
      this.title = '编辑'
      this.form = {
        id:row.id,
        icon:row.icon,
        equityName:row.equityName,
      }
      this.dialogFormVisible1 = true

    },
    handleDel(index){
      this.setQuery.equityContent.splice(index,1)
    },
    handleSearch(){
      this.couponQuery.currentPage = 1
      this.getCouponList();
    },
    handleSearch1(){
      this.query.currentPage = 1
      this.getLuckyDrawList();
    },
    selectCoupon(name){
      this.couponName = name
    },
    changeService(){
      this.setQuery.bindContent = ''
    },
    // 选择优惠券
    handleChoose(type){
      if(type==1){
        this.dialogTableVisible = true
        this.couponQuery.currentPage = 1
        this.getCouponList()
      }else{
        this.dialogTableVisible1 = true
        this.query.currentPage = 1
        this.getLuckyDrawList()
      }
    },
    handleCheckChange(val,ischecked){
      if(ischecked){
        this.$nextTick(()=>{
          this.$refs.setQuery.clearValidate('bindContent')
        })
      }
    },
    handleSizeChange(val) {
      this.couponQuery.currentPage = 1;
      this.couponQuery.pageSize = val;
      this.getCouponList()
    },
    handleCurrentChange(val) {
      this.couponQuery.currentPage = val;
      this.getCouponList()
    },
    handleSizeChange1(val) {
      this.query.currentPage = 1;
      this.query.pageSize = val;
      this.getLuckyDrawList()
    },
    handleCurrentChange1(val) {
      this.query.currentPage = val;
      this.getLuckyDrawList()
    },
    uploadEnd(val) {
      this.setQuery[val.type] = val.url;
    },
    uploadEnd1(val){
      this.form[val.type] = val.url;

    },
    save() {
      
      if(this.setQuery.bindService==3){
        this.setQuery.bindContent = this.$refs.tree.getCheckedKeys().join()
      }
        let setQuery = JSON.parse(JSON.stringify(this.setQuery))

      if(setQuery.bindService==4){
        setQuery.equityContent = JSON.stringify(setQuery.equityContent) 
      }else{
        setQuery.equityContent = ''
      }
      this.$refs.setQuery.validate((v) => {
    if (v) {
          this.loading = true;
          editEquity(setQuery).then((res) => {
            this.loading = false;
            if (res.state == "Success") {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
              });
               this.$router.push({
                path:"/operationManage/equitiesManage/index",
                query:{
                  id:this.setQuery.setMealCode
                }
              });
            }
          });
        }
      });
    },

    save1(){
        this.$refs.form.validate((v) => {
        if (v) {
          if(this.title == '编辑'){
            let index = this.setQuery.equityContent.findIndex(item => item.id == this.form.id)
            this.$set(this.setQuery.equityContent[index],'id',this.form.id)
            this.$set(this.setQuery.equityContent[index],'icon',this.form.icon)
            this.$set(this.setQuery.equityContent[index],'equityName',this.form.equityName)
            
            this.dialogFormVisible1 = false
          }else{
            this.goodsData.map(item=>{
              if(item.pid == this.form.pid){
                 this.setQuery.equityContent.push({
                  icon:item.cover&&item.cover.length?item.cover[0]:'',
                  equityName:item.title,
                  serviceId:item.pid
                 })
              }
            })

            // this.setQuery.equityContent.push(this.form)
            this.dialogFormVisible1 = false
          }
        }
      });
    },
    getDetail(){
       this.loading1 = true
      getEquity({equityId:this.$route.query.id,regionCode:'520100'}).then((res) => {
        this.loading1 = false
        if (res.state == "Success") {
            this.setQuery = res.content
            this.setQuery.bindContent = Number(this.setQuery.bindContent)
            if(this.setQuery.bindService == 3){
              this.$nextTick(()=>{

                this.$refs.tree.setCheckedKeys(this.setQuery.bindContent.split(','))
              })
            }else if(this.setQuery.bindService == 4){
              this.setQuery.equityContent = JSON.parse(this.setQuery.equityContent)

            }else{
              this.couponName = this.setQuery.couponName
            }
         
        }
      });
    },
    getCouponList(){
      this.couponQuery.couponType = this.setQuery.bindService == 1?1:3
      this.loading2 = true
      getCouponList(this.couponQuery).then((res) => {
          this.loading2 = false;
          if (res.state == "Success") {
            this.tableData = res.content.records;
            this.total = res.content.total;
          }
        });
    },
    getData(){
      this.loadingTree=true
      getData().then(res=>{
          this.loadingTree=false
          if (res.state == "Success") {
            this.data = res.content
          }
      })
    },
    // 获取视频会员商品
    getGoodsList(){
      getGoodsList({
          title:'',
					productType:['Recharge'],
          regionCode:'520100',
					page:0,
					size:99}).then(res=>{
        if(res.state == 'Success'){
          this.goodsData = res.content.content
        }
      })
    },
    // 抽奖列表
    getLuckyDrawList(){
      this.loading = true
      getLuckyDrawList(this.query).then(res=>{
        this.loading = false
        if(res.state == 'Success'){
          this.tableData1 = res.content.records
          this.total = res.content.total
        }
      })
    }
  },
  created () {
    this.getGoodsList()
    this.setQuery.equityType = this.$route.query.equityType
    this.setQuery.setMealCode = this.$route.query.setMealCode
    if(this.$route.query.id){
      this.getDetail()
    }
  },
};
</script>

<style lang="scss" scoped>
.addEquities {
  padding-bottom: 40px;
  .icon{
    width: 40px;
    height: 40px;
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .item{
    display: flex;
    align-items: center;
    .label{
      color: #606266;
      font-size: 14px;
      padding: 0 10px;
    }

  }
}
</style>