<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :rules="rules" label-width="160px">
      <el-form-item label="所属商家" prop="businessId">
        <el-select v-model="form.businessId" filterable :disabled="$route.query.type == 'show'" placeholder="请选择所属商家" clearable style="width: 100%" @change="businessIdChange">
          <el-option v-for="(v, i) in shopList" :key="i" :label="v.businessName" :value="v.businessId" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="businessProductCategoryId">
        <el-select v-model="form.businessProductCategoryId" :disabled="$route.query.type == 'show'" placeholder="请选择商品分类" clearable style="width: 100%">
          <el-option v-for="(v, i) in shopTypeList" :key="i" :label="v.categoryName" :value="v.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入商品名称" :disabled="$route.query.type == 'show'" maxlength="50" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label=" 商品图片" prop="coverImage">
        <imageUpload v-model="form.coverImage" unique="coverImage" :disabled="$route.query.type == 'show'" :limit="1" />
      </el-form-item>
      <el-form-item label="排序" prop="sortNum">
        <el-input-number v-model="form.sortNum" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="0"></el-input-number>
      </el-form-item>
      <h3>销售信息</h3>
      <el-form-item label="销售价" prop="sellingPrice">
        <el-input-number v-model="form.sellingPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :max="Number(form.originalPrice)||Infinity" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="原价" prop="originalPrice">
        <el-input-number v-model="form.originalPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="Number(form.sellingPrice)||0" :precision="2"></el-input-number>
        <span class="showTip">
          是否显示价格
          <el-switch v-model="form.originalPriceShow" :disabled="$route.query.type == 'show'">
          </el-switch>
        </span>
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input-number v-model="form.costPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="限售数量" prop="limitQuantity">
        <el-input-number v-model="form.limitQuantity" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="0"></el-input-number>
        <div class="hint">*用户单次可下单的数量，0不限制</div>
      </el-form-item>
      <el-form-item label="供货价格" prop="supplyPrice">
        <el-input-number v-model="form.supplyPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>
        <div class="hint">*商家供应价格</div>
      </el-form-item>
      <el-form-item label="库存" prop="stock" v-if="form.codeType!=1">
        <el-input-number v-model="form.stock" :disabled="$route.query.type == 'show'" controls-position="right" :min="0"></el-input-number>
        <div class="hint">
          *配置库存
          <span style="display: inline-block; margin-left: 20px">可售库存：10 （库存 - 已售库存 = 可售库存）</span>
        </div>
      </el-form-item>

      <el-form-item label="有效期" prop="expirationType">
        <el-radio-group v-model="form.expirationType" :disabled="$route.query.type == 'show'">
          <el-radio :label="1">购买后有效天数</el-radio>
          <el-radio :label="2">指定有效时间</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="effectiveDay" v-if="form.expirationType==1">
        <el-input-number v-model="form.effectiveDay" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="0"></el-input-number>
      </el-form-item>
      <el-form-item label="" prop="effectiveDate" v-if="form.expirationType==2">
        <el-date-picker v-model="form.effectiveDate" :disabled="$route.query.type == 'show'" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <div class="flex-bet">
        <h3>购买须知</h3>
        <div>
          <el-button type="primary" size="mini" @click="addItem" v-if="$route.query.type != 'show'">新增</el-button>
        </div>
      </div>
      <el-form-item label="" prop="businessName">
        <draggable :disabled="$route.query.type == 'show'" v-model="form.businessProductNotesList" :options="{ group: 'typeLabel' }">
          <div class="flex" v-for="(v, i) in form.businessProductNotesList" :key="i">
            <el-input v-model="v.noteTitle" :disabled="$route.query.type == 'show'" placeholder="请输入标题" clearable />
            <el-input style="margin-left: 20px" type="textarea" :disabled="$route.query.type == 'show'" :rows="2" placeholder="请输入描述" v-model="v.noteContent">
            </el-input>
            <div>
              <el-button size="mini" type="danger" v-if="$route.query.type != 'show'" @click="deleteItem(i)">删除</el-button>
            </div>
          </div>
        </draggable>
        <div class="hint">*可拖动排序</div>
      </el-form-item>
      <h3>使用说明</h3>
      <el-form-item label="入园时间" prop="enteringParkTime">
        <el-input v-model="form.enteringParkTime" :disabled="$route.query.type == 'show'" placeholder="请输入入园时间" clearable />
      </el-form-item>
      <el-form-item label="入园地址" prop="enteringParkAddress">
        <el-input v-model="form.enteringParkAddress" :disabled="$route.query.type == 'show'" placeholder="请输入入园地址" clearable />
      </el-form-item>
      <h3>费用说明</h3>
      <el-form-item label="费用包含" prop="costIncluded">
        <el-input v-model="form.costIncluded" :disabled="$route.query.type == 'show'" placeholder="请输入费用包含" clearable />
      </el-form-item>
      <el-form-item label="详细说明" prop="costDescription">
        <el-input type="textarea" :rows="2" placeholder="请输入详细说明" :disabled="$route.query.type == 'show'" clearable v-model="form.costDescription">
        </el-input>
      </el-form-item>
      <h3>运营配置</h3>
      <el-form-item label="是否赠送积分豆" prop="giftPoints">
        <el-switch v-model="form.giftPoints" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="赠送积分比例是否默认" prop="giftPointsDfl" v-if="form.giftPoints">
        <el-switch v-model="form.giftPointsDfl" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="赠送积分比例" prop="giftPointsRate" v-if="form.giftPoints&&!form.giftPointsDfl">
        <el-input-number v-model="form.giftPointsRate" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>倍，*按照景区订单实际支付金额
      </el-form-item>
      <el-form-item label="是否开启分佣" prop="shareMoney">
        <el-switch v-model="form.shareMoney" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="分佣比例是否默认" prop="shareMoneyDfl" v-if="form.shareMoney">
        <el-switch v-model="form.shareMoneyDfl" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="分佣比例" prop="shareMoneyRate" v-if="form.shareMoney&&!form.shareMoneyDfl">
        <el-input-number v-model="form.shareMoneyRate" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>%，*按照订单实际付款金额进行分润
      </el-form-item>
      <el-form-item label="订单结算比例是否开启" prop="settlementProfitStatus">
        <el-switch v-model="form.settlementProfitStatus" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="订单结算比例" prop="settlementProfitRate" v-if="form.settlementProfitStatus">
        <el-input-number v-model="form.settlementProfitRate" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>%
      </el-form-item>
      <el-form-item label="是否热门商品" prop="hotStatus">
        <el-switch v-model="form.hotStatus" :disabled="$route.query.type == 'show'"> </el-switch>
      </el-form-item>
      <el-form-item label="券码库类型" prop="giftPoints">
        <!-- :disabled="form.businessProductId" -->
        <el-radio-group v-model="form.codeType" :disabled="Boolean(form.businessProductId)||$route.query.type == 'show'">
          <el-radio :label="1">券码库</el-radio>
          <el-radio :label="2" disabled>第三方系统</el-radio>
          <el-radio :label="3">商家自建券码库</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="form.codeType==1">
        <h3>时段配置</h3>
        <el-form-item label="是否开启时段" prop="reservationStatus">
          <el-switch v-model="form.reservationStatus" :disabled="$route.query.type == 'show'"> </el-switch>
        </el-form-item>
        <div v-if="form.reservationStatus">
          <el-form-item label="不可预约时间">
            <el-calendar v-model="currentDate">
              <template slot="dateCell" slot-scope="{ date, data }">
                <div class="custom-cell" :class="{ selected: isSelected(date) }" @click.stop="toggleSelection(date)">
                  {{ date.getDate() }}
                </div>
              </template>
            </el-calendar>
            <!-- <div style="margin-top: 20px;">
              已选择的日期：{{ selectedDates}}
            </div> -->
          </el-form-item>
          <div class="flex-bet">
            <h5>预约时间段设置</h5>
            <div><el-button type="primary" size="mini" v-if="$route.query.type != 'show'" @click="addBusinessProductCategory">新增</el-button></div>
          </div>
          <draggable :disabled="$route.query.type == 'show'" v-model=" form.businessProductTimeList" :options="{ group: 'typeLabel' }">
            <el-form-item v-for="(v,i) in form.businessProductTimeList" :key="i" :label="'预约时间段'+(i+1)+'：'">
              <div class="flex">
                <!-- <el-time-select v-model="v.startTime" value-format="hh:mm:ss" :picker-options="{step: '00:01'}" placeholder="选择开始时间">
                </el-time-select>
                <span style="display:inline-block;margin:0 10px">-</span>
                <el-time-select arrow-control v-model="v.endTime" :picker-options="{step: '00:01'}" placeholder="选择结束时间">
                </el-time-select> -->
                <el-time-picker is-range :disabled="$route.query.type == 'show'" v-model="v.timeArr" format="HH:mm" value-format="HH:mm" range-separator="至" start-placeholder="选择开始时间" end-placeholder="选择结束时间" placeholder="选择时间范围">
                </el-time-picker>
                <div><el-button size="mini" type="danger" v-if="$route.query.type != 'show'" @click="deleteBusinessProductCategory(i)">删除</el-button></div>
              </div>
            </el-form-item>
          </draggable>
          <div class="hint">*可拖动排序</div>
        </div>
      </div>
      <h3>页面分享配置</h3>
      <el-form-item label="分享标题" prop="shareTitle">
        <el-input style="width: 470px;" :disabled="$route.query.type == 'show'" v-model="form.shareTitle" placeholder="" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="分享图片" prop="shareImage">
        <imageUpload v-model="form.shareImage" :disabled="$route.query.type == 'show'" unique="shareImage" :limit="1" />
      </el-form-item>
    </el-form>
    <el-form label-width="120px">
      <el-form-item label="">
        <el-button v-if="$route.query.type != 'show'" :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { businessList, businessProductCategoryList } from "@/api/shop";
import {
  businessProductAdd,
  businessProductEdit,
  businessProductInfo,
} from "@/api/goods";
import draggable from "vuedraggable";
export default {
  components: {
    draggable,
  },
  data () {
    return {
      form: {
        businessProductCategoryId: undefined,
        businessId: undefined,
        title: undefined,
        coverImage: undefined,
        sellingPrice: undefined,
        originalPrice: undefined,
        limitQuantity: undefined,
        supplyPrice: undefined,
        stock: undefined,
        enteringParkTime: undefined,
        enteringParkAddress: undefined,
        costIncluded: undefined,
        costDescription: undefined,
        giftPoints: false,
        giftPointsDfl: true,
        shareMoney: false,
        giftPointsRate: undefined,
        shareMoneyDfl: true,
        shareMoneyRate: undefined,
        settlementProfitStatus: false,
        settlementProfitRate: undefined,
        settlementProfitStatus: false,
        reservationStatus: false,
        sortNum: 1,
        hotStatus: false,
        costPrice: undefined,
        expirationType: 1,
        effectiveDay: undefined,
        effectiveDate: undefined,
        businessProductNotesList: [{}],
        businessProductDateList: [{}],
        businessProductTimeList: [],
        codeType: 1,
        originalPriceShow: true,
        shareTitle: undefined,
        shareImage: undefined
      },
      shopList: [],
      shopTypeList: [],
      rules: {
        businessId: [
          { required: true, message: "请输入所属商家", trigger: "change" },
        ],
        title: [
          { required: true, message: "请输入商品名称", trigger: "change" },
        ],
        sellingPrice: [
          { required: true, message: "请输入销售价", trigger: "change" },
        ],
        originalPrice: [
          { required: true, message: "请输入原价", trigger: "change" },
        ],
        limitQuantity: [
          { required: true, message: "请输入限售数量", trigger: "change" },
        ],
        supplyPrice: [
          { required: true, message: "请输入供货价格", trigger: "change" },
        ],
        stock: [{ required: true, message: "请输入库存", trigger: "change" }],
        enteringParkTime: [
          { required: true, message: "请输入入园时间", trigger: "change" },
        ],
        enteringParkAddress: [
          { required: true, message: "请输入入园地址", trigger: "change" },
        ],
        costIncluded: [
          { required: true, message: "请输入费用包含", trigger: "change" },
        ],
        giftPoints: [
          { required: true, message: "请选择是否赠送积分豆", trigger: "change" },
        ],
        costPrice: [
          { required: true, message: "请输入成本价", trigger: "change" },
        ],
        effectiveDay: [
          { required: true, message: "请输入购买后有效天数", trigger: "change" },
        ],
        effectiveDate: [
          { required: true, message: "请输入指定有效时间", trigger: "change" },
        ],
        shareMoney: [
          { required: true, message: "请选择是否开启分佣", trigger: "change" },
        ],
        hotStatus: [
          { required: true, message: "请选择是否热门商品", trigger: "change" }
        ],
        giftPointsRate: [
          { required: true, message: "请输入赠送积分比例", trigger: "change" }
        ],
        shareMoneyRate: [
          { required: true, message: "请输入分佣比例", trigger: "change" }
        ],
        settlementProfitRate: [
          { required: true, message: "请输入订单结算比例", trigger: "change" }
        ],
      },
      buttonLoading: false,
      currentDate: new Date(),
      selectedDates: []
    };
  },
  created () {
    this.getShopList();
    if (this.$route.query.businessProductId) {
      this.getDetails(this.$route.query.businessProductId);
    }
  },
  methods: {
    // 判断某个日期是否已被选中
    isSelected (date) {
      return this.selectedDates.some(
        d => d === this.formatDate(date)
      );
    },
    // 点击切换选中状态
    toggleSelection (date) {
      if (this.$route.query.type == 'show') return
      let dateString = this.formatDate(date);
      let index = this.selectedDates.findIndex(
        d => this.formatDate(d) === dateString
      );
      if (index === -1) {
        this.selectedDates.push(this.formatDate(date));
      } else {
        this.selectedDates.splice(index, 1);
      }
    },
    // 格式化日期为 YYYY-MM-DD
    formatDate (date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getDetails (id) {
      businessProductInfo(id).then((res) => {
        if (!res.data.businessProductTimeList) {
          res.data.businessProductTimeList = [];
        } else {
          res.data.businessProductTimeList.map(item => {
            item.timeArr = [item.startTime, item.endTime]
          })
        }
        if (res.data.businessProductDateList) {
          this.selectedDates = res.data.businessProductDateList.map(item => {
            return item.reservationDate
          })
        } else {
          this.selectedDates = [];
        }
        console.log()
        this.form = res.data;
        this.getGoodsTypeList(this.form.businessId);
      });
    },
    getShopList () {
      businessList().then((res) => {
        this.shopList = res.data;
      });
    },
    addBusinessProductCategory () {
      this.form.businessProductTimeList.push({})
    },
    deleteBusinessProductCategory (index) {
      this.form.businessProductTimeList.splice(index, 1)
    },
    getGoodsTypeList (businessId) {
      businessProductCategoryList(businessId).then((res) => {
        this.shopTypeList = res.data;
      });
    },
    businessIdChange (e) {
      this.form.businessProductCategoryId = undefined;
      if (e) {
        this.getGoodsTypeList(e);
      } else {
        this.shopTypeList = [];
      }
    },
    cancel () {
      if (this.$route.query.queryParams) {
        localStorage.setItem('queryParams', this.$route.query.queryParams)
      }
      this.$router.go(-1);
    },
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let formCopy = JSON.parse(JSON.stringify(this.form));
          if (
            formCopy.businessProductNotesList &&
            formCopy.businessProductNotesList.length > 0
          ) {
            let arr = [];
            formCopy.businessProductNotesList.forEach((item, index) => {
              if (item.noteTitle) {
                item.noteIndex = formCopy.businessProductNotesList.length - index;
                arr.push(item)
              }
            });
            formCopy.businessProductNotesList = arr
          } else {
            formCopy.businessProductNotesList = []
          }
          if (
            formCopy.businessProductTimeList &&
            formCopy.businessProductTimeList.length > 0
          ) {
            let arr = [];
            console.log(formCopy.businessProductTimeList)
            formCopy.businessProductTimeList.forEach((item, index) => {
              if (item.timeArr && item.timeArr.length > 0) {
                item.startTime = item.timeArr[0];
                item.endTime = item.timeArr[1];
                item.sortIndex = index + 1;
                arr.push(item)
              }
            });
            formCopy.businessProductTimeList = arr
          } else {
            formCopy.businessProductTimeList = []
          }
          // 处理不可以预约时间传参格式
          if (this.selectedDates.length > 0) {
            formCopy.businessProductDateList = this.selectedDates.map(item => {
              return { reservationDate: item }
            })
          } else {
            formCopy.businessProductDateList = []
          }
          this.buttonLoading = true;
          if (this.form.businessProductId != null) {
            businessProductEdit(formCopy)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.cancel();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            businessProductAdd(formCopy)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.cancel();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    addItem () {
      this.form.businessProductNotesList.push({});
    },
    deleteItem (index) {
      this.form.businessProductNotesList.splice(index, 1);
    },
  },
};
</script>

<style lang='scss' scoped>
.el-form {
  width: 1000px;
}
.hint {
  font-size: 12px;
  color: red;
}
.map-box {
  width: calc(100% - 120px);
  height: 300px;
  margin-bottom: 30px;
  box-sizing: border-box;
  margin-left: 120px;
}
.flex {
  display: flex;
  margin-bottom: 10px;
  .el-button {
    margin-left: 10px;
  }
}
h3 {
  width: 160px;
  font-weight: 700;
  text-align: right;
}
.flex-bet {
  display: flex;
  justify-content: space-between;
}
.showTip {
  display: inline-block;
  margin-left: 20px;
  font-weight: 700;
  color: #606266;
}

.selected {
  background-color: #909399;
  color: white;
  border-radius: 4px;
}
::v-deep .el-calendar-table .el-calendar-day {
  height: 47px !important;
}
</style>