<template>
    <div class="add-integral-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 || isEdit"
          />
        </div>
        <div class="item">
          <label class="label">积分：</label>
          <Tag>平台积分</Tag>
        </div>
        <div class="item">
          <label class="label">返现数量：</label>
          <Input
            placeholder="请输入返现的积分数量"
            v-model="form.num"
            :maxlength="30"
            style="width: 400px"
            :readonly="isDetail"
          />
        </div>
         <div class="item">
          <label class="label">返现条件：</label>
          <RadioGroup v-model="form.returnCondition">
            <Radio :disabled="isDetail" :label="1" style="width:200px">
                每<Input style="width: 60px" v-model="condition.everyGoods" :readonly="isDetail"></Input>个商品
            </Radio>
            <Radio :disabled="isDetail" :label="2" style="width:200px">
                 每<Input style="width: 60px" v-model="condition.everyMoney" :readonly="isDetail"></Input>元可用
            </Radio>
          </RadioGroup>
        </div>
        <div class="item">
          <label class="label">有效时间：</label>
          <Row class="time">
            <Col>
              <DatePicker type="date" :readonly="isDetail" :options="drawStartOption" v-model="form.effectiveStartTime" placeholder="请选择开始时间" style="width:190px"></DatePicker>
            </Col>
            <span>至</span>
            <Col>
              <DatePicker type="date" :readonly="isDetail" :options="drawEndOption" v-model="form.effectiveEndTime"  placeholder="请选择结束时间" style="width:190px"></DatePicker>
            </Col>
          </Row>
        </div>
         <div class="item">
          <label class="label">备注信息：</label>
          <Input
            placeholder="请输入备注信息"
            v-model="form.remarks"
            :maxlength="30"
            style="width: 400px"
            type="textarea"
            :rows="3"
            :readonly="isDetail"
          />
        </div>
        <div class="item">
          <label class="label">商品范围：</label>
          <RadioGroup v-model="form.goodsRange">
            <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" 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"
            :loading="submitLoading"
          >确定</Button
          >
        </div>
      </div>
       <Card class="range_type" v-if="this.form.goodsRange == 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.goodsRange == 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 { mapMutations } from 'vuex'
import Tables from '_c/tables'
import { formatTime } from '@/libs/tools'
import mixin from '@/libs/mixin'
export default {
  mixins: [mixin],
  components: {
    Tables
  },
  computed: {
    title () {
      if (this.routeName === 'update_integral') {
        return '编辑积分返现'
      } else if (this.routeName === 'integral_detail') {
        return '积分返现详情'
      } else {
        return '新增积分返现'
      }
    },
    isDetail () {
      return this.routeName === 'integral_detail'
    },
    isAdd () {
      return this.routeName === 'add_integral'
    },
    isEdit () {
      return this.routeName === 'update_integral'
    },
    apiToken () {
      return this.$store.state.admin.apiToken
    }
  },
  data () {
    return {
      routeName: '',
      loading: false,
      tableData: [], // 商品列表
      goods: '',
      form: {
        name: '',
        returnCondition: '',
        condition: '',
        num: '',
        effectiveStartTime: '', // 开始时间
        effectiveEndTime: '', // 结束时间
        remarks: '', // 备注信息
        goodsRange: '', // 范围类型
        categoryList: [], // 类目信息
        goodsList: [], // 指定商品
        updateTime: '',
        returnId: ''
      },
      condition: {
        everyGoods: '',
        everyMoney: ''
      },
      submitLoading: false,
      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() - 86400000
        }
      },
      drawEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now()
        }
      }
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    requestDetail (returnId) {
      this.loading = true
      this.api({
        apiName: 'detailIntegralReturn',
        postdata: returnId,
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          let { name, num, returnCondition, conditionVal, effectiveStartTime, effectiveEndTime, remarks, goodsRange, categoryList, goodsList, returnId, updateTime } = res.data
          this.form.name = name
          this.form.num = num
          this.form.returnCondition = returnCondition
          if (returnCondition == 1) {
            this.condition.everyGoods = conditionVal
          } else {
            this.condition.everyMoney = conditionVal
          }
          this.form.effectiveStartTime = formatTime(effectiveStartTime)
          this.form.effectiveEndTime = formatTime(effectiveEndTime)
          this.form.remarks = remarks
          this.form.goodsRange = goodsRange
          this.form.categoryList = categoryList
          let obj = {}
          goodsList.forEach(item => {
            obj = {
              goodsId: item.goodsId,
              returnId: item.returnId
            }
            this.form.goodsList.push(obj)
          })
          this.form.returnId = returnId
          this.form.updateTime = updateTime
          if (goodsRange == 2) {
            this.category()
          }
          if (goodsRange == 3) {
            this.getGoods()
          }
        }
      })
    },
    handleCancel () {
      let title = '已取消'
      let route = this.$route
      let toRouteName = 'integral_recurrence'
      this.closeTag({ route, toRouteName })
      this.$Notice.success({ title })
    },
    checkForm () {
      let { name, num, returnCondition, effectiveStartTime, effectiveEndTime, remarks, goodsRange, categoryList, goodsList, updateTime, returnId } = this.form
      let integralSaveDTO = {
        name,
        num,
        returnCondition,
        effectiveStartTime: new Date(effectiveStartTime).getTime(),
        effectiveEndTime: new Date(effectiveEndTime).getTime() + 86399000,
        remarks,
        goodsRange,
        categoryList,
        goodsList: goodsList.map((item) => {
          return item.goodsId
        }),
        updateTime,
        returnId
      }
      let errMsg = ''
      if (!integralSaveDTO.name) {
        return { errMsg: '请输入活动名称' }
      }
      if (!integralSaveDTO.num) {
        return { errMsg: '请输入返现数量' }
      }
      if (!returnCondition) {
        return { errMsg: '请选择返现条件' }
      }
      if (integralSaveDTO.returnCondition	== 1) {
        integralSaveDTO.conditionVal = this.condition.everyGoods
      } else {
        integralSaveDTO.conditionVal = this.condition.everyMoney
      }
      if (returnCondition == 1 && !this.condition.everyGoods) {
        return { errMsg: '请输入返现条件值' }
      }
      if (returnCondition == 2 && !this.condition.everyMoney) {
        return { errMsg: '请输入返现条件值' }
      }
      if (isNaN(integralSaveDTO.effectiveStartTime) || isNaN(integralSaveDTO.effectiveEndTime)) {
        return { errMsg: '请选择开始或结束时间' }
      }
      if (!integralSaveDTO.remarks) {
        return { errMsg: '请输入备注信息' }
      }
      if (!integralSaveDTO.goodsRange) {
        return { errMsg: '请选择商品范围' }
      }

      if (integralSaveDTO.categoryList.length == 0 && integralSaveDTO.goodsRange == 2) {
        return { errMsg: '请选择指定类目' }
      }
      if (integralSaveDTO.goodsList.length == 0 && integralSaveDTO.goodsRange == 3) {
        return { errMsg: '请选择指定商品' }
      }
      if (integralSaveDTO.effectiveStartTime > integralSaveDTO.effectiveEndTime) {
        effectiveStartTime = ''
        effectiveEndTime = ''
        return { errMsg: '开始时间不能大于结束时间' }
      }
      return { errMsg, integralSaveDTO }
    },
    handleSubmit () {
      let { errMsg } = this.checkForm()
      if (errMsg) {
        return this.$Message.warning(errMsg)
      }
      this.handleSubmitCallback()
      // this.getApiToken()
    },
    handleSubmitCallback () {
      let { integralSaveDTO } = this.checkForm()

      let apiName = this.isAdd ? 'addIntegralReturn' : 'editIntegralReturn'
      let title = this.isAdd ? '添加成功！' : '编辑成功！'
      this.submitLoading = true
      this.api({
        apiName,
        postdata: integralSaveDTO,
        apiToken: this.apiToken,
        success: (res) => {
          // 关闭当前标签页
          let route = this.$route
          let toRouteName = 'integral_recurrence'
          this.closeTag({ route, toRouteName })
          this.$Notice.success({ title })
        },
        complete: () => {
          this.submitLoading = false
        }
      })
    },
    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: 'integralReturnQueryByNameOrId',
        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.goodsList.length; j++) {
              if (this.form.goodsList[j].goodsId === this.tableData[i].goodsId) {
                this.tableData[i]._checked = true
                this.tableData[i].returnId = this.form.goodsList[j].returnId
              }
            }
          }
        }
      })
    },
    // 获取选中商品数据
    btnSelect () {
      if (this.selectCount <= 0 && this.form.goodsList.length <= 0) {
        this.$Message.warning('您还未选中数据')
        return false
      } else if (this.selectCount <= 0) {
        this.$Message.success('取消成功')
        this.form.goodsList = this.selectList
      } else {
        this.$Message.success('添加商品成功')
        this.form.goodsList = this.selectList
      }
    },
    changeSelect (e) {
      let obj = {}
      this.selectList = e.map(item => {
        if (item.returnId != undefined) {
          obj = {
            goodsId: item.goodsId,
            returnId: item.returnId,
            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
    }
  },
  mounted () {
    let routeName = this.$route.name
    let returnId = this.$route.query.returnId
    this.routeName = routeName
    if (routeName == 'update_integral' || routeName == 'integral_detail') {
      this.requestDetail(returnId)
    } else {
      this.loading = false
    }
  }
}
</script>
<style lang="less" scoped>
 .add-integral-page {
    height: 100%;
    .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: 30px;
          .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;
        margin-bottom: 25px;
      }
    }
      .range_type{
        width: 35%;
        float: left;
        margin-bottom: 10px;
      }
    }
  }
</style>
