<template>
  <div class="subPage">
    <form class="mainForm">
      <ul>
        <li class="flex-h">
          <span>对应案场：</span>
          <div class="flex-item">
            <div style="width:50%">
              <el-select v-model="CaseId" placeholder="请选择">
                <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>名称：</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>图片：</span>
          <div class="flex-item">
            <el-upload
              :action="$api.file.image.url"
              list-type="picture-card"
              :limit='limit'
              :file-list='imgsArr'
              :on-success="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-exceed="exceed">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </li>
        <li class="flex-h">
          <span>详细图片：</span>
          <div class="flex-item">
            <el-upload
              :action='$api.file.image.url'
              list-type="picture-card"
              :limit='limit'
              :file-list='detailimgsArr'
              :on-success="handlePictureCardPreviewDetail"
              :on-remove="handleRemoveDetail"
              :on-exceed="exceed">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </li>
        <li class="flex-h">
          <span>专题简介：</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>展示课程：</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>{{toolClass.dateFormat(scope.row.BeginDate,'yyyy-MM-dd')}}</label>
              </template>
            </el-table-column>
            <el-table-column
              prop="EndDate"
              label="课程结束时间">
              <template slot-scope="scope">
                <label>{{toolClass.dateFormat(scope.row.EndDate,'yyyy-MM-dd')}}</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>是否前台展示：</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>{{toolClass.dateFormat(scope.row.BeginDate,'yyyy-MM-dd')}}</label>
            </template>
          </el-table-column>
          <el-table-column
            prop="EndDate"
            label="课程结束时间">
            <template slot-scope="scope">
              <label>{{toolClass.dateFormat(scope.row.EndDate,'yyyy-MM-dd')}}</label>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <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,
      selCourseVisible: false,
      selCourseList: [],
    }
  },
  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()
      }
    },
    imgsArr: {
      get () {
        return this.imgs || (this.detail.CmsCaseImgs || []).filter(x => x.ImageType === 'cover').map(x => {
          return {
            url: x.CaseImageUrl,
            response: {
              result: {
                url: x.CaseImageUrl
              }
            }
          }
        })
      },
      set (val) {
        this.imgs = val
      }
    },
    detailimgsArr: {
      get () {
        return this.detailimgs || (this.detail.CmsCaseImgs || []).filter(x => x.ImageType === 'detail').map(x => {
          return {
            url: x.CaseImageUrl,
            response: {
              result: {
                url: x.CaseImageUrl
              }
            }
          }
        })
      },
      set (val) {
        this.detailimgs = val
      }
    },
    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',
    ]),
    submit () {
      const imgs = this.imgsArr.map(x => x.response.result.url).join(',')
      const detailimgs = this.detailimgsArr.map(x => x.response.result.url).join(',')
      const courseids = this.detail.Courses.map(x => x.CourseId).join(',')
      if (this.id === '') {
        this.detail.OrgId = this.OrgId
        this.AddCaseInfo({...this.detail, imgs, detailimgs, courseids}).then(res => {
          this.afterSave()
        })
      } else {
        this.AddCaseInfo({...this.detail, imgs, detailimgs, courseids}).then(res => {
          this.afterSave()
        })
      }
    },
    afterSave () {
      this.$message({
        message: '保存成功',
        type: 'success',
        duration: 1000
      })
      setTimeout(() => {
        this.$router.push({ name: 'indexCase' })
      }, 1000)
    },
    cancel () {
      this.$router.go(-1)
    },
    handlePictureCardPreview (res, file, fileList) {
      this.imgsArr = fileList
    },
    handleRemove (file, fileList) {
      this.imgsArr = fileList
    },
    handlePictureCardPreviewDetail (res, file, fileList) {
      this.detailimgsArr = fileList
    },
    handleRemoveDetail (file, fileList) {
      this.detailimgsArr = fileList
    },
    getDetail () {
      this.GetCaseInfo({id: this.id})
    },
    getCourse () {
      this.GetCourseList({caseid: this.CaseId, page: 1, pagesize: 100})
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.courseTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.courseTable.clearSelection()
      }
    },
    exceed () {
      this.$message({
        message: '超过可传的图片上限',
        type: 'info',
        duration: 1000
      })
    },
    addCourse () {
      this.GetCourseList({caseid: 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
      // this.UpdateInfo({...this.detail, Courses: 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)})
    }
  },
  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>
