<!-- 新闻管理 by wangshxc -->
<template>
  <div v-loading="listLoading">
    <!-- 页面title -->
    <div class="management">
      <div class="table-button float-right">
        <ws-button type="primary"
                   @click="submitDetail"
                   round>发布</ws-button>
        <ws-button round
                   @click="save"
                   type="primary"
                   class="mr10">保存</ws-button>
        <ws-button slot="reference"
                   type="primary"
                   class="mr10"
                   @click="toPreview"
                   round>预览</ws-button>
        <ws-button @click="goBack"
                   class="mr10"
                   round>返回</ws-button>
      </div>
    </div>
    <!--<detail-dialog v-if="newsFlag" @close="handleCloseDetail" :showFlag="newsFlag" :url="appendixPath"
                   :params="ruleForm"></detail-dialog>-->
    <ws-dialog title="预览"
               :visible.sync="newsFlag"
               :before-close="handleCloseDetail"
               width="820px"
               :close-on-click-modal="false">
      <div class="notice-details">
        <div class="notice-header-right"
             style="text-align: right;">
        </div>
        <div class="notice-header">
          <div class="notice-header-left">
            <div style="font-size: 16px;font-weight: bold;color: #333333;margin-top: 10px;"
                 :title='ruleForm.title'>{{ruleForm.title}}</div>
            <div class="text">
              <div class="time"
                   :title='ruleForm.issueUserName'
                   style="color: #333;font-weight: bold">{{ruleForm.issueUserName}}</div>
              <div class="time">{{ruleForm.createDate.substr(0,16)}}</div>
              <div class="time"
                   :title='ruleForm.typeName'> {{ruleForm.typeName}}</div>
            </div>
            <div class="text">
              <div class="time"
                   :title='ruleForm.websiteName'>{{ruleForm.websiteName}}</div>
              <div class="time">
                <a :href="ruleForm.websiteUrl"
                   :title='ruleForm.websiteUrl'
                   style="color: #1a61d5;"
                   target="_blank">{{ruleForm.websiteUrl}}</a>
              </div>
            </div>
            <div class="text">
              <div class="timeFw"
                   :title='ruleForm.tenantName'>{{ruleForm.tenantName}}</div>
            </div>
          </div>
        </div>
        <div class="notice-sub-header"
             v-if="appendixPath">
          <img :src="appendixPath">
        </div>
        <div class="notice-content">
          <div class="notice-content-html"
               v-html="ruleForm.content">{{ruleForm.content}}</div>
        </div>
      </div>
    </ws-dialog>
    <!--新增表单列表 Start-->
    <ws-form :model="ruleForm"
             :rules="rules"
             ref="ruleForm"
             label-width="120px"
             class="demo-ruleForm">
      <ws-form-item label="标题 :"
                    prop="title">
        <ws-input v-model="ruleForm.title"
                  class="title"
                  maxlength="100"
                  placeholder="请输入标题"></ws-input>
      </ws-form-item>
      <ws-form-item label="类型 :"
                    prop="typeId">
        <ws-select v-model="ruleForm.typeId"
                   @change="getnewTypeName(ruleForm.typeId)"
                   placeholder="请选择类型"
                   class="noticetype">
          <ws-option v-for="item in dynamicTags"
                     :key="item.parameterKey"
                     :label="item.parameterValue"
                     :value="item.parameterKey" />
        </ws-select>
      </ws-form-item>
      <ws-form-item label="推荐用户 :"
                    class="defaultNews"
                    prop="defaultNews">
        <ws-select v-model="ruleForm.defaultNews"
                   placeholder="请选择推荐顺序"
                   @change="defaultListChange"
                   class="noticetype">
          <ws-option v-for="item in defaultList"
                     :key="item.key"
                     :label="item.name"
                     :value="item.key" />
        </ws-select>
        <span class="content">
          选择新用户，默认新闻按发布时间倒叙，新注册用户首页只显示前两条。</span>
      </ws-form-item>
      <ws-form-item label="发布人 :">
        <ws-input v-model="ruleForm.issueUserName"
                  maxlength="50"
                  class="send"></ws-input>
      </ws-form-item>
      <ws-form-item label="发送范围 :">
        <ws-input v-model="ruleForm.tenantName"
                  :title="ruleForm.tenantName"
                  clearable
                  readonly
                  class="send input-range"
                  @focus="dialogFormVisible = true"
                  placeholder="请选择"></ws-input>
        <ws-dialog title="选择租户"
                   :close-on-click-modal="false"
                   :visible.sync="dialogFormVisible"
                   width="650px"
                   center>
          <div class="adddepartment">
            <div class="adddepartment1">
              <ws-tree :data="datalist"
                       :default-checked-keys="checkedKeys"
                       :default-expanded-keys="['YHCompId']"
                       show-checkbox
                       ref="tree"
                       node-key="id"
                       :props="defaultProps"
                       :render-after-expand="false"
                       @check-change="handleCheckChange">
              </ws-tree>
            </div>
            <div class="adddepartment2">
              <span class="adddepartment4">已选</span>
              <div class="adddepartment3"
                   v-for="item in selectList"
                   :key="item.id">
                <div class="adddepartmentLeft">
                  <span :title="item.name">{{ item.name }}</span>
                </div>
                <span class="adddepartmentDel"
                      @click="delShipSelect(item)">删除</span>
              </div>
            </div>
          </div>
          <span slot="footer"
                class="dialog-footer">
            <ws-button @click="dialogFormVisible = false">取消</ws-button>
            <ws-button type="primary"
                       @click="submitTree">确定</ws-button>
          </span>
        </ws-dialog>
      </ws-form-item>
      <ws-form-item label="是否按类型推送 :"
                    style="margin-bottom: 12px;">
        <ws-radio v-model="ruleForm.likeFlag"
                  :label="likeFlag">否</ws-radio>
        <ws-radio v-model="ruleForm.likeFlag"
                  :label="!likeFlag">是</ws-radio>
      </ws-form-item>
      <ws-form-item label="封面图片 :"
                    style="margin-bottom: 12px;">
        <ws-upload ref="upload"
                   :limit="1"
                   oss-key="test"
                   :appendix-ids="appendixIds"
                   accept=".jpg,.png"
                   table-name="announcement_issue_info" />
      </ws-form-item>
      <ws-form-item label="来源 :">
        <ws-input v-model="ruleForm.websiteName"
                  maxlength="100"
                  placeholder="请输入网站名称"
                  class="title"></ws-input>
        <ws-input v-model="ruleForm.websiteUrl"
                  maxlength="800"
                  placeholder="请输入网站地址"
                  class="title"></ws-input>
      </ws-form-item>
      <ws-form-item label="正文 :"
                    style="margin-bottom: 30px;height:400px; margin-top: 10px;"
                    prop="content">
        <Tinymce ref="editor"
                 table-name="announcement_issue_info"
                 oss-key="test"
                 v-model="ruleForm.content"
                 :height="400" />
      </ws-form-item>
    </ws-form>
  </div>
</template>

<script>
import Tinymce from '../../components/Tinymce';
import WsUpload from '../../components/WsUpload'
import { editIssueInfo, createIssueInfo, sendScope, queryCommonDetail, getNewType, getFileList } from '../../api/new'

export default {
  name: 'newAdd',
  components: {
    Tinymce,
    WsUpload,
  },
  data () {
    return {
      defaultList: [{
        key: '0',
        name: '老用户'
      }, {
        key: '1',
        name: '新用户'
      }],
      newsFlag: false,
      likeFlag: false,
      appendixPath: '',
      imageSrc: undefined,
      isLoading: false,
      listLoading: false,
      selectList: [],
      dynamicTags: [],
      appendixIds: '',
      ruleForm: {
        title: '',
        issueUserName: localStorage.getItem('ws-pf_userName'),
        ossCoverUrl: '',
        typeName: '',
        typeId: '',
        content: '',
        createDate: '',
        issueUserId: localStorage.getItem('ws-pf_userId'),
        isIssue: '',
        websiteUrl: '',
        websiteName: '',
        tenantId: '',
        tenantName: '',
        defaultNews: '0',
        likeFlag: false
      },
      words: '',
      wordsId: '',
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        typeName: [
          { required: true, message: '请选择公告类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入正文内容', trigger: 'blur' }
        ],
        defaultNews: [
          { required: true, message: '请选择推荐顺序', trigger: 'change' }
        ],
      },
      noticeTypeList: [],
      props: {
        label: 'name',
        children: 'zones'
      },
      count: 1,
      dialogFormVisible: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '200px',
      datalist: [],
      checkedKeys: [],
      check: [-1],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeDeleteData: [],
      treeCheckedData: [],
      deleteFlag: true
    };
  },
  created () {
    this.ruleForm.createDate = this.getTime()
    this.render()
  },
  methods: {
    //推荐用户的change事件
    defaultListChange () {
      console.log('1111')
      if (this.ruleForm.defaultNews === '1') {
        this.ruleForm.tenantName = ''
        this.checkedKeys = []
      } else {
        this.render()
      }
    },
    toPreview () {
      this.$refs.upload.handleSaveBill().then(res => {
        if (res) {
          let appendixIds = res
          getFileList({ appendixIds })
            .then(resp => {
              if (resp.data.length > 0) {
                this.appendixPath = this.$store.getters.baseInfo.fileUrl + resp.data[0].appendixPath
              }
            })
        }
      })
      this.newsFlag = true
    },
    handleCloseDetail () {
      this.newsFlag = false
    },
    getTime () {     	//获取时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth();
      var day = date.getDate();

      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();

      //这样写显示时间在1~9会挤占空间；所以要在1~9的数字前补零;
      if (hour < 10) {
        hour = '0' + hour;
      }
      if (minute < 10) {
        minute = '0' + minute;
      }
      if (second < 10) {
        second = '0' + second;
      }
      var x = date.getDay();//获取星期
      var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
      return time
    },
    // 初始化
    render () {
      // 设置类型
      getNewType({ constCode: 'NEWS_TYPE' }).then(response => {
        this.dynamicTags = response.data
      })

      // 获取发送范围
      sendScope().then(response => {
        let arr = response.data
        for (let i of arr) {
          for (let j of i.children) {
            j.parentName = i.name
          }
        }
        this.datalist = this._.cloneDeep(arr)
        if (!this.$route.query.id) {
          this.selectList = []
          this.ruleForm.tenantName = ''
          this.ruleForm.tenantId = ''
          for (let i of this.datalist) {
            for (let j of i.children) {
              this.selectList.push(j)
              this.checkedKeys.push(j.id)
              this.ruleForm.tenantName += j.name + ','
              this.ruleForm.tenantId += j.id + ','
            }
          }
        }
      })
      this.getList()

    },
    saveDetail () {
      saveFiles({ newAppendixs: this.newAppendixs }).then(res => {
        this.ruleForm.ossCoverUrl = res.data.join(',')
      })
    },
    getList () {
      if (this.$route.query.id) {
        this.selectList = []
        this.checkedKeys = []
        this.ruleForm.tenantName = ''
        this.ruleForm.tenantId = ''
        queryCommonDetail({ id: this.$route.query.id }).then(res => {
          this.ruleForm = res.data;
          this.appendixIds = res.data.ossCoverUrl;
          if (this.appendixIds) {
            let appendixIds = this.appendixIds
            getFileList({ appendixIds })
              .then(resp => {
                if (resp.data.length > 0) {
                  this.appendixPath = resp.data[0].appendixPath
                }
              })
          }
          if (this.ruleForm.tenantName) {
            let tenantNameArr = this.ruleForm.tenantName.split(',')
            let tenantIdArr = this.ruleForm.tenantId.split(',')
            for (let i = 0; i < tenantNameArr.length - 1; i++) {
              this.selectList.push({
                name: tenantNameArr[i],
                id: tenantIdArr[i]
              })
            }
            for (let y = 0; y < tenantIdArr.length - 1; y++) {
              this.checkedKeys.push(tenantIdArr[y])
            }
          }
          this.listLoading = false;
        });
      }
    },

    // 提交发送范围对话框
    submitTree () {
      this.dialogFormVisible = false;
    },
    // 选中发送范围中的复选框
    handleCheckChange (data, checked, indeterminate) {
      if (this.deleteFlag) {
        if (checked) {
          this.selectList.push(data)
          this.selectList.forEach((item, index) => {
            if (item.parentId === '-1') {
              this.selectList.splice(index, 1)
            }
          })
        } else {
          this.selectList.forEach((item, index) => {
            if (item.id === data.id) {
              this.selectList.splice(index, 1)
            }
          })
        }
      }
      this.deleteFlag = true;
      this.words = ''
      this.wordsId = ''
      if (this.selectList.length > 0) {
        for (let i of this.selectList) {
          this.words += i.name + ','
          this.wordsId += i.id + ','
        }
      }
      this.ruleForm.tenantName = this._.cloneDeep(this.words)
      this.ruleForm.tenantId = this._.cloneDeep(this.wordsId)
    },
    // 保存
    save () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.ruleForm.createDate = ''
          if (this.$route.query.id) {
            this.listLoading = true;
            this.ruleForm.isIssue = 0;
            this.$refs.upload.handleSaveBill().then(res => {
              this.ruleForm.ossCoverUrl = res;
              this.ruleForm.id = this.$route.query.id
              editIssueInfo(this.ruleForm).then(response => {
                this.$message({
                  type: "success",
                  message: '保存成功'
                });
                this.getList()
                this.listLoading = false;
              });
            });
          } else {
            this.listLoading = true;
            this.ruleForm.isIssue = 0;
            this.$refs.upload.handleSaveBill().then((res) => {
              this.ruleForm.ossCoverUrl = res
              createIssueInfo(this.ruleForm).then(response => {
                this.$message({
                  type: 'success',
                  message: '保存成功!'
                });
                this.$router.push({
                  name: 'newList',
                  query: {
                    id: response.data
                  },

                })
                this.getList()
                this.listLoading = false
              })
            })
          }

        } else {
          this.$message({
            message: '带*号的为必填项',
            type: 'error'
          })
          return false
        }
      })
    },
    getnewTypeName (typeId) {
      if (typeId) {
        this.ruleForm.typeName = this.dynamicTags.find(item =>
          item.parameterKey === typeId
        ).parameterValue
      }
    },
    submitDetail () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.ruleForm.createDate = ''
          if (this.$route.query.id) {
            this.listLoading = true;
            this.ruleForm.isIssue = 1;
            this.ruleForm.id = this.$route.query.id
            this.$refs.upload.handleSaveBill().then(res => {
              this.ruleForm.ossCoverUrl = res;
              editIssueInfo(this.ruleForm).then(response => {
                this.$message({
                  type: "success",
                  message: '发布成功'
                });
                this.$router.push({
                  name: "newList",
                  query: {
                    id: response.data
                  }
                });
                this.listLoading = false;
              });
            });
          } else {
            this.listLoading = true;
            this.ruleForm.isIssue = 1;
            this.$refs.upload.handleSaveBill().then((res) => {
              this.ruleForm.ossCoverUrl = res
              createIssueInfo(this.ruleForm).then(response => {
                this.$message({
                  type: 'success',
                  message: '发布成功!'
                });
                this.$router.push({
                  name: 'newList',
                  query: {
                    id: response.data
                  },

                })
                this.listLoading = false
              })
            })
          }

        } else {
          this.$message({
            message: '带*号的为必填项',
            type: 'error'
          })
          return false
        }
      })
    },

    getCurRecipients () {
      for (let j of this.selectList) {
        this.ruleForm.tenantName += j.name + ','
        this.ruleForm.tenantId += j.id + ','
      }
    },
    // 返回
    goBack () {
      this.$confirm('有内容尚未保存，是否继续？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消',
        type: 'warning'
      }).then((res) => {
        if (res) {
          this.$router.push({
            name: 'newList'
          })
        }
      }).catch(() => {
      });
    },
    // 数组去重
    unique (arr) {
      const temp = [];
      for (let i = 0; i < arr.length; i++) {
        if (temp.indexOf(arr[i]) === -1) {
          temp.push(arr[i])
        }
      }
      return temp;
    },
    // 发送范围右侧人员删除
    delShipSelect (data) {
      const index = this.selectList.findIndex(itm => itm.id === data.id);
      this.deleteFlag = false;
      this.$delete(this.selectList, index);
      this.$refs.tree.setCheckedNodes(this.selectList)
    }
  }
}
</script>
<style lang='scss' scoped>
.app-container {
  background: #eee !important;
  height: 91vh;
  overflow-y: auto;
}

#root {
  height: 100%;
}

#body {
  height: calc(100vh - 100px);
  background: #fff;
}

.management {
  height: 50px;
  background: #fff;
}

.table-button {
}

.float-right {
  float: right;
}

.img-class {
  float: left;
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.title-name {
  cursor: pointer;
  font-size: 16px;
  color: #1d6ced;
  margin: 0px;
}

.title {
  width: 30em;
}

.demo-ruleForm {
}

.send {
  width: 20em !important;
}

.noticetype {
  width: 17.2em !important;
}

.input-range {
  /deep/ .el-input__inner {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.demo-form {
  margin-left: 50px;
}

.notice-details {
  /*padding: 10px;*/
  height: 600px;
  width: 100%;
  display: flex;
  flex-direction: column;
  background: #eee;

  .notice-header {
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;

    .notice-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .titleFC {
      font-size: 16px;
      font-weight: bold;
      margin-top: 10px;
    }

    .text {
      display: flex;
      justify-content: center;

      .time {
        font-size: 14px;
        color: #333333;
        margin-top: 10px;
        margin-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .timeFw {
        font-size: 14px;
        color: #333333;
        margin-top: 10px;
        width: 600px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .notice-sub-header {
    background: #fff;
    text-align: center;
    padding-top: 10px;
    padding-bottom: 20px;
    background-color: #eee;
    img {
      max-width: 50%;
      height: 220px;
    }
  }

  .notice-content {
    flex: 1;
    line-height: 35px;
    padding-top: 0px;
    padding-bottom: 30px;
    padding-left: 90px;
    padding-right: 90px;
    overflow-y: auto;
    .notice-content-html {
      /deep/ {
        * {
          color: #333;
        }

        p {
          margin-top: 4px;
          margin-bottom: 4px;
        }
      }
    }
  }
}

.mr10 {
  margin-left: 5px;
}

.adddepartment {
  height: 400px;
  display: flex;
  justify-content: space-between;
}

.adddepartment1 {
  padding: 20px;
  width: 50%;
  overflow-y: auto;
}

.adddepartment2 {
  padding: 20px;
  width: 50%;
  background-color: #eeeeee;
  overflow-y: auto;
}

/deep/ .el-tree-node__content {
  height: 40px;
}

.adddepartment3 {
  height: 36px;
  line-height: 36px;
  background-color: #ffffff;
  position: relative;
  margin-bottom: 5px;
}

.adddepartment4 {
  display: inline-block;
  margin-bottom: 20px;
}

.adddepartmentDel {
  right: 20px;
  color: #1d6ced;
  float: right;
  padding-right: 10px;
}

.defaultNews {
  >>> .el-form-item__content {
    display: flex;
    .content {
      font-size: 12px;
      line-height: 16px;
      margin: auto 0 auto 10px;
      color: #999;
      white-space: normal;
      width: 200px;
      overflow: hidden;
      display: block;
    }
  }
}
.adddepartmentLeft {
  width: 188px;
  display: inline-block;
  position: absolute;
  left: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/ .fileName {
  display: none;
}
</style>
