<template>
  <!-- 添加或修改测试单表对话框 -->
  <div>
    <Drawer :title="title" :visible.sync="show" :showFooter="true" :skeleton="skeletonLoading" :wrapperClosable="true"
      :size="$drawerWidth(800)">
      <el-form ref="form" :model="form" :disabled="title == '查看'" :size="ELsize" :rules="rules" label-width="auto">
        <el-form-item label="用户类型：" prop="trait">
          <div>
            <el-radio v-model="form.trait" :label="0">普通券</el-radio>
            <span class="c_red">（指全部用户可用的优惠券，发布后用户在规定时间内领取）</span>
          </div>
          <!-- <el-radio v-model="form.trait" :label="1">新人券</el-radio>
        <span class="c_red">（指新用户可用的优惠券，注册完成之后，系统自动将所有新人券发放给用户）</span> -->
          <!-- <div>
          <el-radio v-model="form.trait" :label="2">定向券</el-radio>
        </div> -->
        </el-form-item>
        <el-form-item label="优惠券名称：" prop="name">
          <el-input v-model="form.name" maxlength="20" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="发放总量：" prop="issueNumber" v-if="form.trait != 2">
          <el-input-number size="small" :precision="0" v-model="form.issueNumber" controls-position="right" :min="-1"
            :max="10000000"></el-input-number>
          张
          <span class="c_red">（-1代表不限制总量）</span>
        </el-form-item>
        <el-form-item label="使用门槛：" prop="hasThreshold">
          <div>
            <el-radio v-model="form.hasThreshold" :label="true">
              订单满
              <el-input-number size="small" :precision="2" :step="0.01" v-model="form.threshold"
                controls-position="right" :min="0"></el-input-number>
              元
            </el-radio>
          </div>
          <div>
            <el-radio v-model="form.hasThreshold" :label="false">无门槛</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="使用描述：" prop="content">
          <el-input v-model="form.content" maxlength="100" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="优惠金额：" prop="faceValue">
          减免
          <el-input-number size="small" :step="0.01" :precision="2" v-model="form.faceValue" controls-position="right"
            :min="0"></el-input-number>
          元
        </el-form-item>
        <el-form-item label="有效期：" prop="expiredDay">
          领取后生效
          <el-input-number size="small" :precision="0" v-model="form.expiredDay" controls-position="right"
            :min="0"></el-input-number>
          天
        </el-form-item>
        <el-form-item label="每人限领张数：" prop="receiveLimit">
          <el-input-number size="small" v-model="form.receiveLimit" :precision="0" controls-position="right"
            :min="-1"></el-input-number>
          次
          <span class="c_red">（-1代表不限制）</span>
          <!-- 新人券建议限领1次， -->
        </el-form-item>
        <!-- <el-form-item label="其他活动是否参与：">
        <el-checkbox-group v-model="activityArr">
          <el-checkbox v-for="(v,i) in activityList" :key="i" :label="v.code">{{v.name}}</el-checkbox>
        </el-checkbox-group>
        <div class="c_red">
          （不勾选则默认为其他活动不可参与此优惠券活动，勾选后则支持叠加使用）
        </div>
      </el-form-item> -->
        <el-form-item label="领取时间：" prop="timeArr">
          <el-date-picker v-model="form.timeArr" :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用范围：" prop="modeType">
          <div class="flex">
            <!-- <div v-if="form.mode === 0" class="ml20">
            <el-radio v-model="form.modeType" :label="1">全部店铺</el-radio>
            <el-radio v-model="form.modeType" :label="2">指定店铺不可用</el-radio>
            <el-radio v-model="form.modeType" :label="3">指定店铺可用</el-radio>
          </div> -->
            <div v-if="form.mode === 1" class="ml20">
              <el-radio v-model="form.modeType" :label="1">全部商品</el-radio>
              <el-radio v-model="form.modeType" :label="2">指定商品不可用</el-radio>
              <el-radio v-model="form.modeType" :label="3">指定商品可用</el-radio>
            </div>
          </div>
        </el-form-item>
        <!-- <div class="tableBox" v-if="(form.modeType == 2 || form.modeType == 3) && form.mode === 0">
        <div class="flex_bet">
          <h4>{{ mode === 0 ? '选择店铺' : '选择商品' }}</h4>
          <div>
            <el-button type="primary" size="small" @click="innerVisible = true">选择店铺</el-button>
          </div>
        </div>
        <el-table :data="selShops" border style="width: 100%">
          <el-table-column align="center" type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="companyName" header-align="center" align="center" label="店铺名称">
          </el-table-column>
          <el-table-column prop="loser" header-align="center" align="center" label="联系人">
          </el-table-column>
          <el-table-column prop="mobile" header-align="center" align="center" label="联系电话">
          </el-table-column>
          <el-table-column prop="province" header-align="center" align="center" label="店铺地址">
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
            <template slot-scope="{ row, $index }">
              <el-button type="text" size="small" @click="delSelShop(row, $index)">删除</el-button>
            </template>
</el-table-column>
</el-table>
</div> -->

        <div class="tableBox" v-if="(form.modeType == 2 || form.modeType == 3) && form.mode === 1">
          <div class="flex_bet">
            <h4>{{ mode === 0 ? '选择店铺' : '选择商品' }}</h4>
            <div>
              <el-button type="primary" size="small" @click="openSelGoods">{{ mode === 0 ? '选择店铺' : '选择商品'
              }}</el-button>
            </div>
          </div>
          <el-table :data="selProducts" border style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="company_name" header-align="center" align="center" label="商品图片">
              <template slot-scope="{ row }">
                <el-image style="width: 50px; height: 50px" :src="row.coverImage"
                  :preview-src-list="row.coverImage ? [row.coverImage] : []"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="title" header-align="center" align="center" label="商品名称">
            </el-table-column>
            <el-table-column prop="mobile" header-align="center" align="center" label="商品价格（元）">
              <template slot-scope="scope">
                <span>{{
                  scope.row.minSalePrice == scope.row.maxSalePrice
                    ? scope.row.minSalePrice
                    : scope.row.minSalePrice + '~' + scope.row.maxSalePrice
                }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="{ row, $index }">
                <el-button type="text" size="small" @click="delSelGood(row, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template v-slot:footer>
        <el-button :size="ELsize" :loading="buttonLoading" v-if="title != '查看'" type="primary" @click="submitForm">确
          定</el-button>
        <el-button :size="ELsize" @click="cancel">取 消</el-button>
      </template>
    </Drawer>
    <selGoods ref="selGoodsRef" @result="getSelGoods" />
  </div>
  <!-- <el-drawer :title="title" :visible.sync="show" size="800px" append-to-body @close="cancel">

    <div class="demo-drawer__footer">

    </div>

  </el-drawer> -->
</template>

<script>
import { couponAdd, couponInfo, couponEdit } from "@/api/marketing.js";
import selGoods from "@/components/selGoods/index.vue";
export default {
  components: {
    selGoods
  },
  data() {
    return {
      skeletonLoading: false,
      title: "新增",
      form: {},
      activityArr: [],
      activityList: [
        { code: 0, name: '无活动' },
        { code: 5, name: '秒杀' },
        { code: 10, name: '拼团' },
      ],
      show: false,
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'change' }
        ],
        issueNumber: [
          { required: true, message: '请输入发放总量', trigger: 'change' }
        ],
        hasThreshold: [
          { required: true, message: '请选择使用门槛', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入使用描述', trigger: 'change' }
        ],
        faceValue: [
          { required: true, message: '请输入优惠金额', trigger: 'change' }
        ],
        expiredDay: [
          { required: true, message: '请输入有效期', trigger: 'change' }
        ],
        receiveLimit: [
          { required: true, message: '请输入每人限领张数', trigger: 'change' }
        ],
        timeArr: [
          { required: true, message: '请选择领取时间', trigger: 'change' }
        ],
        modeType: [
          { required: true, message: '请选择使用范围', trigger: 'change' }
        ]
      },
      buttonLoading: false,
      pickerOptions: {
        disabledDate(time) {
          // 只允许选择今天之后的日期（不包含今天）
          // 即：禁用今天及之前的所有日期
          const today = new Date();
          // 将今天的时间归零，只比较日期部分
          const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
          return time.getTime() < todayStart.getTime();
        }
      },
      selProducts: []
    }
  },
  props: {
    //0平台券 1商户
    mode: {
      type: Number,
      default: 1
    },
  },
  methods: {
    init() {
      this.selProducts = []
      this.form = {
        trait: 0,
        name: undefined,
        issueNumber: undefined,
        hasThreshold: undefined,
        threshold: undefined,
        content: undefined,
        faceValue: undefined,
        expiredDay: undefined,
        receiveLimit: undefined,
        modeType: undefined,
        timeArr: [],
        type: 0, //优惠券类型只能是满减券
        mode: this.mode,
        adaptActivity: [],
        timeArr: []
      };
      this.$refs["form"] && this.$refs["form"].resetFields();
    },
    open(title, item) {
      this.title = title;
      this.init();
      this.show = true;
      if (item && item.id) {
        this.getDetails(item.id)
      }
    },
    openSelGoods() {
      this.$refs.selGoodsRef.open(this.selProducts)
    },
    getDetails(id) {
      this.skeletonLoading = true;
      couponInfo(id).then(res => {
        this.activityArr = res.data.adaptActivity.map((v, i) => {
          return this.activityList.findIndex(item => item.code == v.code)
        })
        res.data.timeArr = [res.data.startTime, res.data.endTime];
        res.data.mode = 1;
        // 使用范围回显处理
        if (res.data.universal) res.data.modeType = 1
        else if (!res.data.adaptOrNo) res.data.modeType = 2
        else if (res.data.adaptOrNo) res.data.modeType = 3
        this.selProducts = res.data.productList
        this.form = res.data
      }).finally(() => {
        this.skeletonLoading = false;
      })
    },
    // 表单重置
    reset() {
      this.init();
      this.resetForm("form");
    },
    // 删除选择的商品
    delSelGood(row, index) {
      this.selProducts.splice(index, 1)
    },
    // 取消按钮
    cancel() {
      this.show = false;
      this.reset();
    },
    getSelGoods(e) {
      this.selProducts = e;
      // this.form.adaptProductIds = e.map((v) => {
      //   return v.productId
      // })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if (this.activityArr && this.activityArr.length > 0) {
          //   this.form.adaptActivity = [];
          //   this.activityArr.forEach((v) => {
          //     this.form.adaptActivity.push(this.activityList[v])
          //   })
          // }
          // 只能是
          this.form.adaptActivity = [this.activityList[0]]
          // 重新定义  领取时间字段
          this.form.startTime = this.form.timeArr[0]
          this.form.endTime = this.form.timeArr[1]
          // 重新定义  使用范围字段
          if (this.form.modeType == 1) {
            this.form.universal = true
            this.form.adaptOrNo = false
          } else if (this.form.modeType == 2) {
            this.form.universal = false
            this.form.adaptOrNo = false
          } else if (this.form.modeType == 3) {
            this.form.universal = false
            this.form.adaptOrNo = true
          }
          // 获取选择的部门id
          if (!this.form.universal) {
            this.form.adaptProductIds = this.selProducts.map((v) => {
              return v.productId
            })
            if (
              !this.form.adaptProductIds ||
              this.form.adaptProductIds.length <= 0
            ) {
              this.$message.error('选择的商品个数不能少于1！')
              return
            }
          }
          this.buttonLoading = true;
          if (this.form.id != null) {
            couponEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.show = false;
              this.$emit('change')
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            couponAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.show = false;
              this.$emit('change')
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
  }
}
</script>

<style lang='scss' scoped>
.flex_bet {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-drawer__footer {
  margin: 20px 0;
}
</style>