<template>
  <div class="page-body document">
    <q-tabs style="margin-bottom:20px;" v-model="tabCheck" @input="tabChange()" narrow-indicator dense align="left"
      class="text-primary">
      <q-tab :ripple="false" name="first" label="公文" />
      <q-tab :ripple="false" name="second" label="基础设置" />
    </q-tabs>
    <template v-if="tabCheck=='first'">
      <div class="page-search row items-center">
        <div class="col row wrap q-mr-lg q-col-gutter-md">
          <div class="col-3">
            <q-input clearable @change="getList" standout="bg-primary text-white" v-model="msg.Title" label="公文标题"
              @clear="getList" />
          </div>
          <div class="col-3">
            <q-input clearable @change="getList" standout="bg-primary text-white" v-model="msg.Number" label="编号"
              @clear="getList" />
          </div>
          <q-select @input="getList" filled stack-label option-value="Id" option-label="EmployeeName" use-input
            v-model="msg.UpdateBy" ref="DeptTier" :options="PersionList" label="发布人" :dense="false"
            class="col-3 q-pr-lg" emit-value map-options @filter="filterFn">
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  未找到相关数据
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <div class="col-3">
            <q-select @input="getList" filled stack-label option-value="Id" option-label="Name"
              v-model="msg.NoticeState" ref="DeptTier" :options="NoticeList" label="发布状态" :dense="false"
              class="col-6 q-pr-lg" emit-value map-options />
          </div>
        </div>
      </div>
      <div class="page-content">
        <q-table :pagination="msg" :loading="loading" no-data-label="暂无相关数据" flat class="sticky-tow-column-table"
          separator="none" title="" :data="data" :columns="columns" row-key="name">
          <template v-slot:top="props">
            <div class="page-option" style="width:100%;">
              <q-btn color="accent" style="float:right;margin-right:0;" size="sm" class="q-mr-md" icon="add"
                label="发布公文" @click="addDoc(null)" />
            </div>
          </template>
          <template v-slot:body-cell-NoticeStateName="props">
            <q-td :props="props">
              <div class="row" style="line-height: 30px">
                <img v-if="props.row.NoticeState==2" src="../../assets/images/dcaogao.png" class="NoticeStateNimg" />
                <img v-if="props.row.NoticeState==3" src="../../assets/images/dchehui.png" class="NoticeStateNimg" />
                <img v-if="props.row.NoticeState==1" src="../../assets/images/dfabu.png" class="NoticeStateNimg" />
                <span
                  :style="{color:props.row.NoticeState==1?'#02C499':(props.row.NoticeState==2?'#2961FE':'#F72E52')}">{{props.row.NoticeStateName}}</span>
              </div>
            </q-td>
          </template>
          <template v-slot:body-cell-IsTop="props">
            <q-td :props="props">
              <span v-if="props.row.Is_Top==1">是</span>
              <span v-if="props.row.Is_Top==2">否</span>
            </q-td>
          </template>

          <template v-slot:body-cell-optioned="props">
            <q-td :props="props">
              <q-btn flat size="xs" icon="iconfont icon-zhiding" style="font-weight:400;color: #789CFF" class="q-mr-xs"
                label="置顶" @click="setNoticeOtion(props.row.Id,1)"
                v-if="props.row.NoticeState==1&&props.row.Is_Top==2" />
              <q-btn flat size="xs" icon="iconfont icon-quxiaozhiding1" style="font-weight:400;color:#FF7C93;"
                class="q-mr-xs" label="取消置顶" @click="setNoticeOtion(props.row.Id,2)"
                v-if="props.row.NoticeState==1&&props.row.Is_Top==1" />
              <q-btn flat size="xs" icon="iconfont icon-xiangqing-" style="font-weight:400;color: #3FC4FF"
                class="q-mr-xs" label="详情" @click="EditConfig(props.row.Id)" />
              <q-btn flat size="xs" icon="iconfont icon-chehui4" color="deep-orange" style="font-weight:400"
                class="q-mr-xs" label="撤回" @click="setNoticeOtion(props.row.Id,3)" v-if="props.row.NoticeState==1" />
              <q-btn flat size="xs" icon="iconfont icon-xiugai1" style="font-weight:400;color: #02C499" class="q-mr-xs"
                label="修改" v-if="props.row.NoticeState!=1" @click="addDoc(props.row.Id)" />
            </q-td>
          </template>
          <template v-slot:bottom>
            <q-pagination class="full-width justify-end" v-model="msg.PageIndex" color="primary" :max="pageCount"
              :input="true" @input="changePage" />
          </template>
        </q-table>
      </div>
    </template>
    <template v-if="tabCheck=='second'">
      <div class="page-content ">
        <div class="second-item col-6 q-pr-lg q-pb-lg">
          <div class="col-2 q-pr-lg q-pb-lg">
            <q-uploader style="display: inline-block;max-height: 320px;max-width: 100%; background-repeat:no-repeat"
              :style="{'background-image':'url(' + NoticeBaseInfo.Image + ')'}" max-files="1" hide-upload-btn
              @rejected="onRejected" label="公文抬头图片"  accept=".jpg, image/*" auto-upload
              :factory="uploadFile" no-thumbnails>
            </q-uploader>
          </div>
          <div class="row">
            <div class="col-4">
              <q-input clearable standout="bg-primary text-white" v-model="NoticeBaseInfo.From" label="公文来源（FR）" />
            </div>
          </div>
          <div class="row">
            <div class="col-4" style="margin-top: 20px">
              <q-select filled stack-label option-value="Id" option-label="Name" v-model="NoticeBaseInfo.NumberRule"
                ref="DeptTier" :options="RuleEnumList" label="编号规则" :dense="false" class="col-6 q-pr-lg q-pb-lg"
                emit-value map-options clearable />
            </div>
          </div>
          <div class="row">
            <div class="col-4">
              <q-select class="col-6 q-pb-lg q-pr-lg" multiple clearable filled stack-label use-input use-chips
                option-value="Id" option-label="EmployeeName" v-model="tempManager" ref="ManagerId"
                :options="PersionList" label="默认抄送" :dense="false" emit-value map-options @filter="filterFn">
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      未找到相关数据
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
          </div>
          <q-btn label="立即提交" color="accent q-px-md" size="sm" style="font-weight:400 !important" :loading="saveLoading"
            @click="save" />
        </div>
      </div>
    </template>
    <q-dialog v-model="persistent" content-class="bg-grey-1" persistent transition-show="scale" transition-hide="scale">
      <q-card style="width: 800px;max-width:900px;">
        <q-card-section>
          <div class="text-h6">{{addMsg.Id==0?'发布公告':'修改公告'}}</div>
        </q-card-section>
        <div class="text-caption q-mb-lg q-px-md text-grey-6">基本资料</div>
        <q-card-section class="q-pt-none">
          <div class="row wrap">
            <q-input clearable filled class="col-6 q-pb-lg q-pr-lg" standout="bg-primary text-white"
              v-model="addMsg.From" ref="From" label="公文来源（FR）" :rules="[val => !!val || '公文来源（FR）']" />
            <selectTree class="col-6 q-pb-lg q-pr-lg" :treeData='DeptList' :defaultArray="returnString" nodeKey="DeptId"
              :multiple="true" :defaultExpandAll="true" labelKey="DeptName" childrenKey="ChildList" tipText="To"
              @getChild="getChild" classStr="col-6 q-pr-lg q-pb-lg"></selectTree>

            <q-select class="col-6 q-pb-lg q-pr-lg" multiple clearable filled stack-label use-input use-chips
              option-value="Id" option-label="EmployeeName" v-model="tempManager2" ref="ManagerId"
              :options="PersionList" label="默认抄送" :dense="false" emit-value map-options @filter="filterFn">
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    未找到相关数据
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            <q-input clearable class="col-6 q-pb-lg q-pr-lg" standout="bg-primary text-white" disable v-model="nNumber"
              label="编号" v-if="nNumber!=null  " />
            <q-input clearable filled class="col-12 q-pb-lg q-pr-lg" standout="bg-primary text-white"
              v-model="addMsg.Title" ref="Title" label="标题" :rules="[val => !!val || '标题']" />
            <div class="text-caption q-my-md q-px-xs text-grey-6">公告内容</div>
            <ext-editor :defaultMsg="addMsg.Content" classStr="col-12" @getEditValue="getEditValue"></ext-editor>
            <el-upload style="margin-top: 20px" :http-request="uploadFile2" :file-list="fileList"
              :before-remove="beforeRemove" :multiple="true" :show-file-list="true" action="">
              <el-button size="mini" type="primary">附件上传</el-button>
            </el-upload>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white">
          <q-btn label="取消" flat color="grey-10" size="sm" style="font-weight:400 !important" @click="closeSaveForm" />
          <q-btn label="草稿" color="accent q-px-md" size="sm" style="font-weight:400 !important" :loading="saveLoading"
            @click="save_t(2)" />
          <q-btn label="立即提交" color="accent q-px-md" size="sm" style="font-weight:400 !important" :loading="saveLoading"
            @click="save_t(1)" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <el-drawer title="" :visible.sync="drawer" size="40%" :with-header="false">
      <q-img :src="NoticeBaseInfo.Image" spinner-color="white" style=" width: 100%;height: 120px" />
      <div style="padding: 20px">
        <div class="col-12 g row">
          <div class="col-6">
            Fr：{{addMsg.From}}
          </div>
          <div class="col-6 " style="text-align: right">
            编号：{{nNumber}}
          </div>
        </div>
        <div class="col-12  row">
          To：<span v-for="(item,index) in NInfo.DepartmentList"
            :index="index">{{item.DeptName}}{{NInfo.DepartmentList.length==index+1?'':'、'}}</span>
        </div>
        <div class="col-12  row">
          Cc：<span v-for="(item,index) in NInfo.CopyPeopleList"
            :index="index">{{item.EmName}}{{NInfo.CopyPeopleList.length==index+1?'':'、'}}</span>
        </div>
        <div class="col-12  row">
          Time：{{NInfo.UpdateTime}}
        </div>
        <div class="col-12  row" style="margin-top: 20px">
          <span v-html="addMsg.Content"></span>
        </div>
        <div class="col-12  row" style="margin-top: 20px">
          <div>附件:</div>
          <template>
            <div class="q-pa-md" style="max-width: 350px">
              <q-list dense padding class="rounded-borders">
                <q-item clickable v-ripple v-for="(file,fIndex) in fileList" :key="fIndex">
                  <q-item-section>
                    <div class="row" @click="wopen(file)">
                      <i class="iconfont icon-xiazai2" style="margin-right: 10px"></i>
                      {{file.name}}
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </div>
          </template>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {
    getNoticePageList,
    getNoticeStateEnumList,
    getNoticeBaseInfo, //获取 公告配置
    getNoticeRuleEnumList, //获取编号规则 枚举列表
    setNoticeBaseInfo, //新增修改 公告配置
    setNoticeOperation, //公告操作
    setNoticeInfo, //发布公告
    getNoticeInfo, //公告详情
  } from '../../api/administration/document';
  import {
    getDeptTree
  } from '../../api/system/dept.js'
  import {
    queryEmployee
  } from '../../api/users/user'
  import {
    UploadSelfFile,
  } from '../../api/common/common'
  import extEditor from '../../components/common/ext-editor'
  import selectTree from '../../components/common/select-tree'

  export default {
    meta: {
      title: "行政公告"
    },
    components: {
      extEditor,
      selectTree
    },
    name: "document",
    data() {
      return {
        tabCheck: 'first',
        msg: {
          PageIndex: 1,
          PageSize: 20,
          Title: '',
          Number: '',
          NoticeState: 0,
          Is_Top: 0,
          UpdateBy: -1
        },
        loading: true,
        //公告column
        columns: [{
            name: 'NoticeStateName',
            label: '状态',
            align: 'left'
          },
          {
            name: 'Number',
            field: 'Number',
            label: '编号',
            align: 'left',
          },
          {
            name: 'Title',
            label: '标题',
            field: 'Title',
            align: 'left'
          },
          {
            name: 'ReadNum',
            label: '阅读情况',
            field: 'ReadNum',
            align: 'left'
          },
          {
            name: 'IsTop',
            label: '是否置顶',
            align: 'left'
          },
          {
            name: 'UpdateByName',
            label: '发布人',
            field: 'UpdateByName',
            align: 'left'
          },
          {
            name: 'UpdateTime',
            label: '发布时间',
            align: 'left',
            field: 'UpdateTime'
          }, {
            name: 'optioned',
            label: '操作',
            field: 'DeptId'
          }
        ],
        data: [],
        pageCount: 0,
        NoticeList: [],
        PersionList: [], //员工列表
        AllemployeeList: [], //所有员工
        NoticeBaseInfo: { //基础配置
          Id: 0,
          Image: '',
          From: '',
          NumberRule: '',
          NumberRuleName: '',
          CopyPeople: '',
        },
        tempManager: [], //默认抄送
        tempManager2: [], //发布公告 默认抄送
        RuleEnumList: [], //编号规则列表
        saveLoading: false,
        persistent: false,
        addMsg: { //添加和修改公告
          Id: 0,
          From: '',
          To: '-1', //抄送部门
          CopyPeople: '-1', //抄送人
          Title: '',
          Content: '',
          NoticeState: 1, //状态 1发布 2草稿
          Is_Top: 2, //是否置顶 1是 2否
          FileList: [], //附件列表

        },
        fileList: [], //上传列表
        DeptList: [], // 部门下拉
        returnString: [], //默认岗位
        nNumber: null,
        drawer: false, //显示右侧抽屉
        NInfo: {}, //详情内容

      }
    },
    mounted() {
      this.getList();
      this.getNoticeList()
      this.getEmployee()
      this.getNoticeBase()
      this.getDepartList();
      this.getNoticeRule() //获取编号规则 枚举列表
    },
    methods: {

      //获取编辑器值
      getEditValue(obj) {
        this.addMsg.Content = obj;
      },
      tabChange() {
        if (this.tabCheck == 'first') {
          this.getList();
        } else if (this.tabCheck == 'second') {
          this.getNoticeBase()
        }
      },
      onRejected(rejectedEntries) {
        this.$q.notify({
          type: 'negative',
          position: "top",
          message: `文件验证失败，请重新上传`
        })
      },
      uploadFile(files) {
        UploadSelfFile('studentIcon', files[0], res => {
          if (res.Code == 1) {
            this.NoticeBaseInfo.Image = res.FileUrl;
          }
        })
      },
      uploadFile2(files) {
        UploadSelfFile('studentIcon', files.file, res => {
          if (res.Code == 1) {
            let obj = {
              name: res.FileName,
              url: res.FileUrl,
            }
            this.fileList.push(obj)
          }
        })
      },
      beforeRemove(file, fileList) { //删除的操作
        this.fileList.forEach((x, j) => {
          if (x.uid == file.uid) {
            this.fileList.splice(j, 1)
          }
        })
      },
      getList() {
        if (this.msg.UpdateBy == '' || this.msg.UpdateBy == null) {
          this.msg.UpdateBy = 0
        }
        this.loading = false;
        getNoticePageList(this.msg).then(res => {
          this.data = res.Data.PageData;
          this.loading = false;
          this.pageCount = res.Data.PageCount;
        }).catch(() => {
          this.loading = false
        })
      },
      getNoticeList() {
        this.loading = false;
        getNoticeStateEnumList({
          Name: '',
          Id: ''
        }).then(res => {
          this.NoticeList = res.Data
          let obj = {
            Name: '不限',
            Id: 0
          }
          this.NoticeList.unshift(obj)
        }).catch(() => {
          this.loading = false
        })
      },
      //筛选员工
      filterFn(val, update) {
        update(() => {
          if (val === '') {
            this.PersionList = JSON.parse(JSON.stringify(this.AllemployeeList))
          } else {
            const needle = val.toLowerCase()
            this.PersionList = this.AllemployeeList.filter(v => v.EmployeeName.toLowerCase().indexOf(needle) > -1)
          }
        })
      },
      //获取员工列表
      getEmployee() {
        var qMsg = {
          EmployeeName: ""
        }
        queryEmployee(qMsg).then(res => {
          if (res.Code == 1) {
            let obj = {
              EmployeeName: '不限',
              Id: -1
            }
            res.Data.unshift(obj)
            var jsonData = res.Data;
            if (jsonData && jsonData.length > 0) {
              this.AllemployeeList = JSON.parse(JSON.stringify(jsonData));
              this.PersionList = JSON.parse(JSON.stringify(jsonData));;
            }
          }
        })
      },
      //获取部门下拉数据
      getDepartList(id) {
        let msg = {
          School_Id: 0
        }
        getDeptTree(msg).then(res => {
          if (res.Code == 1) {
            this.DeptList = res.Data;
          }
        })
      },
      //分页改变
      changePage(val) {
        this.msg.PageIndex = val;
        this.getSchool()
      },
      getChild(deptArray) {
        var tempStr = "";
        if (deptArray && deptArray != '') {
          tempStr = deptArray;
        }
        if (tempStr) {
          this.addMsg.To = tempStr;
        } else {
          this.addMsg.To = '';
        }
      },
      ////获取 公告配置
      getNoticeBase() {
        getNoticeBaseInfo({}).then(res => {
          if (res.Code == 1) {
            this.NoticeBaseInfo = res.Data
            this.tempManager = res.Data.CopyPeople.split(',').map(Number); //字符串转为数组map 是转为数字
          }
        })
      },
      getNoticeRule() {
        getNoticeRuleEnumList({
          Name: '',
          Id: ''
        }).then(res => {
          if (res.Code == 1) {
            this.RuleEnumList = res.Data
          }
        })
      },
      save() {
        this.saveLoading = true;
        var tempStr = "";
        if (this.tempManager && this.tempManager.length > 0) {
          this.tempManager.forEach(item => {
            tempStr += "," + item;
          });
        }
        if (tempStr && tempStr != '') {
          //去掉第一个字符
          tempStr = tempStr.substr(1);
        }
        this.NoticeBaseInfo.CopyPeople = tempStr;
        setNoticeBaseInfo(this.NoticeBaseInfo).then(res => {
          this.saveLoading = false
          if (res.Code == 1) {
            this.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: '数据保存成功！',
              position: 'top'
            })
            this.$emit("success")
          }
        }).catch(() => {
          this.saveLoading = false
        })
      },
      getNInfo(id) {
        getNoticeInfo({
          NoticeId: id
        }).then(res => {
          if (res.Code == 1) {
            this.NInfo = res.Data
            this.addMsg.Id = res.Data.Id;
            this.addMsg.From = res.Data.From;
            //数组处理
            this.addMsg.To = res.Data.To;
            this.returnString = []
            this.returnString = res.Data.To.split(',').map(Number)
            //数组处理
            this.addMsg.CopyPeople = res.Data.CopyPeople;
            this.tempManager2 = res.Data.CopyPeople.split(',').map(Number) //字符串转为数组map 是转为数字
            this.addMsg.Title = res.Data.Title;
            this.addMsg.Content = res.Data.Content;
            this.addMsg.NoticeState = res.Data.NoticeState;
            this.addMsg.Is_Top = res.Data.Is_Top;
            this.fileList = [];
            res.Data.FileList.forEach((x) => {
              let obj = {
                name: x.FileName,
                url: x.FileUrl
              }
              this.fileList.push(obj)
            })
            this.nNumber = res.Data.Number;
          }
        }).catch(() => {})
      },
      addDoc(id) {
        this.nNumber = null
        if (id) {

          this.getNInfo(id)
        } else {
          this.tempManager2 = this.tempManager ? this.tempManager : []
          this.addMsg.From = this.NoticeBaseInfo.From;
          this.addMsg.Title = this.NoticeBaseInfo.Title;
          this.addMsg.Id = 0;
          this.addMsg.Content = this.NoticeBaseInfo.Content;
          this.addMsg.NoticeState = 1;
          this.addMsg.Is_Top = 2;
          this.addMsg.FileList = [];
          this.fileList = []
        }
        this.persistent = true;
      },
      closeSaveForm() {
        this.persistent = false
      },
      save_t(val) {
        this.$refs.From.validate()
        this.$refs.Title.validate()
        if(!this.$refs.From.hasError && !this.$refs.Title.hasError){
          this.addMsg.NoticeState = val //发布状态
          this.saveLoading = true;
          var tempStr = "";
          if (this.tempManager2 && this.tempManager2.length > 0) {
            this.tempManager2.forEach(item => {
              tempStr += "," + item;
            });
          }
          if (tempStr && tempStr != '') {
            //去掉第一个字符
            tempStr = tempStr.substr(1);
          }
          this.addMsg.CopyPeople = tempStr;
          this.addMsg.FileList = []
          this.fileList.forEach((x) => {
            let obj = {
              FileName: x.name,
              FileUrl: x.url
            }
            this.addMsg.FileList.push(obj)
          })
          let data = this.addMsg
          if (data.CopyPeople == '') {
            data.CopyPeople = -1
          }
          if (data.To == '') {
            data.To = -1
          }
          setNoticeInfo(data).then(res => {
            this.saveLoading = false
            if (res.Code == 1) {
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '数据保存成功！',
                position: 'top'
              })
              this.$emit("success")
              this.persistent = false
              this.getList();
            }
          }).catch(() => {
            this.saveLoading = false
          })
        }


      },
      EditConfig(id) {
        this.drawer = true;
        this.getNInfo(id)
      },
      setNoticeOtion(id, type) {
        setNoticeOperation({
          NoticeId: id,
          Type: type
        }).then(res => {
          this.saveLoading = false
          if (res.Code == 1) {
            this.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: '操作成功！',
              position: 'top'
            })
            this.$emit("success")
            this.persistent = false
            this.msg.PageIndex = 1;
            this.getList();
          }
        }).catch(() => {
          this.saveLoading = false
        })
      },
      wopen(file) {
        window.open(file.url);
      }
    }
  }

</script>

<style scoped>
  .second-item {}

  .document .NoticeStateNimg {
    width: 30px;
    height: 30px;
    margin-right: 5px;
  }

  .document .q-pr-lg {
    padding-right: 0;
  }

</style>
