<template>
  <a-modal
    centered
    class="noticeEdit-modal"
    :footer="null"
    :maskClosable="false"
    :title="modalTit"
    v-model="isShow"
    @cancel="isShow=false"
    width="68%">
    <!-- 表单 -->
    <div class="noticeEditContent">
      <a-spin :spinning="spinning" tip="Loading...">
        <a-form-model
          id="noticeEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-form-model-item label="公告标题" prop="title">
            <a-input
              id="noticeEdit-title"
              :maxLength="30"
              v-model.trim="form.title"
              placeholder="请输入公告标题(最多30个字符)"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="类别" prop="type">
            <v-select code="NOTITY_BIZ_TYPE" id="noticeEdit-type" v-model="form.type" allowClear placeholder="请选择类别"></v-select>
          </a-form-model-item>
          <a-form-model-item label="可见性" prop="toAppName">
            <v-select code="NOTITY_APP_TYPE" id="noticeEdit-toAppName" v-model="form.toAppName" allowClear placeholder="请选择可见性"></v-select>
          </a-form-model-item>
          <a-form-model-item label="发布时间" prop="releaseDate">
            <a-date-picker
              show-time
              id="noticeEdit-releaseDate"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="年/月/日 时/分/秒"
              :disabled-date="disabledDate"
              :disabledTime="disabledDateTime"
              v-model="form.releaseDate"/>
          </a-form-model-item>
          <a-form-model-item label="图片上传" prop="imgPaths">
            <Upload
              class="upload"
              id="noticeEdit-imgPaths"
              v-model="form.imgPaths"
              ref="imgPaths"
              :fileSize="10"
              :maxNums="5"
              @change="changeImage"
              listType="picture-card"></Upload>
            <span class="upload-desc">说明：单张大小小于10Mb，最多5张。</span>
          </a-form-model-item>
          <a-form-model-item label="附件上传" prop="attachList">
            <Upload
              id="noticeEdit-attachList"
              v-model="form.attachList"
              ref="attachList"
              :fileSize="10"
              :maxNums="3"
              fileType="*"
              uploadType="attach"
              :action="attachAction"
              @change="changeAttach"></Upload>
            <span class="upload-desc">说明：单个文件小于10Mb，最多3个附件。</span>
          </a-form-model-item>
          <a-form-model-item label="公告内容" prop="content">
            <editor id="noticeEdit-editor" ref="editor" class="noticeEdit-editor" @on-change="editorChange" :cache="false"></editor>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </div>
    <div class="btn-cont">
      <a-button id="noticeEdit-cancel-btn" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
      <a-button type="primary" id="noticeEdit-save-btn" @click="handleSave">保存</a-button>
    </div>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { VSelect, Upload } from '@/components'
import Editor from '@/components/WEeditor'
// 接口
import { noticeSave, noticeDetail } from '@/api/notice'
export default {
  name: 'ProductBrandEditModal',
  mixins: [commonMixin],
  components: { VSelect, Upload, Editor },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemId: {
      type: [Number, String],
      default: ''
    },
    nowData: {
      type: Object,
      default: null
    }
  },
  computed: {
    // 弹窗标题
    modalTit () {
      return (this.itemId ? '编辑' : '新增') + '公告'
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      // form表单label布局
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 }
      },
      // 提交参数
      form: {
        type: undefined, // 类别
        toAppName: undefined, // 可见性
        title: '', // 公告标题
        releaseDate: null, // 公告发布时间
        imgPaths: '', // 公告图片
        attachList: '', // 公告附件
        content: ''// 公告内容
      },
      attachList: [], // 附件集合
      // form表单验证规则
      rules: {
        type: [
          { required: true, message: '请选择类别', trigger: 'change' }
        ],
        toAppName: [
          { required: true, message: '请选择可见性', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        releaseDate: [
          { required: true, message: '请选择发布时间', trigger: 'change' }
        ]
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo' // 上传附件地址
    }
  },
  methods: {
    // 不可选日期
    disabledDate (current) {
      return current && current < moment().startOf('day')
    },
    // 禁用时间
    disabledDateTime (date) {
      if (!date) {
        date = moment()
      }
      return {
        disabledHours: () => this.getDisabledHours(date.format('YYYY-MM-DD HH:mm:ss')),
        disabledMinutes: () => this.getDisabledMinutes(date.format('YYYY-MM-DD HH:mm:ss')),
        disabledSeconds: () => this.getDisabledSeconds(date.format('YYYY-MM-DD HH:mm:ss'))
      }
    },
    // 禁用时间范围  时
    getDisabledHours (nowTime) {
      const todayDate = moment().format('YYYY-MM-DD HH:mm:ss')
      const time = nowTime.split(' ')
      const times = todayDate.split(' ')
      const timeArrs = times[1].split(':')
      const hours = []
      if (todayDate.split(' ')[0] == time[0]) {
        for (var i = 0; i < parseInt(timeArrs[0]); i++) {
          hours.push(i)
        }
      }
      return hours
    },
    // 禁用时间范围  分
    getDisabledMinutes (nowTime) {
      const todayDate = moment().format('YYYY-MM-DD HH:mm:ss')
      const time = nowTime.split(' ')
      const times = todayDate.split(' ')
      const timeArr = time[1].split(':')
      const timeArrs = times[1].split(':')
      const minutes = []
      if (todayDate.split(' ')[0] == time[0] && timeArrs[0] == timeArr[0]) {
        for (var i = 0; i < parseInt(timeArrs[1]); i++) {
          minutes.push(i)
        }
      }
      return minutes
    },
    // 禁用时间范围  秒
    getDisabledSeconds (nowTime) {
      const todayDate = moment().format('YYYY-MM-DD HH:mm:ss')
      const time = nowTime.split(' ')
      const times = todayDate.split(' ')
      const timeArr = time[1].split(':')
      const timeArrs = times[1].split(':')
      const second = []
      if (todayDate.split(' ')[0] == time[0] && timeArrs[0] == timeArr[0] && timeArrs[1] == timeArr[1]) {
        for (var i = 0; i <= parseInt(timeArrs[2]); i++) {
          second.push(i)
        }
      }
      return second
    },
    //  详情
    getDetail () {
      noticeDetail({ id: this.itemId }).then(res => {
        if (res.status == 200) {
          this.form = Object.assign(this.form, res.data)
          this.form.attachList = ''
          this.attachList = res.data.attachList
          this.form.releaseDate = moment(res.data.releaseDate, 'YYYY-MM-DD HH:mm:ss')
          this.$refs.imgPaths.setFileList(res.data.imgPaths)
          this.$refs.attachList.setFileList(res.data.attachList)
          this.$refs.editor.setHtml(res.data.content)
        }
      })
    },
    //  保存
    handleSave () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(_this.form))
          formData.releaseDate = moment(formData.releaseDate).format('YYYY-MM-DD HH:mm:ss')
          formData.id = _this.itemId ? _this.itemId : undefined
          formData.attachList = this.attachList
          _this.spinning = true
          noticeSave(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$emit('ok')
              _this.isShow = false
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    //  图片上传
    changeImage (file) {
      this.form.imgPaths = file
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
    },
    //  文本编辑器
    editorChange (html, text) {
      this.form.content = html
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.attachList = []
        this.$refs.imgPaths.setFileList('')
        this.$refs.attachList.setFileList([])
        this.$refs.editor.setHtml('')
        this.$refs.ruleForm.resetFields()
      }
    },
    itemId (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
      }
    }
  }
}
</script>

<style lang="less">
  .noticeEdit-modal{
    .ant-modal-body {
      padding: 20px 40px 24px;
    }
    .upload{
      width: 100%!important;
    }
    //  商品图片描述
    .upload-desc{
      font-size: 12px;
      color: #808695;
    }
    //  文本编辑器  工具栏样式换行
    .noticeEdit-editor{
      .w-e-toolbar{
        flex-wrap: wrap;
      }
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
    #noticeEdit-attachList{
      height: auto;
    }
    a{
      color: inherit;
    }
    .noticeEditContent{
      max-height:655px;
      overflow-y:scroll;
    }
  }
</style>
