<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 :disabled="id && id !== ''" v-model="CaseId" placeholder="请选择" @change="caseChange">
                <el-option
                  key="all"
                  label="全部案场"
                  value="all">
                </el-option>
                <el-option
                  v-for="item in caseList"
                  :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 style="width:50%">
              <el-input
                placeholder="请输入名称"
                v-model="detail.Name"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>标题：</span>
          <div class="flex-item">
            <div style="width:50%">
              <el-input
                placeholder="请输入标题"
                v-model="detail.Title"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>图片：<em>*</em></span>
          <div class="flex-item">
            <el-upload
              class="avatar-uploader"
              action='string'
              :http-request="toolClass.upload"
              :show-file-list="false"
              :on-success="handleImgSuccess">
              <img v-if="imgShow" :src="imgShow" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </li>
        <li class="flex-h">
          <span>详细图片：<em>*</em></span>
          <div class="flex-item">
            <el-upload
              class="avatar-uploader"
              action='string'
              :http-request="toolClass.upload"
              :show-file-list="false"
              :on-success="handleDetailImgSuccess">
              <img v-if="detailImgShow" :src="detailImgShow" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </li>
        <li class="flex-h">
          <span>专题简介：<em>*</em></span>
          <div class="flex-item">
            <div style="width:50%">
              <el-input
                placeholder="请输入专题简介"
                v-model="detail.DetailContent"
                type='textarea'
                :autosize="{ minRows: 3, maxRows: 5}"
                clearable>
              </el-input>
            </div>
          </div>
        </li>
        <li class="flex-h">
          <span>展示课程：<em>*</em></span>
          <div class="flex-item">
            <div style="width:50%" class="radio">
              <el-radio v-model="detail.IsAllCourse" :label='1' >全部课程</el-radio>
              <el-radio v-model="detail.IsAllCourse" :label='0' >指定课程</el-radio>
            </div>
          </div>
        </li>
        <li class="flex-h" v-if="detail.IsAllCourse === 0">
          <el-table
            :data="detail.Courses"
            stripe
            style="width: 100%">
            <el-table-column
              prop="CourseName"
              label="课程名称">
            </el-table-column>
            <el-table-column
              prop="BeginDate"
              label="课程开始时间">
              <template slot-scope="scope">
                <label v-if="scope.row.BeginDate !== '0001-01-01T00:00:00Z'">{{toolClass.dateFormat(scope.row.BeginDate,'yyyy-MM-dd')}}</label>
                <label v-else>-</label>
              </template>
            </el-table-column>
            <el-table-column
              prop="EndDate"
              label="课程结束时间">
              <template slot-scope="scope">
                <label v-if="scope.row.EndDate !== '0001-01-01T00:00:00Z'">{{toolClass.dateFormat(scope.row.EndDate,'yyyy-MM-dd')}}</label>
                <label v-else>-</label>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="450">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
            <el-button type="primary" size="mini" @click="coursesShow">新增</el-button>
        </li>
        <li class="flex-h">
          <span>是否前台展示：<em>*</em></span>
          <div class="flex-item">
            <div style="width:50%" class="radio">
              <el-radio v-model="detail.Status" :label='1' >是</el-radio>
              <el-radio v-model="detail.Status" :label='0' >否</el-radio>
            </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>
    <el-dialog
      title="选择课程"
      :visible.sync="selCourseVisible"
      width="500px"
      center>
      <div>
        <el-table
          ref="courseTable"
          :data="coursesList"
          tooltip-effect="dark"
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="CourseName"
            label="课程名称">
          </el-table-column>
          <el-table-column
            prop="BeginDate"
            label="课程开始时间">
            <template slot-scope="scope">
              <label v-if="scope.row.BeginDate !== '0001-01-01T00:00:00Z'">{{toolClass.dateFormat(scope.row.BeginDate,'yyyy-MM-dd')}}</label>
              <label v-else>-</label>
            </template>
          </el-table-column>
          <el-table-column
            prop="EndDate"
            label="课程结束时间">
            <template slot-scope="scope">
              <label v-if="scope.row.EndDate !== '0001-01-01T00:00:00Z'">{{toolClass.dateFormat(scope.row.EndDate,'yyyy-MM-dd')}}</label>
              <label v-else>-</label>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="postData.page"
        :page-size="postData.pagesize"
        layout="prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selCourseVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCourseOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapState } from 'vuex'

const { mapState: mapCaseState, mapActions: mapCaseActions } = createNamespacedHelpers('cmscase')
const { mapState: mapCourseState, mapActions: mapCourseActions } = createNamespacedHelpers('course')

export default {
  name: '',
  data () {
    return {
      id: '',
      limit: 1,
      // imgs: null,
      // detailimgs: null,
      img: '',
      detailimg: '',
      selCourseVisible: false,
      selCourseList: [],
      postData: {
        page: 1,
        pagesize: 6
      },
      total: 0,
    }
  },
  components: {},
  computed: {
    ...mapState({
      caseList: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default,
      OrgId: x => x.app.user.OrgId
    }),
    ...mapCaseState({
      detail: x => x.caseInfo,
    }),
    ...mapCourseState({
      courses: x => x.courseList,
    }),
    CaseId: {
      get () {
        return this.detail.CaseId || this.caseid
      },
      set (val) {
        this.UpdateInfo({ ...this.detail, CaseId: val })
        this.getCourse()
      }
    },
    imgShow () {
      return this.img || ((this.detail.CmsCaseImgs || []).filter(x => x.ImageType === 'cover')[0] || {}).CaseImageUrl
    },
    detailImgShow () {
      return this.detailimg || ((this.detail.CmsCaseImgs || []).filter(x => x.ImageType === 'detail')[0] || {}).CaseImageUrl
    },
    coursesList () {
      return (this.courses.list || []).map(x => {
        return {
          CourseId: x.CourseId,
          CourseName: x.CourseName,
          BeginDate: x.BeginDate,
          EndDate: x.BeginDate
        }
      })
    },
  },
  methods: {
    ...mapCaseActions([
      'GetCaseInfo',
      'AddCaseInfo',
      'SetNull',
      'UpdateInfo',
    ]),
    ...mapCourseActions([
      'GetCourseList',
    ]),
    caseChange () {
      this.selCourseList = []
      this.detail.Courses = []
    },
    checkFn (arr) {
      for (var n = 0; n < arr.length; n++) {
        if (arr[n].type === 'isNull' && !arr[n].target) {
          this.$message({
            message: arr[n].errorMsg,
            type: 'error'
          })
          return false
        }
      }
      return true
    },
    handleCurrentChange (val) {
      this.postData.page = val
      this.getCourse()
    },
    submit () {
      var checkOff = this.checkFn([{
        target: Boolean(this.CaseId || ''),
        errorMsg: '对应案场不能为空',
        type: 'isNull'
      }, {
        target: Boolean(this.detail.Name || ''),
        errorMsg: '名称不能为空',
        type: 'isNull'
      }, {
        target: Boolean(this.imgShow || ''),
        errorMsg: '图片不能为空',
        type: 'isNull'
      }, {
        target: Boolean(this.detailImgShow || ''),
        errorMsg: '详细图片不能为空',
        type: 'isNull'
      }, {
        target: Boolean(this.detail.DetailContent || ''),
        errorMsg: '专题简介不能为空',
        type: 'isNull'
      }, {
        target: Boolean(String(this.detail.IsAllCourse) || ''),
        errorMsg: '展示课程不能为空',
        type: 'isNull'
      }, {
        target: Boolean(String(this.detail.Status) || ''),
        errorMsg: '是否前台展示不能为空',
        type: 'isNull'
      }])
      if (!checkOff) {
        return false
      }
      if (this.detail.IsAllCourse === 0 && !this.detail.Courses.length) {
        this.$message({
          message: '选择指定课程不能为空',
          type: 'error'
        })
        return false
      }
      const courseids = (this.detail.Courses || []).map(x => x.CourseId).join(',')
      if (this.id === '') {
        this.detail.OrgId = this.OrgId
        // console.log(JSON.stringify({ ...this.detail, OrgId: this.OrgId, imgs: this.imgShow, detailimgs: this.detailImgShow, courseids }))
        this.AddCaseInfo({ ...this.detail, OrgId: this.OrgId, imgs: this.imgShow, detailimgs: this.detailImgShow, courseids }).then((res) => {
          this.afterSave()
        })
      } else {
        // console.log(JSON.stringify({ ...this.detail, OrgId: this.OrgId, imgs: this.imgShow, detailimgs: this.detailImgShow, courseids }))
        this.AddCaseInfo({ ...this.detail, imgs: this.imgShow, detailimgs: this.detailImgShow, courseids }).then((res) => {
          this.afterSave()
        })
      }
    },
    afterSave () {
      this.$message({
        message: '保存成功',
        type: 'success',
        duration: 1000
      })
      this.$router.push({ name: 'indexCase' })
    },
    cancel () {
      this.$router.go(-1)
    },
    getDetail () {
      this.GetCaseInfo({ id: this.id })
    },
    getCourse () {
      this.GetCourseList({ caseid: this.CaseId === 'all' ? '' : this.CaseId, ...this.postData }).then((res) => {
        this.postData.page = res.page
        this.total = res.pagenum
      })
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.courseTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.courseTable.clearSelection()
      }
    },
    addCourse () {
      this.GetCourseList({ caseid: this.CaseId === 'all' ? '' : this.CaseId, page: 1, pagesize: 100, callback: this.coursesShow })
    },
    coursesShow () {
      this.selCourseList = this.detail.Courses || []
      this.selCourseVisible = true
      setTimeout(() => {
        this.toggleSelection(this.coursesList.filter(x => (this.selCourseList || []).filter(y => y.CourseId === x.CourseId).length > 0))
      }, 30)
    },
    handleSelectionChange (val) {
      this.selCourseList = val
    },
    addCourseOk () {
      this.UpdateInfo({ ...this.detail, Courses: this.selCourseList })
      this.selCourseVisible = false
    },
    deleteItem (row) {
      this.UpdateInfo({ ...this.detail, Courses: this.detail.Courses.filter(x => x.CourseId !== row.CourseId) })
    },
    handleImgSuccess (res, file) {
      this.img = res.result.url
    },
    handleDetailImgSuccess (res, file) {
      this.detailimg = res.result.url
    }
  },
  mounted () {
    this.getCourse()
    const { id } = this.$route.query
    this.id = id
    if (id && id !== '') {
      this.getDetail()
    } else {
      this.SetNull()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
</style>
