<template>
  <div class="global">
    <div class="mainContainer">
      <el-form label-width="80px" :model="formData" ref="formData" :rules="rules">
        <el-row :span="24">
          <el-col :span="24">
            <el-form-item label="标题:" prop="title">
              <el-input class="wdh" v-model="formData.title" :disabled="isdisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-form-item prop="content" label="正文:" label-width="80px" class="list-margin">
            <quill-editor
              ref="myTextEditor"
              v-model="formData.content"
              :config="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
              :disabled="isdisabled"
            ></quill-editor>
          </el-form-item>
        </el-row>
        <el-row :span="24">
          <el-col :span="24">
            <el-form-item label="发布时间:" prop="publishTime">
              <el-date-picker  v-model="formData.publishTime" :disabled="isdisabled" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"  placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="发送给:" label-width="90px" prop="recvType">
              <el-radio-group v-model="formData.recvType" style="margin-top:11px"  :disabled="isdisabled">
                <el-radio :label="10">全员</el-radio>
                <el-row style="margin:15px 0" v-if="formData.orgType == '分公司'">
                  <el-radio :label="20">指定粮库</el-radio>
                  <el-tree
                    show-checkbox
                    class="filter-tree"
                    :data="depotIdList"
                    node-key="depotCode"
                    highlight-current
                    :props="defaultProps"
                    :default-checked-keys="check"
                    ref="warehouseTree"
                    default-expand-all
                    >        
                  </el-tree>
                </el-row>
                <el-radio :label="30" v-if="formData.orgType == '分公司'">分公司全员</el-radio>
                <el-row style="margin:15px 0">
                  <el-radio :label="40">指定角色组</el-radio>
                  <el-select v-model="roleCodeArr" multiple placeholder="请选择" style="width:200px"  :disabled="isdisabled">
                    <el-option
                      v-for="item in roleList"
                      :key="item.roleCode"
                      :label="item.roleName"
                      :value="item.roleCode">
                    </el-option>
                  </el-select>
                </el-row>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发布者:">
              {{formData.publishUserName}}
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <div class="btns">
        <el-button v-if="status !== 'detail'" type="success" @click="release('formData','1')">发布</el-button>
        <el-button v-if="status !== 'detail'" type="success" plain @click="release('formData','2')">保存至草稿箱</el-button>
        <el-button type="success" plain @click="goback">返回</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { addFun,updateFun,detailFun,getAllRole,getDepotAll } from '@/api/system/notice'
import { quillEditor } from "vue-quill-editor"
import { getUser } from '@/utils/auth'
export default {
  name: "Addnotice",
  components: {
    quillEditor
  },
  data() {
    return {
      formData: {
        title:'',
        content:'',
        publishUserId:'',
        publishUserName:'',
        recvType:10,
        recvDetails:'',
        recvDetailsInfo:'',
        publishTime:'',
        publishStatus: false, //发布状态
        annoType:'20' //公告
      },
      editorOption: {},
      roleList:[], //角色组
      roleCodeArr:[],
      depotIdList:[], //指定粮库
      defaultProps: {
        children: 'children',
        label: 'depotName',
        value:'depotCode'
      },
      check:[],
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: false, message: '请输入正文', trigger: 'blur' }],
        recvType: [{ required: true, message: '请选择接收方', trigger: 'change' }],
      },
      isdisabled: false,
      status: 'add'
    }
  },
  created() {
    this.$nextTick(() => {
      this.$refs['formData'].resetFields()
      this.formData = {
        title:'',
        content:'',
        publishUserId:'',
        publishUserName:'',
        recvType:10,
        recvDetails:'',
        recvDetailsInfo:'',
        publishTime:'',
        publishStatus: false, //发布状态
        annoType:'20' //公告
      }
      this.status = this.$route.query.state
      this.getRoleList()
      this.getDepotList()
      if (this.$route.query.state == 'add') {
        this.formData.publishUserId = JSON.parse(getUser()).personnelId
        this.formData.publishUserName = JSON.parse(getUser()).personnelName
        this.formData.publishOrgId = JSON.parse(getUser()).depotId
        this.formData.publishOrgName = JSON.parse(getUser()).depotName
        if (this.$route.query.orgType == '1') {
          this.formData.orgType = '分公司'
        }else if (this.$route.query.orgType == '2') {
          this.formData.orgType = '粮库'
        }
      }
      if (this.$route.query.state == 'edit') {
        this.detailInfo()
      }
      if (this.$route.query.state == 'detail') {
        this.isdisabled = true
        this.detailInfo()
      }
    })
  },
  methods: {
    getRoleList() {
      getAllRole().then(res => {
        this.roleList = res.data
      })
    },
    getDepotList() {
      let depotId = ''
      getDepotAll(depotId).then(res => {
        this.depotIdList = res.data
        if (this.$route.query.state == 'detail') {
          if(this.depotIdList && this.depotIdList.length>0){
            this.depotIdList.forEach(item => {
              item.disabled = true
              if(item.children && item.children.length>0){
                item.children.forEach(itemChild => {
                  itemChild.disabled = true
                  if(itemChild.children && itemChild.children.length>0){
                    itemChild.children.forEach(itemChildren => {
                      itemChildren.disabled = true
                    })
                  }
                })
              }
            })
          }
        }
      })
    },
    addList() {
      addFun(this.formData).then(res => {
        if (res.code == 200) {
          this.$message.success('新增成功')
          if(!this.formData.publishStatus){
            this.$router.push({ path: "/systemManagement/notice/AllNotice" })
          }else if(this.formData.publishStatus){
            this.$router.push({ path: "/systemManagement/notice/NewNotice" })
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    updateList() {
      updateFun(this.formData).then(res => {
        if (res.code == 200) {
          this.$message.success('修改成功')
          if(!this.formData.publishStatus){
            this.$router.push({ path: "/systemManagement/notice/AllNotice" })
          }else if(this.formData.publishStatus){
            this.$router.push({ path: "/systemManagement/notice/NewNotice" })
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    goback() {
      if(this.$route.query.state == 'add'){
        this.$router.push({ path: "/systemManagement/notice/NewNotice" })
      }else{
        if(!this.formData.publishStatus){
          this.$router.push({ path: "/systemManagement/notice/AllNotice" })
        }else if(this.formData.publishStatus){
          this.$router.push({ path: "/systemManagement/notice/NewNotice" })
        }
      }
    },
    detailInfo() {
      detailFun(this.$route.query.id).then(res => {
        if (res.code == 200) {
          this.formData = res.data
          this.formData.recvType = Number(res.data.recvType)
          if(this.formData.recvType == 20){
            this.check = this.formData.recvDetails.split(',')
          }
          if(this.formData.recvType == 40){
            this.roleCodeArr = this.formData.recvDetails.split(',')
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    release(formName,state) {
      console.log(this.$refs.warehouseTree.getCheckedNodes(true))
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(state == '1'){
            this.formData.publishStatus = true
          }else{
            this.formData.publishStatus = false
          }
          if(this.formData.recvType == '20'){
            let ids = []
            ids.push(this.$refs.warehouseTree.getCheckedKeys(true))
            this.formData.recvDetails = ids.join(',')

            let nodeData = this.$refs.warehouseTree.getCheckedNodes(true)
            let nodeDataName = [] 
            nodeData.forEach(item => {
              nodeDataName.push(item.depotName)
            })
            this.formData.recvDetailsInfo = `${nodeDataName.join(',')}全员`
          }else if(this.formData.recvType == '40'){
            this.formData.recvDetails = this.roleCodeArr.join(',')
            let recvDetailsInfo = []
            this.roleCodeArr.forEach(item => {
              this.roleList.forEach(itemRole => {
                if(item == itemRole.roleCode){
                   recvDetailsInfo.push(itemRole.roleName)
                }
              })
            })
            this.formData.recvDetailsInfo =  recvDetailsInfo.join(',')
          }
          else if(this.formData.recvType == '10'){
            this.formData.recvDetailsInfo = '全员'
          }
          else if(this.formData.recvType == '30'){
            this.formData.recvDetailsInfo = '分公司全员'
          }
          if(this.formData.publishStatus){
            if(this.formData.publishTime){
              if (this.$route.query.state == 'add') {
                this.addList()
              } else if (this.$route.query.state == 'edit') {
                this.updateList()
              }
            }else{
              this.$message.error('请选择发布时间')
            }
          }else{
            if (this.$route.query.state == 'add') {
              this.addList()
            } else if (this.$route.query.state == 'edit') {
              this.updateList()
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 富文本编辑器js
    onEditorBlur(editor) {
      console.log("editor blur!", editor)
    },
    onEditorFocus(editor) {
      console.log("editor focus!", editor)
    },
    onEditorReady(editor) {
      console.log("editor ready!", editor)
    },
    onEditorChange({ editor, html, text }) {
      console.log('editor change!', editor, html, text)
      // this.content = html
    }
  }
}
</script>
<style lang="scss" scoped>
.btns {
  text-align: center;
  margin-top: 20px;
}
</style>
