<template>
  <div class="add-coupon-page">
    <Card v-if="loading" class="loading-card">
      <Spin fix size="large" />
    </Card>
    <Card v-else class="main_card">
      <div class="main_info">
        <div class="head">
          <Icon type="md-bookmark" color="#2d8cf0" :size="28" />
          <label>{{ title }}</label>
        </div>
        <div class="item">
          <label class="label">名称：</label>
          <Input
            placeholder="请输入优惠券名称"
            v-model="form.name"
            :maxlength="30"
            style="width: 400px"
            :readonly="isDetail"
          />
        </div>
        <!-- <div class="item">
          <label class="label">类型：</label>
          <Select
            placeholder="请选择优惠券类型"
            style="width: 400px;"
            v-model="form.type"
            :disabled="isDetail"
          >
            <Option v-for="item in typeList" :value="item.value" :key="item.value">{{item.label}}</Option>
          </Select>
        </div> -->
        <div class="item">
          <label class="label">面值：</label>
          <Input
            placeholder="请输入优惠券面值"
            v-model="form.couponVal"
            :maxlength="30"
            style="width: 400px"
            :readonly="isDetail"
          />
        </div>
        <div class="item" v-if="form.type==1">
          <label class="label">使用条件：</label>
          满 &nbsp <Input :readonly="isDetail" v-model="form.conditionVal" style="width: 100px;"/> &nbsp 可使用
          <!-- <RadioGroup v-model="condition">
            <Radio :disabled="isDetail" :label="1">无限制</Radio>
            <Radio :disabled="isDetail" :label="2" ></Radio>
          </RadioGroup> -->
        </div>
        <div class="item">
          <label class="label">使用范围：</label>
          <Select
            placeholder="请选择优惠券可用范围"
            v-model="form.scope"
            style="width: 400px;"
            :disabled="isDetail"
          >
            <Option v-for="item in scopeList" :value="item.value" :key="item.value">{{item.label}}</Option>
          </Select>
        </div>
        <div class="item">
          <label class="label">有效时间：</label>
          <Row class="time">
            <Col>
              <DatePicker type="date" :readonly="isDetail" :options="drawStartOption" v-model="form.startTime" placeholder="请选择开始时间"></DatePicker>
            </Col>
            <span>至</span>
            <Col>
              <DatePicker type="date" :readonly="isDetail" :options="drawEndOption" v-model="form.endTime"  placeholder="请选择结束时间"></DatePicker>
            </Col>
          </Row>
        </div>
        <div class="item">
          <label class="label">发行量：</label>
          <Input
            placeholder="请输入发行量"
            v-model="form.circulation"
            :maxlength="30"
            style="width: 400px"
            :readonly="isDetail"
          />
        </div>
        <div class="item">
          <label class="label">备注信息：</label>
          <Input
            placeholder="请输入备注信息"
            v-model="form.remark"
            :maxlength="30"
            style="width: 400px"
            type="textarea"
            :readonly="isDetail"
          />
        </div>
        <div class="item">
          <label class="label">商品范围：</label>
          <RadioGroup v-model="form.rangeType">
            <Radio :label="1" :disabled="isDetail" class="ivu-radio">全部商品</Radio>
            <span @click="category"><Radio :disabled="isDetail" :label="2" class="ivu-radio">指定类目</Radio></span>
            <span @click="getGoods"><Radio :disabled="isDetail" :label="3" v-if="!platform" class="ivu-radio">指定商品</Radio></span>
          </RadioGroup>
        </div>
        <div class="footer-con">
          <Button
            type="default"
            @click="handleCancel"
            style="margin-right: 30px"
            v-if="!isDetail"
          >取消</Button
          >
          <Button
            type="primary"
            @click="handleSubmit"
            v-if="!isDetail"
          >确定</Button
          >
        </div>
      </div>
      <Card class="range_type" v-if="this.form.rangeType == 2">
        <div>
          <Tree :disabled="isDetail" :data="specifiedCategoryList" show-checkbox multiple ref="tree" @on-check-change="getCategoryList"></Tree>
        </div>
        <div style="text-align:right;margin-top:10px">
          <Button
            type="primary"
            @click="getCategoryList"
            v-if="!isDetail"
          >确定</Button
          >
        </div>
      </Card>
      <Card class="range_type" v-if="this.form.rangeType == 3">
        <div style="text-align:left;margin:10px 0">
          <Input :readonly="isDetail" v-model="goods" placeholder="请输入产品编号或者名称" style="width: 300px" search @on-search="getGoods"/>
        </div>
        <div>
          <tables
            ref="tables"
            editable
            v-model="tableData"
            :columns="columns"
            :loading="loading"
            @on-selection-change="changeSelect"
            :readonly="isDetail"
            :disabled="isDetail"
            height="500"
          />
        </div>
        <div style="text-align:right;margin:10px 0">
          <Button
            type="primary"
            @click="btnSelect"
            v-if="!isDetail"
          >添加</Button
          >
        </div>
      </Card>
    </Card>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { mapMutations } from 'vuex'
import { formatTime } from '@/libs/tools'
export default {
  name: 'add-coupon',
  components: {
    Tables
  },
  computed: {
    title () {
      if (this.routeName === 'update_coupon') {
        return '编辑优惠券'
      } else if (this.routeName === 'coupon_detail') {
        return '优惠券详情'
      } else {
        return '新增优惠券'
      }
    },
    isDetail () {
      return this.routeName === 'coupon_detail'
    },
    isAdd () {
      return this.routeName === 'add_coupon'
    },
    isEdit () {
      return this.routeName === 'update_coupon'
    },
    platform () {
      return this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
    }
  },
  data () {
    return {
      routeName: '',
      loading: false,
      tableData: [], // 商品列表
      selectList: [],
      goods: '',
      selectCount: '',
      categoryInfo: {}, // 类目信息
      skuList: [],
      form: {
        name: '', // 优惠券名称
        type: 1, // 优惠券类型
        couponVal: '', // 优惠券面值
        conditionVal: '', // 使用优惠券条件值
        scope: '', // 活动范围
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        circulation: '', // 发行量
        remark: '', // 备注信息
        rangeType: '', // 范围类型
        categoryList: [], // 类目信息
        couponSkuList: [], // 指定商品
        exchangePrice: '', // 优惠券兑换价格（仅旅游消费）
        updateTime: '', // 更新时间
        couponId: ''
      },
      condition: '', // 使用条件
      typeList: [
        {
          value: '1',
          label: '满减'
        }
        // {
        //   value: '2',
        //   label: '直减'
        // }
      ],
      scopeList: [
        {
          value: '1',
          label: '全部 '
        },
        {
          value: '2',
          label: 'APP'
        },
        {
          value: '3',
          label: 'PC'
        },
        {
          value: '4',
          label: '微信小程序'
        }
      ],
      specifiedCategoryList: [
        {
          expand: true,
          children: [
            {
              // expand: true,
              children: [
              ]
            },
            {
              children: [
              ]
            }
          ]
        }
      ],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        { title: '编号', key: 'goodsId', align: 'center', width: 150 },
        { title: '名称', key: 'name', align: 'center', minWidth: 100 },
        { title: '描述', key: 'description', align: 'center', minWidth: 100 }
      ],
      drawStartOption: {
        // 指定开始限制时间
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now()
        }
      },
      drawEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now()
        }
      }
    }
  },
  mounted () {
    this.initData()
  },
  methods: {
    ...mapMutations(['closeTag']),
    requestBannerDetail (couponId) {
      this.api({
        apiName: 'couponDetail',
        dealUrl: (url) => {
          return `${url}/${couponId}`
        },
        success: (res) => {
          // debugger
          // console.log(res)
          let { name, type, couponVal, conditionVal, scope, startTime, endTime, circulation, remark, rangeType, categoryList, couponSkuList, updateTime, couponId } = res.data
          this.form.name = name
          this.form.type = JSON.stringify(type)
          this.form.couponVal = couponVal
          this.form.conditionVal = conditionVal
          this.form.scope = JSON.stringify(scope)
          this.form.startTime = formatTime(startTime)
          this.form.endTime = formatTime(endTime)
          this.form.circulation = circulation
          this.form.remark = remark
          this.form.rangeType = rangeType
          this.form.categoryList = categoryList
          let obj = {}
          couponSkuList.forEach(item => {
            obj = {
              goodsId: item.goodsId,
              couponId: item.couponId
            }
            this.form.couponSkuList.push(obj)
          })
          this.form.updateTime = updateTime
          this.form.couponId = couponId
          if (this.form.conditionVal == 0) {
            this.condition = 1
            this.form.conditionVal = ''
          } else {
            this.condition = 2
          }
          if (this.form.rangeType == 2) {
            this.category()
          }
          if (this.form.rangeType == 3) {
            this.getGoods()
          }
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      console.log(routeName)
      let couponId = this.$route.query.couponId
      this.routeName = routeName
      if (routeName == 'update_coupon' || routeName == 'coupon_detail') {
        this.requestBannerDetail(couponId)
      } else {
        this.loading = false
      }
    },
    handleCancel () {
      let title = '已取消'
      let route = this.$route
      let toRouteName = 'coupon_management'
      this.closeTag({ route, toRouteName })
      this.$Notice.success({ title })
    },
    // 指定类目
    category () {
      this.api({
        apiName: 'categoryList',
        success: (res) => {
          let value = this.formatRes(res.data)
          this.specifiedCategoryList.forEach(item => {
            item.title = value[0].title
            item.children = value[0].children
            item.categoryId = value[0].categoryId
            item.level = value[0].level
          })
        }
      })
    },
    // 指定商品
    getGoods () {
      let { goods } = this
      this.api({
        apiName: 'queryByNameOrId',
        postdata: { goods },
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          this.tableData = res.data
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.isDetail) {
              this.tableData[i]._disabled = true
            }
            for (let j = 0; j < this.form.couponSkuList.length; j++) {
              if (this.form.couponSkuList[j].goodsId === this.tableData[i].goodsId) {
                this.tableData[i]._checked = true
                this.tableData[i].couponId = this.form.couponSkuList[j].couponId
              }
            }
          }
        }
      })
    },
    handleSubmit () {
      let couponSaveDTO = {
        name: this.form.name,
        type: this.form.type,
        couponVal: JSON.parse(this.form.couponVal),
        conditionVal: JSON.parse(this.form.conditionVal),
        scope: this.form.scope,
        startTime: new Date(this.form.startTime).getTime(),
        endTime: new Date(this.form.endTime).getTime() + 86399000,
        circulation: this.form.circulation,
        remark: this.form.remark,
        rangeType: this.form.rangeType,
        exchangePrice: this.form.exchangePrice || 0,
        categoryList: this.form.categoryList,
        couponSkuList: this.form.couponSkuList,
        updateTime: this.form.updateTime,
        couponId: this.form.couponId
      }
      if (couponSaveDTO.type == 2) {
        couponSaveDTO.conditionVal = 0
      }
      if (couponSaveDTO.name == '') {
        return this.$Notice.warning({ title: '请输入优惠券名称' })
      }
      if (couponSaveDTO.couponVal == '') {
        return this.$Notice.warning({ title: '请输入优惠券面值' })
      }
      if (couponSaveDTO.conditionVal == '') {
        return this.$Notice.warning({ title: '请输入使用条件' })
      }
      if (couponSaveDTO.scope == '') {
        return this.$Notice.warning({ title: '请选择活动范围' })
      }
      if (isNaN(couponSaveDTO.startTime) || isNaN(couponSaveDTO.endTime)) {
        return this.$Notice.warning({ title: '请选择开始或结束时间' })
      }
      if (couponSaveDTO.circulation == '') {
        return this.$Notice.warning({ title: '请输入发行量' })
      }
      if (couponSaveDTO.remark == '') {
        return this.$Notice.warning({ title: '请输入备注信息' })
      }
      if (couponSaveDTO.rangeType == '') {
        return this.$Notice.warning({ title: '请选择商品范围' })
      }
      if (couponSaveDTO.couponVal < 0) {
        this.$Notice.warning({ title: '优惠券面值不能小于0' })
        this.form.couponVal = ''
        return false
      } else if (couponSaveDTO.conditionVal < 0) {
        this.$Notice.warning({ title: '优惠券使用条件值不能小于0' })
        this.form.conditionVal = ''
        return false
      } else if (couponSaveDTO.couponVal > couponSaveDTO.conditionVal) {
        this.$Notice.warning({ title: '优惠券使用条件值不能小于面值' })
        this.form.couponVal = ''
        this.form.conditionVal = ''
        return false
      } else if (couponSaveDTO.circulation < 0) {
        this.$Notice.warning({ title: '优惠券发行量不能小于0' })
        this.form.circulation = ''
        return false
      } else if (couponSaveDTO.startTime > couponSaveDTO.endTime) {
        this.$Notice.warning({ title: '开始时间不能大于结束时间' })
        this.form.startTime = ''
        this.form.endTime = ''
        return false
      } else if (couponSaveDTO.categoryList.length == 0 && couponSaveDTO.rangeType == 2) {
        this.$Notice.warning({ title: '请选择指定类目' })
        return false
      } else if (couponSaveDTO.couponSkuList.length == 0 && couponSaveDTO.rangeType == 3) {
        this.$Notice.warning({ title: '请选择指定商品' })
        return false
      }
      let apiName = this.isAdd ? 'addcoupon' : 'updateCoupon'
      let title = this.isAdd ? '添加成功！' : '编辑成功！'
      this.api({
        apiName,
        postdata: couponSaveDTO,
        success: (res) => {
          console.log('res', res)
          // 关闭当前标签页
          let route = this.$route
          let toRouteName = 'coupon_management'
          this.closeTag({ route, toRouteName })
          this.$Notice.success({ title })
        }
      })
    },
    // 获取选中商品数据
    btnSelect () {
      if (this.selectCount <= 0 && this.form.couponSkuList.length <= 0) {
        this.$Message.warning('您还未选中数据')
        return false
      } else if (this.selectCount <= 0) {
        this.$Message.success('取消成功')
        this.form.couponSkuList = this.selectList
      } else {
        this.$Message.success('添加商品成功')
        this.form.couponSkuList = this.selectList
      }
    },
    changeSelect (e) {
      let obj = {}
      this.selectList = e.map(item => {
        if (item.couponId != undefined) {
          obj = {
            goodsId: item.goodsId,
            couponId: item.couponId,
            skuId: item.skuId
          }
        } else {
          obj = {
            goodsId: item.goodsId,
            skuId: item.skuId
          }
        }
        return obj
      })
      this.selectCount = e.length
    },
    // 获取选中商品类目
    getCategoryList () {
      const checkedNodes = this.$refs.tree.getCheckedNodes()
      this.form.categoryList = []
      checkedNodes.forEach(item => {
        this.categoryInfo = {
          categoryId: item.categoryId,
          checked: item.checked,
          expand: true,
          clazzId: item.clazzId,
          level: item.level,
          name: item.title,
          updateTime: item.updateTime
        }
        this.form.categoryList.push(this.categoryInfo)
        console.log(checkedNodes)
      })
    },
    formatRes (res) {
      const arr = []
      let obj = {}
      res.forEach(item => {
        const tmp = { ...item }
        if (item.name) {
          if (tmp.childList) {
            tmp.children = this.formatRes(tmp.childList)
            obj = {
              title: tmp.name,
              children: tmp.children,
              categoryId: tmp.categoryId,
              level: tmp.level,
              clazzId: tmp.clazzId,
              thumb: tmp.thumb,
              updateTime: tmp.updateTime
            }
            if (this.isDetail) {
              obj.disabled = true
            }
            if (this.form.categoryList.find(itemb => tmp.categoryId === itemb.categoryId)) {
              obj = {
                title: tmp.name,
                children: tmp.children,
                categoryId: tmp.categoryId,
                level: tmp.level,
                clazzId: tmp.clazzId,
                thumb: tmp.thumb,
                updateTime: tmp.updateTime,
                checked: true,
                expand: true
              }
              if (this.isDetail) {
                obj.disabled = true
              }
            }
          }
          arr.push(obj)
        }
      })
      return arr
    }
  }
}
</script>

<style scoped lang="less">
  .add-coupon-page {
    height: 100%;
    min-width: 1000px;
    // position: relative;

    .loading-card {
        height: 100%;
      }
    .main_card{
      overflow: hidden;
      .main_info{
      float: left;
      width: 60%;
      .head {
        color: #17233d;
        font-size: 18px;
        font-weight: bold;
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        i {
          margin-right: 10px;
        }
      }
      .item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
      .ivu-radio{
        width: 150px;
      }
      }
      .item .label {
        display: block;
        width: 200px;
        text-align: right;
      }
      .time{
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .footer-con {
        display: flex;
        padding: 30px 200px;
      }
    }
      .range_type{
        width: 35%;
        float: left;
        margin-bottom: 10px;
      }
    }
  }
  // /deep/.vertical-center-modal{
  //       display: flex;
  //       align-items: center;
  //       justify-content: center;
  //       .ivu-modal{
  //           top: 0;
  //       }
  //   }
</style>
