<template>
  <div class="addGoods app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      v-loading="loading"
      label-width="150px"
    >
      <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"
            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">需真实展示店内环境情况 查看示例图</div>
          <div class="notice">
            (图片支持jpg, png, bmp格式，建议上传100kb~500kb大小文件)
          </div>
          <Upload
            type="studyItem"
            id="studyItem"
            width="300px"
            height="200px"
            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>
      </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="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>

    </el-form>

    <div class="btn-group" v-if="mode != 'detail'">
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import {
  allCouponByShop,
  get,
  getGoodsCoupon,
  search,
  goodsCouponSet,
  addOrUpdate
} from "@/api/goods";
import { getSetMealNameAndId } from "@/api/common";
import { getData } from "@/api/study";
import {getRuleList } from "@/api/rule";

import Upload from "@/components/Upload";
export default {
  components: {
    Upload,
  },
  data() {
    return {
      mode: "add",
      that: this,
      nums: 7,
      value2: "",
      tabs: ["不限制", "自定义时间", "每周", "每月"],
      tab: 0,
      date: "",
      date1: "",
      loading: false,
      tableLoading: false,
      tableData: [],
      imgList: [],
      ruleOptions:[],
      query: {
        shopId: localStorage.getItem("epid"),
        currentPage: 1,
        pageSize: 10,
      },
      total: 0,
      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,
      },
      rules: {
        condition: [
          { required: true, message: "请输入满足条件", trigger: "blur" },
        ],
        discount: [
          { required: true, message: "请输入	优惠值", trigger: "blur" },
        ],
        goodsCode: [
          { required: true, message: "请选择优惠券类型", trigger: "change" },
        ],
        // goodsDescribe: [{ required: true, message: "请输入", trigger: "blur" }],
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goodsType: [
          { required: true, message: "请选择商品类型", trigger: "change" },
        ],
        realPrice: [{ required: true, message: "请输入售价", trigger: "blur" }],
        stockCount: [
          { required: true, message: "请输入库存", trigger: "blur" },
        ],
        shareId: [{ required: true, message: "请选择分账规则", trigger: "change" }],
        // goodsType: [{ required: true, message: "请选择商品类型", trigger: "change" }],
        // goodsType: [{ required: true, message: "请选择商品类型", trigger: "change" }],
        // goodsType: [{ required: true, message: "请选择商品类型", trigger: "change" }],
      },
      options: [
        {
          value: "1",
          label: "优惠券",
        },
        {
          value: "6",
          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: {
    // 获取研学栏目
    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() {
      this.$refs.setQuery.validate((v) => {
        if (v) {
          this.setQuery.goodsId = this.$route.query.id
          addOrUpdate(this.setQuery).then((res) => {
            this.loading = false;
            if (res.state == "Success") {
              this.goodsCouponSet();
            }
          })
        }
      });
    },
    // 获取兑换码库存
    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;
          // 初始化购买设置
          if (!this.setQuery.details) {
            this.setQuery.details = [];
            this.mealOption.map((item) => {
              this.setQuery.details.push({
                buyNum: 0,
                buyPrice: this.setQuery.realPrice,
                buySet: 2,
                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,
                });
              }
            }
            resolve();
          }
        });
      });
    },
    // 商品购买配置
    goodsCouponSet() {
      this.loading = true;
      goodsCouponSet({
        goodsCouponSets: this.setQuery.details,
        goodsId: this.$route.query.id,
        shopId: this.$route.query.shopId,
      }).then((res) => {
        this.loading = true;
        if (res.state == "Success") {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });
          this.$router.push("/operationManage/goodsManage/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 lang="scss" scoped>
@import "@/styles/element-variables";
.addGoods {
  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>