<template>
  <div class="subPage">
    <form class="mainForm">
      <ul>
        <li class="flex-h">
          <span>选择案场：<em>*</em></span>
          <div class="flex-item">
            <div style="width:50%">
              <el-select v-model="cardInfo.CaseId" placeholder="请选择" @change="caseChange" :disabled="isEdit">
                <el-option
                  v-for="item in cases"
                  :key="item.CaseId"
                  :label="item.CaseName"
                  :value="item.CaseId">
                </el-option>
              </el-select>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>卡图片：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-upload
                class="avatar-uploader"
                action='string'
                :http-request="toolClass.upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <img v-if="cardInfo.Images" :src="cardInfo.Images[0].CardImageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>卡名称：<em>*</em></span>
          <div class="flex-item">
            <div style="width:200px;">
              <el-input
                placeholder="请输入"
                v-model="cardInfo.CardName"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>卡价格：<em>*</em></span>
          <div class="flex-item">
            <div style="width:200px;">
              <el-input
                :disabled="isEdit"
                placeholder="请输入"
                v-model="cardInfo.Price"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>总张数：<em>*</em></span>
          <div class="flex-item">
            <div style="width:200px;">
              <el-input
                :disabled="isEdit"
                placeholder="请输入"
                v-model="cardInfo.TotalCount"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>发送类型：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-radio v-model="cardInfo.SendType" label="channel" :disabled="isEdit">渠道</el-radio>
              <el-radio v-model="cardInfo.SendType" label="case" :disabled="isEdit">案场</el-radio>
              <el-radio v-model="cardInfo.SendType" label="system" :disabled="isEdit">系统</el-radio>
            </div>
          </div>
        </li>
        <li class="flex-h" v-if="cardInfo.SendType === 'channel'">
          <span>选择渠道：<em>*</em></span>
          <div class="flex-item">
            <div style="width:50%">
              <el-select v-model="cardInfo.ChannelId" placeholder="请选择" :disabled="isEdit">
                <el-option
                  v-for="item in channelList"
                  :key="item.ChannelId"
                  :label="item.ChannelName"
                  :value="item.ChannelId">
                </el-option>
              </el-select>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>目标课程：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-select v-model="cardInfo.Targets[0].TargetId" placeholder="请选择" v-if="!isEdit" @change="courseChange">
                <el-option
                  v-for="item in courseList"
                  :key="item.CourseId"
                  :label="item.CourseName"
                  :value="item.CourseId"
                  :disabled="item.Status !== 1">
                </el-option>
              </el-select>
              <span v-else style="line-height: 40px;">{{cardInfo.Targets[0].TargetName}}</span>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>卡有效时间：<em>*</em></span>
          <div class="flex-item">
            <div>
              <div class="addLine flex-h" style="align-item:center;margin-bottom:20px;">
                <el-date-picker
                  value-format="yyyy-MM-ddT00:00:00+08:00"
                  :disabled="isEdit"
                  v-model="cardInfo.StartDate"
                  :picker-options="pickerOptions"
                  type="date"
                  placeholder="选择起始日期">
                </el-date-picker>
                <span style="line-height:40px;">至</span>
                <el-date-picker
                  value-format="yyyy-MM-ddT23:59:59+08:00"
                  :disabled="true"
                  v-model="cardInfo.EndDate"
                  type="date"
                  placeholder="选择截止日期">
                </el-date-picker>
              </div>
            </div>
          </div>
        </li>
        <li class="flex-h" v-if="cardInfo.SendType !== 'case' && cardInfo.SendType !== 'system'">
          <span>视频：</span>
          <div class="flex-item">
            <div style="vertical-align: middle;">
              <a style="line-height: 40px;" v-if="videoOff" :href="cardInfo.VideoUrl" target="blank">{{cardInfo.VideoUrl}}</a>
              <el-upload
                class="avatar-uploader"
                action='string'
                :http-request="toolClass.upload"
                :show-file-list="false"
                :on-success="videoSuccess">
                <a style="line-height: 40px;padding: 0 10px;">{{videoOff ? '更换' : '添加'}}视频</a>
              </el-upload>
              <el-button v-if="videoOff" type="danger" @click="deleteVideo">删除视频</el-button>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>分享描述：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入"
                v-model="cardInfo.Share.CardShareInfo">
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>规则描述：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入"
                v-model="cardInfo.Share.CardUseRule">
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>使用说明：<em>*</em></span>
          <div class="flex-item">
            <div>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入"
                v-model="cardInfo.Share.CardUseInstruction">
              </el-input>
            </div>
          </div>
        </li>
        <li style="text-align:center">
          <el-button type="primary" size="mini" @click="submit">保存</el-button>
          <el-button type="danger" size="mini" @click="cancel">取消</el-button>
        </li>
      </ul>
    </form>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: mapCardActions } = createNamespacedHelpers('card')
const { mapState: mapChannelState, mapActions: mapChannelActions } = createNamespacedHelpers('channel')
const { mapActions: mapCourseActions } = createNamespacedHelpers('course')

export default {
  name: '',
  data () {
    return {
      date: '',
      courseList: [],
      videoOff: false,
      total: 0,
      type: this.$route.query.type,
      isEdit: !!this.$route.query.id,
      ChannelList: [], // 渠道列表
      TypeList: [], // 类型列表
      GoodsList: [], // 商品列表
      currentList: [{
        Name: 'ccc',
        Type: 'xxx'
      }], // 指定商品数据
      cardInfo: {
        CardName: '',
        SendType: '',
        VideoUrl: '',
        Price: ' ',
        StartDate: '',
        EndDate: '',
        TotalCount: '',
        CaseId: '',
        OrgId: '',
        Share: {
          CardShareInfo: '',
          CardUseRule: '',
          CardUseInstruction: '',
        },
        Images: null,
        Targets: [{}],
        ChannelId: ''
      },
      postData: {
        page: 1,
        pagesize: 10,
      },
    }
  },
  mounted () {
    this.$nextTick(function () {
      this.GetChannelListList({
        caseid: this.defaultCaseId,
        page: 1,
        pagesize: 10000
      }).then(() => {
        this.getCourseLister({
          caseid: this.defaultCaseId,
          page: 1,
          pagesize: 10000
        }).then((res) => {
          // console.log(JSON.stringify(res))
          this.courseList = res.list
          if (this.$route.query.id) {
            this.getCardById({
              id: this.$route.query.id
            }).then((res) => {
              // console.log(JSON.stringify(res))
              if (res.Card.CaseId !== '') {
                var aRes = res
                this.GetChannelListList({
                  caseid: res.Card.CaseId,
                  page: 1,
                  pagesize: 10000
                }).then((res) => {
                  this.cardInfo = aRes.Card
                  if (aRes.Card.StartDate === '0001-01-01T00:00:00Z' || aRes.Card.StartDate === '') {
                    this.cardInfo.StartDate = ''
                    this.cardInfo.EndDate = ''
                  }
                  if (aRes.Card.VideoUrl) {
                    this.videoOff = true
                  }
                  if (aRes.Card.Images === null) {
                    this.cardInfo.Images = [{
                      CardImageUrl: ''
                    }]
                  }
                  if (aRes.Card.StartDate !== '0001-01-01T00:00:00Z' && aRes.Card.StartDate !== '') {
                    this.date = [aRes.Card.StartDate, aRes.Card.EndDate]
                  } else {
                    this.date = ['', '']
                  }
                })
              } else {
                this.cardInfo = res.Card
                if (aRes.Card.StartDate === '0001-01-01T00:00:00Z' || aRes.Card.StartDate === '') {
                  this.cardInfo.StartDate = ''
                  this.cardInfo.EndDate = ''
                }
                if (res.Card.VideoUrl) {
                  this.videoOff = true
                }
                if (res.Card.Images === null) {
                  this.cardInfo.Images = [{
                    CardImageUrl: ''
                  }]
                }
                if (aRes.Card.StartDate !== '0001-01-01T00:00:00Z' && aRes.Card.StartDate !== '') {
                  this.date = [res.Card.StartDate, res.Card.EndDate]
                } else {
                  this.date = ['', '']
                }
              }
            })
          }
        })
      })
    })
  },
  computed: {
    ...mapChannelState({
      channelList: x => x.channelList,
    }),
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default,
      OrgId: x => x.app.user.OrgId,
    }),
    CaseId: {
      get () {
        return this.postData.caseid || this.defaultCaseId
      },
      set (val) {
        this.postData.caseid = val
      }
    },
    pickerOptions () {
      var beginDate = Date.now() - 24 * 60 * 60 * 1000
      var endDate = new Date(this.cardInfo.EndDate).getTime()
      return {
        disabledDate (time) {
          return time.getTime() < beginDate || time.getTime() > endDate
        }
      }
    },
  },
  methods: {
    ...mapCardActions([
      'addCard',
      'getCardById',
      'editCard',
    ]),
    ...mapCourseActions([
      'getCourseLister',
    ]),
    ...mapChannelActions([
      'GetChannelListList',
    ]),
    courseChange () {
      for (var n = 0; n < this.courseList.length; n++) {
        if (this.courseList[n].CourseId === this.cardInfo.Targets[0].TargetId) {
          this.cardInfo.EndDate = this.courseList[n].EndDate
        }
      }
    },
    caseChange () { // 选择案场
      this.GetChannelListList({
        caseid: this.cardInfo.CaseId,
        page: 1,
        pagesize: 10000
      })
      this.getCourseLister({
        caseid: this.cardInfo.CaseId,
        page: 1,
        pagesize: 10000
      }).then((res) => {
        this.courseList = res.list
      })
      this.cardInfo.Targets = [{
        TargetType: '',
        TargetId: '',
        TargetName: ''
      }]
      this.cardInfo.ChannelId = ''
    },
    deleteVideo () { // 删除视频
      this.cardInfo.VideoUrl = ''
      this.videoOff = false
    },
    videoSuccess (res, file) {
      this.videoOff = true
      this.cardInfo.VideoUrl = res.result.url
    },
    addGoods () { // 添加指定商品
      this.centerDialogVisible = true
    },
    checkInfo () { // 校验表单信息
      if (this.cardInfo.CaseId === '') {
        this.$message({
          type: 'error',
          message: '案场不能为空'
        })
        return false
      }
      if (this.cardInfo.Images === '') {
        this.$message({
          type: 'error',
          message: '卡图片不能为空'
        })
        return false
      }
      if (this.cardInfo.CardName === '') {
        this.$message({
          type: 'error',
          message: '卡名称不能为空'
        })
        return false
      }
      if (this.cardInfo.Price === '') {
        this.$message({
          type: 'error',
          message: '卡价格不能为空'
        })
        return false
      }
      if (this.cardInfo.TotalCount === '') {
        this.$message({
          type: 'error',
          message: '总张数不能为空'
        })
        return false
      }
      if (this.cardInfo.SendType === '') {
        this.$message({
          type: 'error',
          message: '发送类型不能为空'
        })
        return false
      }
      if (this.cardInfo.SendType === 'channel' && this.cardInfo.ChannelId === '') {
        this.$message({
          type: 'error',
          message: '渠道不能为空'
        })
        return false
      }
      if (this.cardInfo.Targets[0].TargetId === '') {
        this.$message({
          type: 'error',
          message: '目标课程不能为空'
        })
        return false
      }
      if (this.cardInfo.StartDate === '') {
        this.$message({
          type: 'error',
          message: '开始时间不能为空'
        })
        return false
      }
      if (this.cardInfo.EndDate === '') {
        this.$message({
          type: 'error',
          message: '截止时间不能为空'
        })
        return false
      }
      // if (this.cardInfo.SendType === 'channel' && this.cardInfo.VideoUrl === '') {
      //   this.$message({
      //     type: 'error',
      //     message: '视频不能为空'
      //   })
      //   return false
      // }
      if (this.cardInfo.Share.CardShareInfo === '') {
        this.$message({
          type: 'error',
          message: '分享描述不能为空'
        })
        return false
      }
      if (this.cardInfo.Share.CardUseRule === '') {
        this.$message({
          type: 'error',
          message: '使用规则不能为空'
        })
        return false
      }
      if (this.cardInfo.Share.CardUseInstruction === '') {
        this.$message({
          type: 'error',
          message: '使用说明不能为空'
        })
        return false
      }
      return true
    },
    submit () { // 保存
      console.log(this.cardInfo.StartDate, this.cardInfo.EndDate)
      if (this.$route.query.id) {
        // if (this.date !== '') {
        //   this.cardInfo.StartDate = this.date[0]
        //   this.cardInfo.EndDate = this.date[1]
        // }
        this.courseList = this.courseList || []
        for (var x = 0; x < this.courseList.length; x++) {
          if (this.courseList[x].CourseId === this.cardInfo.Targets[0].TargetId) {
            this.cardInfo.Targets[0].TargetType = this.courseList[x].CourseType
            this.cardInfo.Targets[0].TargetName = this.courseList[x].CourseName
          }
        }
        this.cardInfo.TotalCount = this.cardInfo.TotalCount - 0
        if (!this.checkInfo()) {
          return false
        }
        this.editCard(this.cardInfo).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.$router.push({ name: 'cardList' })
        })
      } else {
        this.cardInfo.OrgId = this.OrgId
        // if (this.date !== '') {
        //   this.cardInfo.StartDate = this.date[0]
        //   this.cardInfo.EndDate = this.date[1]
        // }
        this.courseList = this.courseList || []
        for (var n = 0; n < this.courseList.length; n++) {
          if (this.courseList[n].CourseId === this.cardInfo.Targets[0].TargetId) {
            this.cardInfo.Targets[0].TargetType = this.courseList[n].CourseType
            this.cardInfo.Targets[0].TargetName = this.courseList[n].CourseName
          }
        }
        this.cardInfo.TotalCount = this.cardInfo.TotalCount - 0
        if (!this.checkInfo()) {
          return false
        }
        this.addCard(this.cardInfo).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.$router.push({ name: 'cardList' })
        })
      }
    },
    cancel () { // 取消
      this.$router.push({ name: 'cardList' })
    },
    handleAvatarSuccess (res, file) {
      if ((this.cardInfo.Images || []).length > 0) {
        this.cardInfo.Images[0].CardImageUrl = res.result.url
      } else {
        this.cardInfo.Images = [{
          CardImageUrl: res.result.url,
        }]
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.addLine {
  > * {
    margin-right: 10px;
  }
}
.mainForm > ul > li > div > div > button {
  margin-top: 0;
}
</style>
