<template>
  <div class="app-container">
    <el-form ref="formRef" :model="formData" :rules="rules" size="small" label-width="auto">
      <el-form-item label="优惠券标题" prop="couponTitle" class="form-common-input" required>
        <el-input v-model="formData.couponTitle" placeholder="请输入优惠券标题" disabled />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="couponType" class="form-common-input" required>
        <el-select v-model="formData.couponType" placeholder="请选择优惠券类型" disabled>
          <el-option v-for="(item, index) in dict.type.coupon_type2" :key="index" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券分类" prop="categoryName" class="form-common-input" required>
        <el-input v-model="formData.categoryName" placeholder="请输入优惠券分类" disabled />
      </el-form-item>
      <el-form-item label="有效期" style="margin-bottom: 0;">
        <el-row style="width: 688px;">
          <el-col :span="4">
            <el-form-item prop="validityType">
              <el-radio v-model="formData.validityType" label="1">固定日期</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="validityDate" :rules="{
              required: formData.validityType === '1', message: '请选择日期', trigger: ['change', 'blur']
            }">
              <el-date-picker v-model="formData.validityDate" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;" value-format="yyyy-MM-dd"
                :disabled="formData.validityType === '2'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 688px;">
          <el-col :span="5">
            <el-form-item props="validityType">
              <el-radio v-model="formData.validityType" label="2">领取后当天生效</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="validityNum" :rules="{
              required: formData.validityType === '2', message: '请输入天数', trigger: ['change', 'blur']
            }">
              有效期
              <el-input type="number" v-model.number="formData.validityNum" placeholder="请输入天数" style="width: 200px;"
                :disabled="formData.validityType === '1'" />
              天
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="库存" prop="issued" class="form-common-input" :rules="{
        required: true, message: '请输入库存数', trigger: ['change', 'blur']
      }">
        <el-input type="number" v-model.number="formData.issued" placeholder="请输入库存数" />
      </el-form-item>
      <el-form-item label="领券限制" style="margin-bottom: 0;">
        <el-row style="width: 688px;">
          <el-col :span="12">
            <el-form-item prop="receiveTotalNum" :rules="{
              required: !receiveTotalChecked, message: '请输入', trigger: ['change', 'blur']
            }">
              总共可领取
              <el-input type="number" v-model.number="formData.receiveTotalNum" placeholder="请输入" style="width: 200px;"
                :disabled="receiveTotalChecked" />
              张
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="receiveTotalChecked">不限制</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 688px;">
          <el-col :span="12">
            <el-form-item prop="receiveDayNum" :rules="{
              required: !receiveDayChecked, message: '请输入', trigger: ['change', 'blur']
            }">
              每日可领取
              <el-input type="number" v-model.number="formData.receiveDayNum" placeholder="请输入" style="width: 200px;"
                :disabled="receiveDayChecked" />
              张
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="receiveDayChecked">不限制</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="适用门店">
        {{ formData.storeName }}
      </el-form-item>
      <el-form-item label="优惠券图片" class="image-url">
        <el-radio-group v-model="formData.url">
          <el-radio
            label="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-1.png">
            <ImagePreview
              src="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-1.png"
              :src-list="['https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-1.png']" />
          </el-radio>
          <el-radio
            label="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-2.png">
            <ImagePreview
              src="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-2.png"
              :src-list="['https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-2.png']" />
          </el-radio>
          <el-radio
            label="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-3.png">
            <ImagePreview
              src="https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-3.png"
              :src-list="['https://scrm-kp-event.crb.cn/links-software-web-file/integralMall/snow-guizhou/1_couponStyle-3.png']" />
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="使用须知" prop="remarks" class="form-common-input" :rules="{
        required: true, message: '请输入', trigger: ['change', 'blur']
      }">
        <el-input type="textarea" rows="6" v-model="formData.remarks" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="每日发放限制">
        <el-row style="width: 688px;">
          <el-col :span="8">
            <el-form-item prop="grantNum" :rules="{
              required: !grantChecked, message: '请输入', trigger: ['change', 'blur']
            }">
              <el-input type="number" v-model.number="formData.grantNum" placeholder="请输入" style="width: 200px;"
                :disabled="grantChecked" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item>
              <el-checkbox v-model="grantChecked">不限制</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item v-if="formData.couponType === 'team'" label="套餐名称" prop="mealTitle" class="form-common-input"
        :rules="{
          required: true, message: '请输入套餐名称', trigger: ['change', 'blur']
        }"
      >
        <el-input v-model="formData.mealTitle" placeholder="请输入套餐名称" />
      </el-form-item>
      <el-form-item v-if="formData.couponType === 'team'" label="原价" prop="originalPrice" class="form-common-input"
        :rules="{
          required: true, message: '请输入原价', trigger: ['change', 'blur']
        }"
      >
        <el-input type="number" v-model.number="formData.originalPrice" placeholder="请输入原价" />
      </el-form-item>
      <el-form-item v-if="formData.couponType === 'team'" label="折扣价" prop="presentPrice" class="form-common-input"
        :rules="{
          required: true, message: '请输入折扣价', trigger: ['change', 'blur']
        }"
      >
        <el-input type="number" v-model.number="formData.presentPrice" placeholder="请输入折扣价" />
      </el-form-item>
      <el-form-item v-if="formData.couponType === 'team'" label="套餐备注" prop="mealRemarks" class="form-common-input">
        <el-input type="textarea" rows="6" v-model="formData.mealRemarks" placeholder="请输入套餐备注" />
      </el-form-item>

      <template v-if="formData.couponType === 'team'">
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新建分类</el-button>
        </el-form-item>
        <el-form-item v-for="(item, index) in couponDetailList" :key="index" class="form-common-input">
          <el-card class="header-card" shadow="never">
            <div slot="header" class="clearfix">
              <span class="header-title">{{ item.category }}</span>
              <el-button
                size="small"
                type="primary"
                style="margin-left: 20px"
                @click="handleEdit(index)"
              >编辑</el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(index)"
              >删除</el-button>
            </div>
            <el-table :data="item.list" style="width: 100%;" size="small" border>
              <el-table-column label="菜品" prop="foodName">
              </el-table-column>
              <el-table-column label="份数" prop="foodNum">
              </el-table-column>
              <el-table-column label="价格" prop="foodPrice">
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>
      </template>

      <el-form-item label="状态" prop="couponStatus">
        <el-radio-group v-model="formData.couponStatus">
          <el-radio :label="'0'">正常</el-radio>
          <el-radio :label="'1'">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item size="medium">
        <el-button type="primary" @click="onSubmit">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>


    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="780px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="dialogFormRef" :model="chooseCouponDetail" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类:" prop="category"
              :rules="{
                required: true, message: '请输入分类', trigger: ['change', 'blur']
              }"
            >
              <el-input v-model="chooseCouponDetail.category" placeholder="请输入分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号:" prop="sort"
              :rules="{
                required: true, message: '请输入序号', trigger: ['change', 'blur']
              }"
            >
              <el-input type="number" v-model.number="chooseCouponDetail.sort" placeholder="请输入序号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px;">
          <el-button type="primary" @click="addFood">新增菜品</el-button>
        </el-row>
        <el-row v-for="(item, index) in chooseCouponDetail.list" :key="index">
          <el-col :span="7">
            <el-form-item label="菜名:" :prop="'list.' + index + '.foodName'"
              :rules="{
                required: true, message: '请输入菜品', trigger: ['change', 'blur']
              }"
            >
              <el-input v-model="item.foodName" placeholder="请输入菜品" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="份数:" :prop="'list.' + index + '.foodNum'"
              :rules="{
                required: true, message: '请输入份数', trigger: ['change', 'blur']
              }"
            >
              <el-input type="number" v-model.number="item.foodNum" placeholder="请输入份数" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="价格:" :prop="'list.' + index + '.foodPrice'"
              :rules="{
                required: true, message: '请输入价格', trigger: ['change', 'blur']
              }"
            >
              <el-input type="number" v-model.number="item.foodPrice" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialog">确 定</el-button>
        <el-button @click="cleanDialog">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import { couponDetail, editCoupon } from '@/api/coupon/list.js'
import { deepClone } from '@/utils';

export default {
  name: "CouponEdit",
  dicts: ["coupon_type2"],
  data() {
    return {
      receiveTotalChecked: false,
      receiveDayChecked: false,
      grantChecked: false,
      formData: {},
      rules: {},
      couponDetailList: [],
      chooseCouponDetail: {},
      dialogTitle: '',
      dialogVisible: false,
      editIndex: 0
    };
  },
  mounted() {
    this.getDetail();
  },
  watch: {
    "formData.validityType": {
      handler(o, v) {
        // if (v === '1') {
        //   this.formData.validityDate = []
        // } else {
        //   this.formData.validityNum = undefined
        // }
      }
    }
  },
  methods: {
    getDetail() {
      couponDetail(this.$route.query.id).then(res => {
        const formData = Object.assign({}, res.data);
        if (formData.validityType === "1") {
          formData.validityDate = [
            formData.validityStartDate,
            formData.validityEndDate
          ];
        }
        else {
          formData.validityDate = [];
        }
        // 总共可领取
        if (formData.receiveTotal === -1) {
          this.receiveTotalChecked = true;
        }
        else {
          this.receiveTotalChecked = false;
          formData.receiveTotalNum = formData.receiveTotal;
        }
        // 每日可领取
        if (formData.receiveDay === -1) {
          this.receiveDayChecked = true;
        }
        else {
          this.receiveDayChecked = false;
          formData.receiveDayNum = formData.receiveDay;
        }
        // 每日发放
        if (formData.grant === -1) {
          this.grantChecked = true;
        }
        else {
          this.grantChecked = false;
          formData.grantNum = formData.grant;
        }

        this.formData = formData;
        this.couponDetailList = deepClone(formData.couponDetailList)
      });
    },
    handleAdd() {
      this.dialogTitle = '新增分类'
      this.chooseCouponDetail = {
        category: undefined,
        sort: undefined,
        list: []
      }
      // this.reset('dialogFormRef')
      this.dialogVisible = true
    },
    handleEdit(index) {
      this.editIndex = index
      this.dialogTitle = '编辑分类'
      const chooseCouponDetail = deepClone(this.couponDetailList[index])
      this.chooseCouponDetail = chooseCouponDetail
      this.dialogVisible = true
    },
    handleDelete(index) {
      this.couponDetailList.splice(index, 1)
    },
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {

          const pp = deepClone(this.formData)

          if (pp.validityType === "1") {
            pp.validityStartDate = pp.validityDate[0]
            pp.validityEndDate = pp.validityDate[1]
          }

          if (this.receiveTotalChecked) {
            pp.receiveTotal = -1
          } else {
            pp.receiveTotal = pp.receiveTotalNum
          }

          if (this.receiveDayChecked) {
            pp.receiveDay = -1
          } else {
            pp.receiveDay = pp.receiveDayNum
          }

          if (this.grantChecked) {
            pp.grant = -1
          } else {
            pp.grant = pp.grantNum
          }

          if (pp.couponType === 'team') {
            pp.couponDetailList = deepClone(this.couponDetailList)
            pp.couponDetailList.forEach(item => {
              item.goodsJson = JSON.stringify(item.list)
            })
          }

          editCoupon(pp).then(res => {
            this.$modal.msgSuccess('优惠券编辑成功')
            this.$tab.closeOpenPage()
            this.$router.push({
              name: 'CouponList',
              params: {
                refreshTable: true
              }
            })
          })
        }
      });
    },
    cancel() {
      this.$tab.closeOpenPage();
      this.$router.push({ name: "CouponList" });
    },
    addFood() {
      this.chooseCouponDetail.list.push({
        foodName: undefined,
        foodNum: undefined,
        foodPrice: undefined
      })
    },
    submitDialog() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {

          const chooseCouponDetail = deepClone(this.chooseCouponDetail)

          if (this.dialogTitle === '编辑分类') {
            this.couponDetailList.splice(this.editIndex, 1, chooseCouponDetail)
          } else {
            this.couponDetailList.push(chooseCouponDetail)
          }

          this.dialogVisible = false
        }
      })
    },
    cleanDialog() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
}

.image-url {
  ::v-deep .el-radio__input {
    vertical-align: top;
  }
}
</style>
