<template>
  <van-popup
    v-model="dialogVisible"
    class="ibps-fullscreen-popup"
    position="bottom"
    @opened="loadFormData"
  >
    <div v-if="dialogLoading">
      <van-sticky>
        <van-nav-bar
          title="公告"
          left-arrow
          @click-left="onClose"
        >
          <template #left>
            <van-icon name="cross" class="ibps-nav-bar__close-icon" />
          </template>
        </van-nav-bar>
      </van-sticky>
      <div v-if="!readonly" class="ibps-fixed-toolbar">
        <van-form ref="form">
          <van-field
            v-model="form.title"
            label="标题"
            placeholder="请输入"
            clearable
            required
            input-align="right"
            name="title"
            autocomplete="off"
            :rules="[{ required: true, message: '必填' }]"
          />
          <ibps-radio
            v-model="form.publicItem"
            :options="publishOptions"
            :clearable="false"
            label="发布类型"
            placeholder="请选择"
          />
          <ibps-type-selector
            v-model="form.typeId"
            category-key="NOTICE_TYPE"
            label="类型"
            clearable
          />
          <ibps-user-selector
            v-model="userSelect"
            label="发布人"
            type="user"
            store="array"
            clearable
          />
          <van-field label="是否公共" input-align="right">
            <template #input>
              <van-switch
                v-model="form.public0"
                size="20"
                active-value="Y"
                inactive-value="N"
              />
            </template>
          </van-field>

          <ibps-user-selector
            v-show="form.public0==='N'"
            v-model="orgSelect"
            label="发布范围"
            type="org"
            store="array"
            clearable
          />
          <van-field
            v-model="form.author"
            label="作者"
            placeholder="请输入"
            input-align="right"
            clearable
            autocomplete="off"
            name="text"
          />
          <van-field
            v-model="form.key"
            label="关键字"
            placeholder="请输入"
            input-align="right"
            clearable
            name="text"
            autocomplete="off"
          />
          <ibps-date-picker
            v-model="form.publicDate"
            label="发布时间"
            placeholder="请选择"
            format="yyyy-MM-dd"
            clearable
          />
          <ibps-date-picker
            v-model="form.loseDate"
            label="过期时间"
            placeholder="请选择"
            format="yyyy-MM-dd"
            clearable
          />
          <ibps-uploader
            v-model="form.fileAttach"
            multiple
            label="附件"
            placeholder="请上传附件"
            clearable
          />
          <ibps-editor
            v-model="form.content"
            label="内容"
          />
          <ibps-toolbar
            :actions="actions"
          />
        </van-form>
      </div>

      <!--明细-->
      <div v-else class="ibps-notice-detail">
        <van-row>
          <van-col span="24" class="notice-title ibps-size-l_xx">{{ form.title }}</van-col>
          <van-col span="24" class="notice-detailed">
            <van-row gutter="5" type="flex" align="center">
              <!-- <van-col class="notice-time-horizon">{{ form.publicDate|dateFormat('yyyy-MM-dd') }} <span v-if="$utils.isNotEmpty(form.loseDate)"> ~ </span>{{ form.loseDate|dateFormat('yyyy-MM-dd') }}</van-col>
              <van-col class="notice-userName ibps-is-link">{{ form.userName }}</van-col> -->
              <van-col span="15">
                <span class="notice-time-horizon">
                  {{ form.publicDate|dateFormat('yyyy-MM-dd') }} <span v-if="$utils.isNotEmpty(form.loseDate)"> ~ </span>{{ form.loseDate|dateFormat('yyyy-MM-dd') }}
                </span>
                <span class="notice-userName ibps-is-link ibps-wingblank">{{ form.userName }}</span>
              </van-col>

              <!-- <van-col
                span="9"
                class="notice-publicItem"
                :style="{'color':form.publicItem==='important'?'#f56c6c':'#67c23a'}"
              > {{ form.publicItem| optionsFilter(publishOptions) }}</van-col> -->

              <van-col
                span="9"
                class="notice-publicItem"
              > <van-tag
                size="medium"
                :color="form.publicItem | optionsFilter(publishOptions,'color')"
                :text-color="form.publicItem | optionsFilter(publishOptions,'textColor')"
              >
                {{ form.publicItem| optionsFilter(publishOptions) }}</van-tag></van-col>

            </van-row>
          </van-col>
          <van-col span="24" class="notice-content">
            <ibps-editor
              v-model="form.content"
              label="内容"
              :have-padding="false"
              readonly
            />
          </van-col>
          <van-col span="24" class="notice-fileAttach">
            <div class="ibps-blank-bar" />
            <ibps-uploader
              v-model="form.fileAttach"
              label="附件"
              download
              :have-padding="false"
              multiple
              clearable
              readonly
            />
          </van-col>
        </van-row>
      </div>
    </div>
  </van-popup>
</template>

<script>
import { save, get } from '@/api/platform/system/news'
import navbar from '@/mixins/navbar'
import fecha from '@/utils/fecha'
import { publishOptions } from './constants'

import IbpsRadio from '@/components/ibps-radio'
import IbpsUserSelector from '@/business/platform/org/selector'
import IbpsDatePicker from '@/components/ibps-date-picker'
import IbpsUploader from '@/business/platform/file/uploader'
import IbpsEditor from '@/components/ibps-editor'
import IbpsTypeSelector from '@/business/platform/cat/type/selector'
import IbpsToolbar from '@/components/ibps-toolbar'

export default {
  components: {
    IbpsRadio,
    IbpsDatePicker,
    IbpsUserSelector,
    IbpsUploader,
    IbpsEditor,
    IbpsTypeSelector,
    IbpsToolbar
  },
  mixins: [navbar],
  props: {
    visible: Boolean,
    id: String,
    readonly: Boolean
  },
  data() {
    return {
      dialogVisible: false,
      dialogLoading: false,
      defaultForm: {
        id: '',
        picture: '',
        status: '',
        publicItem: 'notices',
        typeId: '',
        type: '',
        title: '',
        userId: '',
        userName: '',
        public0: 'Y',
        depId: '',
        depName: '',
        author: '',
        key: '',
        publicDate: '',
        loseDate: '',
        fileAttach: '',
        content: '',
        editorValue: ''
      },
      form: {},
      userSelect: [],
      orgSelect: [],
      publishOptions: publishOptions,
      actions: [
        {
          'name': this.$t('common.button.ts'),
          'type': 'default',
          'callback': this.saveDraft
        },
        {
          'name': this.$t('common.button.save'),
          'type': 'primary',
          'callback': this.saveData
        }]
    }
  },
  watch: {
    visible: {
      handler: function(val, oldVal) {
        this.dialogVisible = this.visible
        if (!val) {
          this.dialogLoading = false
        }
      },
      immediate: true
    },
    userSelect() {
      if (this.userSelect[0]) {
        this.form.userId = this.userSelect[0].id
        this.form.userName = this.userSelect[0].name
      }
    },
    orgSelect() {
      if (this.orgSelect[0]) {
        this.form.depId = this.orgSelect[0].id
        this.form.depName = this.orgSelect[0].name
      }
    }
  },
  created() {
    this.form = JSON.parse(JSON.stringify(this.defaultForm))
    this.form.userId = this.$store.getters.userId
    this.form.userName = this.$store.getters.name
  },
  methods: {
    loadFormData() {
      this.userSelect = []
      this.orgSelect = []
      this.form = JSON.parse(JSON.stringify(this.defaultForm))

      this.dialogLoading = true
      if (this.$utils.isEmpty(this.id)) {
        this.form.publicItem = 'notices'
        this.form.publicDate = fecha.format(new Date(), 'yyyy-MM-dd')
        this.userSelect = [{ 'id': this.$store.getters.userId, 'name': this.$store.getters.userName }]
        return
      }
      get({
        newsId: this.id
      }).then(response => {
        const data = response.data
        if (this.$utils.isNotEmpty(data.publicDate)) {
          data.publicDate = fecha.format(fecha.parse(data.publicDate, 'yyyy-MM-dd'), 'yyyy-MM-dd')
        }
        if (this.$utils.isNotEmpty(data.loseDate)) {
          data.loseDate = fecha.format(fecha.parse(data.loseDate, 'yyyy-MM-dd'), 'yyyy-MM-dd')
        }

        this.form = data
        if (this.$utils.isNotEmpty(this.form.userId) && this.$utils.isNotEmpty(this.form.userName)) {
          this.userSelect = [{ 'id': this.form.userId, 'name': this.form.userName }]
        }
        if (this.$utils.isNotEmpty(this.form.depId) && this.$utils.isNotEmpty(this.form.depName)) {
          this.orgSelect = [{ 'id': this.form.depId, 'name': this.form.depName }]
        }
      }).catch(error => {
        console.error(error)
      })
    },
    onBack() {
      this.$router.push({ name: 'notice' })
    },
    onClose() {
      this.$emit('close', false)
    },
    onSave() {
      const data = JSON.parse(JSON.stringify(this.form))
      const publicDate = new Date(this.form.publicDate).getTime() || ''
      const loseDate = new Date(this.form.loseDate).getTime() || ''
      // 检测失效日期是否发布日期在之前。
      if (publicDate > loseDate && loseDate !== '') {
        this.$notify({
          type: 'warning',
          message: '发布时间与失效时间范围不合法！'
        })
        return
      }

      if (this.$utils.isNotEmpty(data.publicDate)) {
        data.publicDate += ' 00:00:00'
      }
      if (this.$utils.isNotEmpty(data.loseDate)) {
        data.loseDate += ' 00:00:00'
      }
      save(data).then(response => {
        const message = this.form.status === 'drafts' ? `暂存公告成功！` : `保存公告成功！`
        this.$notify({
          type: 'success',
          message: message
        })
        this.onClose()
        this.$emit('callback', true)
        // this.$router.push({ name: 'notice' })
      }).catch(error => {
        console.error(error)
      })
    },
    saveDraft() {
      this.form.status = 'drafts'
      this.onSave()
    },
    saveData() {
      this.$refs.form.validate().then(() => {
        this.form.status = 'publish'
        this.onSave()
      }).catch(() => {
        this.$notify({
          type: 'warning',
          message: this.$t('common.formError')
        })
        this.$refs.form.scrollToField('title')
      })
    }
  }

}
</script>
<style lang="scss" sc>
 .ibps-notice-detail{
    .ibps-field__control--left{
      text-align: right;
    }
    .notice-title{
      flex: 1;
      -webkit-box-flex: 1;
      display: flex;
      box-sizing: border-box;
      width: 100%;
      padding: 10px 16px;
      overflow: hidden;
      color: #323233;
      font-size: 14px;
      line-height: 24px;
      background-color: #fff;
    }
    .notice-detailed{
      padding: 0px 16px;
      color: #969799;
      font-size: 12px !important;
      line-height: 18px;
    }
    .notice-publicItem{
      text-align:right;
    }
    .ibps-cell-wrapper{
      padding: 0;
    }
}
</style>
