<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>
        <RadioGroup v-model="form.type">
          <Radio :disabled="isDetail" :label="4" style="margin-right:20px">
            直降 <Input :readonly="isDetail" v-model="condition.straightDown" style="width: 60px" />元
          </Radio>
          <Radio :disabled="isDetail" :label="2" style="margin-right:20px"
            >满
            <Input :readonly="isDetail" v-model="condition.full" style="width: 60px" />
            元减 <Input
              v-model="condition.reduction"
              style="width: 60px"
              :readonly="isDetail"
            />元</Radio
          >
          <Radio :disabled="isDetail" :label="3" style="margin-right:20px"
            >每满
            <Input :readonly="isDetail" v-model="condition.everyFull" style="width: 60px" />
            元减 <Input
              v-model="condition.everyReduction"
              style="width: 60px"
              :readonly="isDetail"
            />元</Radio
          >
          <Radio :disabled="isDetail" :label="5"
            ><Input
              :readonly="isDetail"
              v-model="condition.discount"
              style="width: 60px"
            /> 折扣</Radio
          >
        </RadioGroup>
      </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>
          <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>
          <Input
            placeholder="请输入备注信息"
            v-model="form.remark"
            :maxlength="30"
            clearable
            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>
        <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>
      <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>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { mapMutations } from 'vuex'
import { formatTime } from '@/libs/tools'
export default {
  name: 'add-promotion',
  components: {
    Tables
  },
  computed: {
    title () {
      if (this.routeName === 'update_promotion') {
        return '编辑促销活动'
      } else if (this.routeName === 'promotion_detail') {
        return '促销活动详情'
      } else {
        return '新增促销活动'
      }
    },
    isDetail () {
      return this.routeName === 'promotion_detail'
    },
    isAdd () {
      return this.routeName === 'add_promotion'
    },
    isEdit () {
      return this.routeName === 'update_promotion'
    },
    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: '', // 促销类型
        promotionRule: {
          conditionVal: '',	// 促销条件值
          promotionVal: ''	// 促销优惠值
        },
        scope: '', // 活动范围
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        remark: '', // 备注信息
        rangeType: '', // 范围类型
        categoryList: [], // 类目信息
        promotionSkuList: [], // 指定商品
        updateTime: '', // 更新时间
        promotionId: ''
      },
      condition: {
        straightDown: '', // 直降
        full: '', // 满多少
        reduction: '', // 减多少
        everyFull: '', // 每满
        everyReduction: '', // 减多少
        discount: ''// 折扣
      },
      scopeList: [
        {
          value: '1',
          label: '全部 '
        },
        {
          value: '2',
          label: 'APP'
        },
        {
          value: '3',
          label: 'PC'
        },
        {
          value: '4',
          label: '微信小程序'
        }
      ],
      specifiedCategoryList: [
        {
          expand: true,
          children: [
            {
              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 (promotionId) {
      this.api({
        apiName: 'getPromotionDetail',
        dealUrl: (url) => {
          return `${url}/${promotionId}`
        },
        success: (res) => {
          let { name, type, promotionRule, scope, startTime, endTime, remark, rangeType, categoryList, promotionSkuList, updateTime, promotionId } = res.data
          this.form.name = name
          this.form.type = type
          this.form.promotionRule = promotionRule
          this.form.scope = JSON.stringify(scope)
          this.form.startTime = formatTime(startTime)
          this.form.endTime = formatTime(endTime)
          this.form.remark = remark
          this.form.rangeType = rangeType
          this.form.categoryList = categoryList
          if (this.form.type == 4) {
            this.condition.straightDown = this.form.promotionRule.promotionVal
          } else if (this.form.type == 2) {
            this.condition.full = this.form.promotionRule.conditionVal
            this.condition.reduction = this.form.promotionRule.promotionVal
          } else if (this.form.type == 3) {
            this.condition.everyFull = this.form.promotionRule.conditionVal
            this.condition.everyReduction = this.form.promotionRule.promotionVal
          } else if (this.form.type == 5) {
            this.condition.discount = this.form.promotionRule.promotionVal * 10
          }
          let obj = {}
          promotionSkuList.forEach(item => {
            obj = {
              goodsId: item.goodsId,
              promotionId: item.promotionId
            }
            this.form.promotionSkuList.push(obj)
          })
          this.form.updateTime = updateTime
          this.form.promotionId = promotionId
          if (this.form.rangeType == 2) {
            this.category()
          }
          if (this.form.rangeType == 3) {
            this.getGoods()
          }
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      let promotionId = this.$route.query.promotionId
      this.routeName = routeName
      if (routeName == 'update_promotion' || routeName == 'promotion_detail') {
        this.requestBannerDetail(promotionId)
      } else {
        this.loading = false
      }
    },
    handleCancel () {
      let title = '已取消'
      let route = this.$route
      let toRouteName = 'sales_promotion'
      this.closeTag({ route, toRouteName })
      this.$Notice.warning({ 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
            item.expand = true
          })
        }
      })
    },
    // 指定商品
    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.promotionSkuList.length; j++) {
              if (this.form.promotionSkuList[j].goodsId === this.tableData[i].goodsId) {
                this.tableData[i]._checked = true
                this.tableData[i].promotionId = this.form.promotionSkuList[j].promotionId
              }
            }
          }
        }
      })
    },
    handleSubmit () {
      let promotionSaveDTO = {
        name: this.form.name,
        type: this.form.type,
        promotionRule: this.form.promotionRule,
        scope: this.form.scope,
        startTime: new Date(this.form.startTime).getTime(),
        endTime: new Date(this.form.endTime).getTime() + 86399000,
        remark: this.form.remark,
        rangeType: this.form.rangeType,
        categoryList: this.form.categoryList,
        promotionSkuList: this.form.promotionSkuList,
        updateTime: this.form.updateTime,
        promotionId: this.form.promotionId
      }
      if (promotionSaveDTO.type == 4) {
        promotionSaveDTO.promotionRule.promotionVal = JSON.parse(this.condition.straightDown)
        promotionSaveDTO.promotionRule.conditionVal = 0
      } else if (promotionSaveDTO.type == 2) {
        promotionSaveDTO.promotionRule.conditionVal = JSON.parse(this.condition.full)
        promotionSaveDTO.promotionRule.promotionVal = JSON.parse(this.condition.reduction)
      } else if (promotionSaveDTO.type == 3) {
        promotionSaveDTO.promotionRule.conditionVal = JSON.parse(this.condition.everyFull)
        promotionSaveDTO.promotionRule.promotionVal = JSON.parse(this.condition.everyReduction)
      } else if (promotionSaveDTO.type == 5) {
        promotionSaveDTO.promotionRule.promotionVal = JSON.parse(this.condition.discount / 10)
        promotionSaveDTO.promotionRule.conditionVal = 0
      }
      if (promotionSaveDTO.name == '') {
        return this.$Notice.warning({ title: '请输入活动名称' })
      }
      if (promotionSaveDTO.type == '') {
        return this.$Notice.warning({ title: '请选择活动规则' })
      }
      if ((promotionSaveDTO.type == 2 || promotionSaveDTO.type == 3) && promotionSaveDTO.promotionRule.conditionVal == '') {
        return this.$Notice.warning({ title: '请输入活动条件值' })
      }
      if (promotionSaveDTO.promotionRule.promotionVal == '') {
        return this.$Notice.warning({ title: '请输入活动优惠值' })
      }
      if (isNaN(promotionSaveDTO.startTime) || isNaN(promotionSaveDTO.endTime)) {
        return this.$Notice.warning({ title: '请选择开始或结束时间' })
      }
      if (promotionSaveDTO.scope == '') {
        return this.$Notice.warning({ title: '请选择活动范围' })
      }
      if (promotionSaveDTO.remark == '') {
        return this.$Notice.warning({ title: '请输入备注信息' })
      }
      if (promotionSaveDTO.rangeType == '') {
        return this.$Notice.warning({ title: '请选择商品范围' })
      }

      if (promotionSaveDTO.categoryList.length == 0 && promotionSaveDTO.rangeType == 2) {
        this.$Notice.warning({ title: '请选择指定类目' })
        return false
      }
      if (promotionSaveDTO.promotionSkuList.length == 0 && promotionSaveDTO.rangeType == 3) {
        this.$Notice.warning({ title: '请选择指定商品' })
        return false
      }
      if (promotionSaveDTO.startTime > promotionSaveDTO.endTime) {
        this.$Notice.warning({ title: '开始时间不能大于结束时间' })
        this.form.startTime = ''
        this.form.endTime = ''
        return false
      }
      if (promotionSaveDTO.promotionRule.conditionVal < promotionSaveDTO.promotionRule.promotionVal && (promotionSaveDTO.type == 2 || promotionSaveDTO.type == 3)) {
        this.$Notice.warning({ title: '活动优惠金额不能大于条件金额' })
        this.condition.full = ''
        this.condition.reduction = ''
        this.condition.everyFull = ''
        this.condition.everyReduction = ''
        return false
      }
      // console.log('promotionSaveDTO', promotionSaveDTO)
      let apiName = this.isAdd ? 'addPromotion' : 'updatePromotion'
      let title = this.isAdd ? '添加成功！' : '编辑成功！'
      this.api({
        apiName,
        postdata: promotionSaveDTO,
        success: (res) => {
          // 关闭当前标签页
          let route = this.$route
          let toRouteName = 'sales_promotion'
          this.closeTag({ route, toRouteName })
          this.$Notice.success({ title })
        }
      })
    },
    // 获取选中商品数据
    btnSelect () {
      if (this.selectCount <= 0 && this.form.promotionSkuList.length <= 0) {
        this.$Message.warning('您还未选中数据')
        return false
      } else if (this.selectCount <= 0) {
        this.$Message.success('取消成功')
        this.form.promotionSkuList = this.selectList
      } else {
        this.$Message.success('添加商品成功')
        this.form.promotionSkuList = this.selectList
      }
    },
    changeSelect (e) {
      let obj = {}
      this.selectList = e.map(item => {
        if (item.promotionId != undefined) {
          obj = {
            goodsId: item.goodsId,
            promotionId: item.promotionId,
            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)
      })
    },
    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: 1200px;
    // position: relative;
    .loading-card {
        height: 100%;
      }
    .main_card{
      // overflow: hidden;
      .main_info{
      // float: left;
      // width: 50%;
      .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;
        align-items: center;
        margin: 10px 0 10px 100px;
      }
    }
  }
  // /deep/.vertical-center-modal{
  //       display: flex;
  //       align-items: center;
  //       justify-content: center;
  //       .ivu-modal{
  //           top: 0;
  //       }
  //   }
</style>
