<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-group>
        </el-form-item>
        <template v-if="setQuery.bindService !=3">
          <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">{{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>
          <el-form-item label="赠送数量：" prop="claimNum">
            <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>
          
        </template>
        <el-form-item label="选择品类：" prop="bindContent" v-else>
          <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>
      </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="选择优惠券" 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>


  </div>
</template>

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

export default {
    components: {
        Upload,
    },
  data() {
    return {
      couponName:'',
      loading: false,
      loading1: false,
      loading2: false,
      loadingTree: false,
      dialogTableVisible: false,
      tableData: [],
      title: "",
      total: 0,
      data:[
        // {
        //   label: '一级 1',
        //   children: [{
        //     label: '二级 1-1',
        //     children: [{
        //       label: '三级 1-1-1'
        //     }]
        //   }]
        // }, {
        //   label: '一级 2',
        //   children: [{
        //     label: '二级 2-1',
        //     children: [{
        //       label: '三级 2-1-1'
        //     }]
        //   }, {
        //     label: '二级 2-2',
        //     children: [{
        //       label: '三级 2-2-1'
        //     }]
        //   }]
        // }
        ],
        typeOptions:[
        {
          label:'每月',
          value:1
        },
        {
          label:'最多',
          value:2
        }
      ],
      setQuery: {
        claimType: 1,
        claimNum:1,
        getFlag:1,
        "setMealCode":'',
        "bindContent": "",
        "bindService": 2,
        "equityDetail": "",
        "equityImg": "",
        "equityName": "",
        "equityType": 0,
        "givenNum": 1,
        "showType": 1,
        "status": 1
      },
      couponQuery: {
         couponName:'',
        startTime:'',
        endTime:'',
        couponType: '',
        status:'2',
        currentPage: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    rules() {
      if(this.setQuery.equityType == 2){

        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" },
        ],
      }
      }else{
          return  {
        equityName: [
          { required: true, message: "请输入权益名称", trigger: "blur" },
        ],
        equityImg: [
          { required: true, message: "请上传权益图片", trigger: "change" },
        ],
        equityDetail: [
          { required: true, message: "请输入权益描述", trigger: "blur" },
        ],
      }
      }
    }
  },
  watch: {
    'setQuery.bindService'(val) {
      if(val==3&&!this.data.length){
        this.getData()
      }
    }
  },
  methods: {
    handleSearch(){
      this.couponQuery.currentPage = 1
      this.getCouponList();
    },
    selectCoupon(name){
      this.couponName = name
    },
    changeService(){
      this.setQuery.bindContent = ''
    },
    // 选择优惠券
    handleChoose(){
      this.dialogTableVisible = true
      this.couponQuery.currentPage = 1
      this.getCouponList()
    },
    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()
    },
    uploadEnd(val) {
      this.setQuery[val.type] = val.url;
    },
    save() {
      let setQuery = JSON.parse(JSON.stringify(this.setQuery))
      
      if(this.setQuery.bindService==3){
        this.setQuery.bindContent = this.$refs.tree.getCheckedKeys().join()
      }
      this.$refs.setQuery.validate((v) => {
    if (v) {
          this.loading = true;
          editEquity(this.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
                }
              });
            }
          });
        }
      });
    },
    getDetail(){
       this.loading1 = true
      getEquity({equityId:this.$route.query.id}).then((res) => {
        this.loading1 = false
        if (res.state == "Success") {
            this.setQuery = res.content
            if(this.setQuery.bindService == 3){
              this.$nextTick(()=>{

                this.$refs.tree.setCheckedKeys(this.setQuery.bindContent.split(','))
              })
            }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
          }
      })
    }
  },
  created () {
    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;
  .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>