<template>
  <div>
    <xy-dialog ref="dialog" :width="70" :is-show.sync="isShow" :type="'form'" :title="type === 'add' ? '新增课程' : '编辑课程'"
      :form="form" :rules='rules' :hasIscheck="true" @mysubmit="mysubmit">
      <template v-slot:step>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold;display:none">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>
          </div>
          <div class="xy-table-item-content">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="课程信息"></el-step>
              <el-step title="报名信息"></el-step>
            </el-steps>
          </div>
        </div>
      </template>
      <template v-slot:name v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>课程名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.name" placeholder="请输入课程名称" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:type v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>课程类别：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.type" @change="changeType" placeholder="请选择类别" clearable style="width: 100%;">
              <el-option v-for="item in courseTypesList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:dateRange v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>开课日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker @change="changeDateRange" style="width: 100%;" v-model="form.dateRange" type="daterange"
              range-separator="至" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="开课日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:signRange v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>报名日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker @change="changeSignRange" style="width: 100%;" v-model="form.signRange" type="daterange"
              range-separator="至" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="报名开始日期"
              end-placeholder="报名截止日期">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:total v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>开课人数：
          </div>
          <div class="xy-table-item-content">
            <el-input style="width: 100%;" v-model="form.total" placeholder="请输入开课人数" clearable></el-input>
          </div>
        </div>
      </template>
      <template v-slot:status v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>状态：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width: 100%;" v-model="form.status" placeholder="请选择" clearable>
              <el-option v-for="item in course_status" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:is_arrange v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>是否排课：
          </div>
          <div class="xy-table-item-content">
            <el-radio-group style="width:100%" v-model="form.is_arrange">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template v-slot:is_fee v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>是否缴费：
          </div>
          <div class="xy-table-item-content">
            <el-radio-group style="width:100%" v-model="form.is_fee">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template v-slot:image_id v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold;">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>课程封面（680*380）：
          </div>
          <div class="xy-table-item-content">
            <el-upload :action="action" class='upload-demo' :on-exceed="onExceed" :limit="1" list-type="picture-card"
              :file-list="imgList" ref="pictureUpload" :before-upload="beforeUpload" :auto-upload="true"
              :on-success="uploadSuccess" :on-remove="uploadRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:publicize_ids v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold;">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>课程宣传页（宽750）：
          </div>
          <div class="xy-table-item-content">
            <el-upload :action="action" multiple class='upload-demo' list-type="picture-card" :file-list="publicizeList"
              ref="pictureUpload" :auto-upload="true" :on-success="uploadSuccesspublic" :on-remove="uploadRemovepublic">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:content v-if="active===0">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>课程简介：
          </div>
          <div class="xy-table-item-content">
            <my-tinymce v-if="showTinymce" @input="saveContent" :value="form.content"></my-tinymce>
          </div>
        </div>
      </template>

      <!-- 自定义报名 表单 -->
      <template v-slot:applylabel v-if="active===1">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold;display:none">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>：
          </div>
          <div class="xy-table-item-content" style="min-height: 300px;">
            <div>
              <el-dialog id="template-dialog" :title="'模板表单'"
                style="position: relative; inset: 0 0 0 0; height: 100%;padding:20px 0" width="90%" top="0px"
                :visible="true" :modal="false" :append-to-body="false" :show-close="false"
                :modal-append-to-body="false">
                <template v-slot:title>
                  <Button v-if="formList.length>0" ghost type="primary" @click="editForm('editor')">编辑表单</Button>
                  <Button v-else ghost type="primary" @click="editForm('add')">新增表单</Button>
                </template>
                <el-form style="min-height: 300px;display: flex;flex-wrap: wrap;" label-width="80px"
                  label-position="right" size="small">
                  <el-divider>基础字段</el-divider>
                  <el-form-item :label="i.name" :required="
                      i.rule ? !!i.rule.includes('required') : false
                    " v-for="(i, index) in defaultFormList">
                    <el-input placeholder="基础字段" :disabled="true"></el-input>
                  </el-form-item>
                  <el-divider>选填字段</el-divider>
                  <el-form-item :label="i.name"
                     v-for="(i, index) in selectFormList">
                    <el-input placeholder="选填字段" :disabled="true"></el-input>
                  </el-form-item>
                  <el-divider>自定义字段</el-divider>
                  <el-form-item style="flex-basis: 100%;" :label="i.name || '字段名称'" :required="
                        i.rule ? !!i.rule.includes('required') : false
                      " v-for="(i, index) in formList">
                    <formSlotRender :config="i" :index="index"></formSlotRender>
                  </el-form-item>
                </el-form>
              </el-dialog>
            </div>
          </div>
        </div>
      </template>

      <template v-slot:footerContent>
        <Button ghost type="primary" v-if="active===1" @click="active=0">上一步</Button>
        <!-- <Button ghost type="primary" v-if="active===0" @click="next">下一步</Button> -->
        <Button type="primary" ghost @click="checkSubmit" v-if="active===0">保存并下一步</Button>
        <Button type="primary" @click="closeSubmit">关闭</Button>
      </template>


    </xy-dialog>

    <applyForm ref="applyForm" @refresh="getFormList"></applyForm>
  </div>
</template>

<script>
  import myMixins from "@/mixin/selectMixin.js";
  import formMixins from "@/mixin/formMixin.js";
  import {
    show,
    save
  } from "@/api/course/index.js"

  import {
    index as formIndex
  } from "@/api/course/form";
  import {
    deepCopy
  } from "@/utils";
  import applyForm from "../components/applyForm.vue";
  import formSlotRender from "@/views/system/components/formSlotRender.vue";
  export default {
    mixins: [myMixins,formMixins],
    components: {
      applyForm,
      formSlotRender
    },
    data() {
      return {
        isShow: false,
        type: 'add',
        active: 0,
        id: '',
        action: `${process.env.VUE_APP_UPLOAD_API}`,
        showTinymce: false,
        courseTypesList: [],
        imgList: [],
        publicizeList: [],
        form: {
          step: '', // 控制课程 课表
          name: '',
          type: '',
          dateRange: '',
          signRange: '',
          total: '',
          status: 0,
          is_arrange: 1,
          is_fee: 1,
          image_id: '',
          publicize_ids: [],
          content: '',
          applylabel: ''
        },
        rules: {
          name: [{
            required: true,
            message: '请输入标题'
          }],
          type: [{
            required: true,
            message: '请选择课程类别'
          }],
          image_id: [{
            required: true,
            message: '请上传课程封面'
          }],
          // content: [{
          //   required: true,
          //   message: '请输入课程简介'
          // }],
        },
        // 自定义表单
        selectForm: {
          page: 1,
          page_size: 999,
          sort_name: 'sort',
          sort_type: 'ASC'
        },
        formList: []
      }
    },
    created() {},
    methods: {

      changeType(e) {
        if (e == 1) {
          this.form.is_arrange = 1
          this.form.is_fee = 1
        } else {
          this.form.is_arrange = 0
          this.form.is_fee = 0
        }
      },
      saveContent(e) {
        this.form.content = e
      },
      changeDateRange(e) {
        if (e) {
          this.form.start_date = e[0]
          this.form.end_date = e[1]
        } else {
          this.form.start_date = ''
          this.form.end_date = ''
        }
      },
      changeSignRange(e) {
        if (e) {
          this.form.sign_start_date = e[0]
          this.form.sign_end_date = e[1]
        } else {
          this.form.sign_start_date = ''
          this.form.sign_end_date = ''
        }
      },
      beforeUpload(file) {
        console.log(file)
        const isImage = file.type.includes('image');
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isImage) {
          this.$message.error('请上传正确的图片格式文件');
        }
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过2MB');
        }
        return isImage && isLt2M;
      },
      onExceed(file, fileList) {
        this.$Message.warning("课程封面只需上传一张")
      },
      uploadSuccess(response, file, fileList) {
        this.form.image_id = response.id
        this.imgList = fileList
      },
      uploadRemove(file, fileList) {
        this.imgList = fileList
        this.form.image_id = ''
      },

      uploadSuccesspublic(response, file, fileList) {
        this.publicizeList = fileList
      },
      uploadRemovepublic(file, fileList) {
        this.publicizeList = fileList
      },

      // 验证form提交规则
      mysubmit(e) {
        if (e) {
          this.submit()
        }
      },
      checkSubmit() {
        this.$refs.dialog.submit(true)
      },
      compareTime(date,sign){
        let date1 = this.$moment(date)
        let sign1 = this.$moment(sign)
        return sign1.isBefore(date1)
      },
      submit() {
        if (this.id) {
          this.form.id = this.id
        }
        // 报名截止时间 不能晚于 日程开始时间
        if(this.form.start_date && this.form.sign_end_date){
          if(!this.compareTime(this.form.start_date,this.form.sign_end_date)){
            this.$Message.warning("报名截止时间不能晚于课程开始时间")
            return
          }
        }
        // return
        let pubFiles = []
        if (this.publicizeList.length > 0) {
          this.publicizeList.map(item => {
            if (item.response) {
              pubFiles.push(item.response.id)
            } else {
              pubFiles.push(item.id)
            }
          })
        }
        this.form.publicize_ids = pubFiles
        this.form.publicize = []
        save({
          ...this.form
        }).then(res => {
          this.$message({
            type: 'success',
            message: '保存课程成功'
          })
          this.id = res.id
          this.$emit('refresh')
          this.active = 1
          // this.active = 1

        })
      },
      closeSubmit() {
        this.isShow = false
        this.$emit('refresh')
      },
      getDetail() {
        show({
          id: this.id,
          show_relation: ['image']
        }).then(res => {
          this.form = this.base.requestToForm(res, this.form)
          if (res.image) {
            this.imgList.push(res.image)
          }
          this.publicizeList = res.publicize
          this.form.dateRange = [res.start_date, res.end_date]
          this.form.signRange = [res.sign_start_date, res.sign_end_date]
          this.form.status = res.status ? res.status : 0
          this.form.is_arrange = res.is_arrange ? res.is_arrange : 0
          this.form.is_fee = res.is_fee ? res.is_fee : 0
          this.showTinymce = true
        })
      },
      // 下一步
      next() {
        if (this.id) {
          this.active = 1
        } else {
          this.$Message.warning("请先保存课程信息")
        }
      },
      // 获取自定义表单列表
      async getFormList() {
        const res = await formIndex({
          filter: [{
            key: 'course_id',
            op: 'eq',
            value: this.id
          }],
          ...this.selectForm
        })
        this.formList = res.data
      },
      // 打开自定义表单
      editForm(type, id) {
        // this.$refs.applyForm.formList = deepCopy(this.formList)
        this.$refs.applyForm.course_id = this.id
        this.$refs.applyForm.dialogVisible = true
      }


    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
            this.getFormList()
          } else {
            this.showTinymce = true
          }
        } else {
          this.id = ''
          this.showTinymce = false
          this.imgList = []
          this.publicizeList = []
          this.active = 0
          this.formList = []
          this.form = {
            step: '', // 控制课程 课表
            name: '',
            type: '',
            dateRange: '',
            signRange: '',
            total: '',
            status: 0,
            is_arrange: 1,
            is_fee: 1,
            image_id: '',
            publicize_ids: [],
            content: '',
            applylabel: ''
          }
          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .content,
  ::v-deep .step,
  ::v-deep .applylabel,
  ::v-deep .image_id,
  ::v-deep .publicize_ids {
    flex-basis: 100%;
  }

  ::v-deep .status,
  ::v-deep .is_arrange,
  ::v-deep .is_fee,
  {
  flex-basis: 33%;
  }

  ::v-deep .el-step.is-simple .el-step__head {
    display: flex
  }
</style>
