
<template>
  <div class="fullDiscountCoupon app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      label-width="130px"
      :disabled="mode == 'detail'"
      v-loading="pageLoading"
    >
      <el-form-item label="优惠券名称：" prop="couponName">
        <el-input
          v-model="setQuery.couponName"
          size="small"
          class="item-width-300"
          :maxlength="20"
        ></el-input>
      </el-form-item>

      <el-form-item label="优惠券内容：" required>
        <div class="flex">
          <div class="flex">
            <el-radio v-model="radio1" label="1">满</el-radio>
            <el-form-item prop="couponCondition">
              <el-input
                v-model="setQuery.couponCondition"
                size="small"
                class="item-width-200"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="label">，减</div>
          <div class="flex">
            <el-form-item prop="couponDiscount">
              <el-input
                v-model="setQuery.couponDiscount"
                size="small"
                class="item-width-200"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="flex" :span="24">
          <el-radio v-model="radio1" label="2">无门槛，立减</el-radio>
          <el-form-item prop="couponDiscount">
            <el-input
              v-model="setQuery.couponDiscount"
              size="small"
              class="item-width-200"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item label="使用日期：" prop="contactName">
        <div class="flex">
          <el-radio v-model="radio2" label="1">{{ "" }}</el-radio>
          <el-form-item prop="useStartTime">
            <el-date-picker
              v-model="date"
              size="small"
              type="datetimerange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </div>
        <div class="flex">
          <el-radio v-model="radio2" label="2">领券后</el-radio>
          <el-select
            v-model="setQuery.claimCalmDay"
            size="small"
            class="item-width-200"
            placeholder="请选择"
          >
            <el-option label="立即生效" :value="0"> </el-option>
            <el-option
              :disabled="disabled"
              :label="setQuery.claimCalmDay + '天生效'"
              :value="setQuery.claimCalmDay"
            >
              <el-input
                v-model.number="setQuery.claimCalmDay"
                type="number"
                size="small"
                class="item-width-150"
                @blur.stop="disabled = false"
                @focus.stop="disabled = true"
              >
                <template slot="append">天</template>
              </el-input>
              生效
            </el-option>
          </el-select>
          <div class="label">有效期</div>

          <el-form-item prop="claimValidDay">
            <el-input
              v-model.number="setQuery.claimValidDay"
              size="small"
              type="number"
              class="item-width-150"
            >
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
        </div>
        <div class="notice">
          例：用户在 1月1日9:00 领券，则该券的可用时间为 6月23日00:00:00 至
          6月23日23:59:59（按自然天计算）
        </div>
      </el-form-item>
      <el-form-item label="发放数量：" prop="limitNum">
        <el-input
          v-model.number="setQuery.limitNum"
          type="number"
          size="small"
          class="item-width-300"
        >
          <template slot="append">张</template>
        </el-input>
      </el-form-item>

      <el-form-item label="使用说明：" prop="usrDetail">
        <el-input
          v-model="setQuery.usrDetail"
          class="item-width-300"
          type="textarea"
          :maxlength="100"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="适用商品：" prop="usrDetail">
        <el-radio v-model="radio5" label="1">全部商品</el-radio>
        <el-radio v-model="radio5" label="2">指定商品</el-radio>
        <div class="box" style="width: 600px" v-if="radio5 == 2">
          <div class="tab-box">
            <el-button size="small" @click="handleChoose">选择商品</el-button>
            <el-button size="small" @click="tableData1 = []">全部删除</el-button>
          </div>

          <el-table
            :data="list"
            tooltip-effect="dark"
            border
            v-loading="loading1"
            style="width: 100%"
          >
            <el-table-column
            align="center"
            label="商品图"
            prop="couponName"
            show-overflow-tooltip
            >
            <template slot-scope="scope">
                <img class="icon" :src="scope.row.goodsImg" alt="" />
            </template>
            </el-table-column>

            <el-table-column
            prop="goodsName"
            align="center"
            label="商品名称"
            show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="address"
              width="180px"
              fixed="right"
              align="center"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleDel(scope.row.goodsId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="page-box">
            <el-pagination
              @current-change="handleCurrentChange1"
              background
              :current-page="chooseQuery.currentPage"
              :page-sizes="[10]"
              :page-size="chooseQuery.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData1.length"
            >
            </el-pagination>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="领取限制：" required>
        <el-radio v-model="radio3" label="1">不限制</el-radio>
        <el-radio v-model="radio3" label="2">限制</el-radio>
          <el-form-item v-if="radio3 == 2" prop="claimNum">
          <el-input
            v-model.number="setQuery.claimNum"
            type="number"
            size="small"
            class="item-width-300"
          >
            <template slot="append">次</template>
          </el-input>
       </el-form-item>
      </el-form-item>
      <el-form-item label="领取用户限制：" required>
        <el-radio v-model="radio4" label="1">不限制</el-radio>
        <el-radio v-model="radio4" label="2">限制分类用户领取</el-radio>
          <el-form-item v-if="radio4 == 2" prop="claimUser">
          <el-checkbox-group v-model="setQuery.claimUser">
            <el-checkbox label="99">非会员</el-checkbox>
            <el-checkbox
              :label="item.value"
              v-for="item in comboList"
              :key="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
      </el-form-item>

      </el-form-item>
      <el-form-item label="展示位置：" prop="showType">
        <el-checkbox-group v-model="setQuery.showType">
          <el-checkbox label="1">领取中心</el-checkbox>
          <el-checkbox label="2">店铺首页</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

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

    <el-dialog title="指定商品" top="30px" width="900px" :visible.sync="dialogTableVisible">
      <div class="search">
        <div>

            <el-input
            v-model="query.goodsName"
            size="small"
            placeholder="请输入商品名称"
            class="item-width-200"
            ></el-input>
            <el-select
            v-model="query.goodsType"
            size="small"
            clearable
            class="item-width-200 ml10"
            placeholder="请选择类型"
            >
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
            <el-select
            v-model="query.shopId"
            size="small"
            class="item-width-200 ml10"
            placeholder="请搜索并选择店铺"
            :remote-method="getShopList"
            :loading="shopLoading"
            clearable
            filterable
            remote
            >
            <el-option
                v-for="item in shopOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
            <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="loading1"
        style="width: 100%"
        ref="multipleTable"
         @selection-change="handleSelectionChange"
      >
       <el-table-column
        type="selection"
        width="40">
        </el-table-column>
        <el-table-column
          align="center"
          label="商品图"
          prop="couponName"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <img class="icon" :src="scope.row.goodsImg" alt="" />
          </template>
        </el-table-column>

        <el-table-column
          prop="goodsName"
          align="center"
          label="商品名称"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="goodsName"
          align="center"
          label="商品分类"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ goodsTypeObj[scope.row.goodsType] || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="shopName"
          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="query.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- <div class="btn-group">
      <el-button @click="dialogTableVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveChoose"
        >确 定</el-button
      >
    </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { getSetMealNameAndId } from "@/api/common";
import { saveOrUpdate, detail,getGoodsInfoByCoupon } from "@/api/coupon";
import { goodsList } from "@/api/goods";
import { getList } from "@/api/shop";
import { debounce } from "@/utils/index";

export default {
  data() {
    var validateLimit = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入发放数量"));
      } else if (value > 100000000 || value < 1) {
        callback(new Error("应在1~100000000之间"));
      } else {
        callback();
      }
    };
    return {
      mode: "add",
      radio: 1,
      radio1: "1",
      radio2: "1",
      radio3: "1",
      radio4: "1",
      radio5: "1",
      setQuery: {
        claimCalmDay: 1,
        claimNum: 0,
        claimUser: [],
        claimValidDay: 0,
        couponCondition: 0,
        couponDiscount: 0,
        couponName: "",
        couponType: 1,
        id: 0,
        limitNum: 0,
        maxDiscount: 0,
        shopId: "",
        showType: [],
        useEndTime: "",
        useGoodsRang: "",
        useStartTime: "",
        usrDetail: "",
      },
      date: [],
      disabled: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
        },
      },
      rules: {
        couponName: [
          { required: true, message: "请输入优惠券名称", trigger: "blur" },
        ],
        couponDiscount: [{ validator: this.validateMoney, trigger: "blur" }],
        limitNum: [{ required:true,validator: validateLimit, trigger: "blur" }],
        claimNum:[
            { required: true, message: '请输入领取次数', trigger: 'blur' },
             { type:'number',min: 1, max: 100, message: '领取限制：1~100次', trigger: 'blur' }
          ]
      },
      comboList: [],
      loading: false,
      tableData: [],
      tableData1: [],
      chooseList: [],
      chooseQuery:{
        currentPage:1,
        pageSize: 10,

      },
      loading1: false,
      pageLoading: false,
      shopLoading: false,
      dialogTableVisible: false,
      goodsTypeObj: JSON.parse(sessionStorage.getItem("goodsTypeObj")),
      typeOptions:[],
      shopOptions:[],
      query: {
        applyState: "",
        status: "3",
        shopId: "",
        goodsName: "",
        currentPage: 1,
        pageSize: 10,
      },
      total: 0,
    };
  },
  watch: {
    date(val) {
      if (val == null) {
        this.setQuery.useStartTime = "";
        this.setQuery.useEndTime = "";
      } else {
        this.setQuery.useStartTime = val[0];
        this.setQuery.useEndTime = val[1];
      }
    },
    radio1: {
      handler: function (val) {
        if (val == 1) {
          this.$set(this.rules, "couponCondition", [
            { validator: this.validateMoney, trigger: "blur" },
          ]);
        } else {
          delete this.rules.couponCondition;
          this.$refs.setQuery.clearValidate("couponCondition");
        }
      },
      deep: true,
      immediate: true,
    },
    radio2: {
      handler: function (val) {
        if (val == 1) {
          this.$set(this.rules, "useStartTime", [
            { required: true, message: "请选择使用时间", trigger: "change" },
          ]);
          delete this.rules.claimCalmDay;
          delete this.rules.claimValidDay;
        } else {
          delete this.rules.useStartTime;
          this.$refs.setQuery.clearValidate("useStartTime");
          this.$set(this.rules, "claimCalmDay", [
            { required: true, message: "请输入生效时间", trigger: "blur" },
            { validator: this.validateNum, trigger: "blur" },
          ]);
          this.$set(this.rules, "claimValidDay", [
            { required: true, message: "请输入有效天数", trigger: "blur" },
            { validator: this.validateNum, trigger: "blur" },
          ]);
        }
      },
      deep: true,
      immediate: true,
    },
    // radio3:{
    //   handler: function (val) {
    //     if(val == 1){
    //         delete this.rules.claimNum

    //     }else{
    //         this.rules.claimNum = [
    //           { validator: validateNum, trigger: 'blur' }
    //         ]
    //     }
    //    },
    //   deep: true,
    //   immediate: true
    // },
    radio4: {
      handler: function (val) {
        if (val == 1) {
          delete this.rules.claimUser;
        } else {
          this.rules.claimUser = [
            {
              required: true,
              message: "请选择领取用户限制",
              trigger: "change",
            },
          ];
        }
      },
      deep: true,
      immediate: true,
    },
    radio5(val){
      if(val == 1){
        this.setQuery.useGoodsRang = ''
      }
    }
  },
  computed: {
    list() {
        return this.tableData1.slice((this.chooseQuery.currentPage-1)*this.chooseQuery.pageSize,this.chooseQuery.currentPage*this.chooseQuery.pageSize)
    }
  },
  methods: {
    handleDel(id){
        this.tableData1.map((item,index)=>{
            if(item.goodsId == id){
                return this.tableData1.splice(index,1)
            }
        })
    },
    // 勾选变化
    handleSelectionChange(val){
      this.chooseList = val
         this.tableData1 = this.tableData1.concat(JSON.parse(JSON.stringify(this.chooseList)) ) 
         this.tableData1 = Array.from(new Set(this.tableData1.map(JSON.stringify))).map(JSON.parse)
        console.log(this.tableData1.map(item=>item.goodsId));
        this.chooseList = []
    },
    saveChoose(){
        this.dialogTableVisible = false
       
    },
    handleChoose(){
        this.dialogTableVisible = true
        this.handleSearch()
    },
    handleSearch(){
      this.query.currentPage = 1;
      this.getGoodsList();
    },
    handleSizeChange(val) {
      this.query.currentPage = 1;
      this.query.pageSize = val;
      this.getGoodsList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getGoodsList();
    },
    // 静态表格手动分页
    handleCurrentChange1(val) {
      this.chooseQuery.currentPage = val;
    },
    getGoodsList() {
      this.loading1 = true;
      goodsList(this.query).then((res) => {
        this.loading1 = false;
        if (res.state == "Success") {
          this.tableData = res.content.records;
          this.total = res.content.total;
        }
      });
    },
    validateNum(rule, value, callback) {
      if (value > 200 || value < 1) {
        callback(new Error("应在1~200之间"));
      } else {
        callback();
      }
    },
    validateMoney(rule, value, callback) {
      if (Number(value).toString() == "NaN") {
        callback(new Error("请输入数字"));
      } else if (value > 100000 || value < 0.01) {
        callback(new Error("金额应在0.01~100000.00之间"));
      } else {
        callback();
      }
    },
    // 获取套餐列表
    getSetMealNameAndId() {
      getSetMealNameAndId().then((res) => {
        if (res.state == "Success") {
          for (const key in res.content) {
            if (res.content.hasOwnProperty.call(res.content, key)) {
              this.comboList.push({
                label: res.content[key],
                value: key,
              });
            }
          }
        }
      });
    },
    // 获取店铺列表
    getShopList:debounce(function(val) {
        if(val){
            getList({shopNameOrPhoneNum: val,
              currentPage: 1,
              pageSize: 20}).then((res) => {
              this.shopLoading = false;
              if (res.state == "Success") {
                 this.shopOptions = []
                res.content.records.map(item=>{
                    this.shopOptions.push({
                        label:item.shopName,
                        value:item.shopId
                    })
                })
              }
            });
        }else{
            this.shopOptions = []
        }
    }),
    getGoodsInfoByCoupon(id){
      getGoodsInfoByCoupon({id,currentPage:1,pageSize:999}).then(res=>{
          if (res.state == "Success") {
            this.tableData1 = res.content.records
          }
      })
    },
    getDetail(id) {
      this.pageLoading = true;
      detail({ id }).then((res) => {
        this.pageLoading = false;
        if (res.state == "Success") {
          let obj = JSON.parse(JSON.stringify(res.content));
          if (obj.showType == 3) {
            obj.showType = ["1", "2"];
          } else if (obj.showType) {
            obj.showType = [obj.showType.toString()];
          } else {
            obj.showType = [];
          }

          if (obj.couponCondition) {
            this.radio1 = "1";
          } else {
            this.radio1 = "2";
          }
          obj.claimCalmDay = obj.claimCalmDay || 1;
          obj.claimValidDay = obj.claimValidDay || 0;
          if (obj.claimValidDay > 0) {
            this.radio2 = "2";
          } else if (obj.useStartTime && obj.useEndTime) {
            this.radio2 = "1";
            this.date = [obj.useStartTime, obj.useEndTime];
          }

          if (obj.claimNum == 0) {
            this.radio3 = "1";
          } else {
            this.radio3 = "2";
          }

          if (obj.claimUser == 0) {
            this.radio4 = "1";
            obj.claimUser = [];
          } else {
            this.radio4 = "2";
            obj.claimUser = obj.claimUser.split(",");
          }

          if(obj.useGoodsRang){
            this.radio5 = '2'
            this.getGoodsInfoByCoupon(id)
          }else{
            this.radio5 = '1'
          }

          this.setQuery = obj;
        }
      });
    },
    save() {
      this.$refs.setQuery.validate((v) => {
        if (v) {
          let query = JSON.parse(JSON.stringify(this.setQuery));
          if (this.radio2 == 1) {
            delete query.claimCalmDay;
            delete query.claimValidDay;
          } else {
            delete query.useStartTime;
            delete query.useEndTime;
          }
          if (this.radio3 == 1) {
            query.claimNum = 0;
          }
          if (this.radio4 == 1) {
            query.claimUser = 0;
          } else {
            query.claimUser = query.claimUser.join();
          }
          if (query.showType.length == 2) {
            query.showType = 3;
          } else if (query.showType.length == 1) {
            query.showType = query.showType[0];
          } else if (!query.showType.length) {
            delete query.showType;
          }

           if (this.radio5 == 2) {
           query.useGoodsRang = this.tableData1.map(item=>item.goodsId).toString()
          }else{
           query.useGoodsRang = ''

          }

          if (!query.id) {
            delete query.id;
          }
          this.loading = true;
          saveOrUpdate(query).then((res) => {
            this.loading = false;
            if (res.state == "Success") {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
              });

              this.$router.push("/operationManage/couponManage/index");
            }
          });
        }
      });
    },
  },
  created() {
    this.mode = this.$route.query.mode || "add";
    if (this.$route.query.id) {
      this.getDetail(this.$route.query.id);
    }
    this.getSetMealNameAndId();
    for (const key in this.goodsTypeObj) {
        if (Object.hasOwnProperty.call(this.goodsTypeObj, key)) {
            this.typeOptions.push({
                label:this.goodsTypeObj[key],
                value:key
            })
            
        }
    }
  },
};
</script>

<style lang="scss" scoped>
.fullDiscountCoupon {
    .icon{
        width: 50px;
        height: 50px;
    }
  .label {
    font-size: 14px;
    color: #606266;
    height: 32px;
    align-self: flex-start;
    padding: 0 10px;
  }
  .flex {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .notice {
    font-size: 12px;
    color: #aaa;
    margin-top: 10px;
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>