<template>
  <div class="flex bg-white p-10 datapanel ">
    <div style="flex: 1.5;" class="flex">
      <div class="flex">
        <criteria-paged :model="model" v-ref:paged :pager="!row && !areainfo" @sort="sort">
          <criteria partial='criteria' v-ref:criteria @condition-changed="$parent.selfSearch">
            <div novalidate class="form-inline auto" partial>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_title"
                       condition="f_title like '%{}%'" placeholder='标题'>
              </div>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_date"
                       condition="f_date like '%{}%'" placeholder='发布时间'>
              </div>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_operator"
                       condition="f_operator like '%{}%'" placeholder='发布人'>
              </div>
              <div class="form-group">
                <button class="btn btn-success" @click="search(), $parent.$parent.clean()">查询</button>
              </div>
              <div class="form-group">
                <button class="btn btn-success" @click="$parent.$parent.add()">新增公告</button>
              </div>
              <div class="form-group">
                <button type="button" name="button" class="btn btn-success" @click.stop="$parent.$parent.addknow()">新增知识库</button>
              </div>
            </div>
          </criteria>
          <data-grid :model="model" v-ref:grid partial='list'>
            <template partial='head'>
              <tr>
                <th>
                  <nobr>序号</nobr>
                </th>
                <th>
                  <nobr>标题</nobr>
                </th>
                <th>
                  <nobr>类型</nobr>
                </th>
                <th>
                  <nobr>发布时间</nobr>
                </th>
                <th>
                  <nobr>结束时间</nobr>
                </th>
                <th>
                  <nobr>发布人</nobr>
                </th>
                <th>
                  <nobr>操作</nobr>
                </th>
                <th>
                  <nobr>下载查看</nobr>
                </th>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align: center;">{{$index + 1}}</td>
              <td style="text-align: center;">{{row.f_title}}</td>
              <td style="text-align: center;">{{row.f_type}}</td>
              <td style="text-align: center;">{{row.f_date}}</td>
              <td style="text-align: center;">{{row.f_enddate}}</td>
              <td style="text-align: center;">{{row.f_operator}}</td>
              <td><center>
                <button type="button" name="button" class="btn btn-link"
                        @click.stop="$parent.$parent.$parent.modifyUser(row)">修正
                </button>
                <!--<button type="button" name="button" class="btn btn-link"
                        @click.stop="$parent.$parent.$parent.revoke(row)">撤销
                </button>--></center>
              </td>
              <td style="text-align: center;">
                <!--<a  v-bind:herf="row.f_filepath" >下载</a>-->
                <a  v-bind:herf="row.f_filepath"  @click="$parent.$parent.$parent.download1(row.f_filepath)">点击下载</a>
              </td>
            </template>
          </data-grid>
        </criteria-paged>
      </div>
    </div>
  </div>
  <div style="height: 500px;" v-show="row || areainfo" class="select-overspread">
    <notice-essential-info v-if="row || areainfo" :row="row" @clean="clean" :areainfo="areainfo" @success="renew"
                          @build-success="buildFileSuccess"></notice-essential-info>
  </div>


  <modal :show.sync="addknow_show"  backdrop="false" z-index="-1">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">新增知识库</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal" >
        <div class="form-group" >
          <label for="f_title" class="control-label">标题</label>
          <input type="text"  class="form-control" v-model="model.f_title"
                   placeholder='标题'>
        </div>

            <!--<button type="button" class="btn btn-success" @click='fileUpload'>上传文件</button>-->
            <div class="form-group">
              <file-upload class="my-file-uploader" name="myFile"
                           action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>

            <input type="hidden"  class="form-control"  v-model="model.f_filepath">

        </div>
      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success" @click='addKnow'>确认</button>
      <button type="button" class="btn btn-default" @click='addknowclose'>取消</button>
    </footer>
  </modal>


  <modal :show.sync="add_show"  backdrop="false" z-index="-1">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">发布公告</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal" >
        <div class="form-group">
          <label for="f_title" class="control-label">标题</label>
          <input type="text"  class="form-control" v-model="model.f_title"
                 placeholder='标题'>
        </div>
        <div class="form-group">
          <label for="f_grade" class="control-label">级别</label>
          <!--<input type="text"  class="form-control" v-model="model.f_grade"
                 placeholder='级别'>-->
          <v-select :value.sync="model.f_grade" v-model="model.f_grade"
                    :options='selectgrade'>
          </v-select>
        </div>
        <div class="form-group">
          <label for="f_enddate" class="control-label">结束时间</label>
          <datepicker id="f_enddate" placeholder="结束日期"
                      v-model="model.f_enddate"
                      :value.sync="model.f_enddate"
                      :disabled-days-of-Week="[]"
                      :format="'yyyy-MM-dd'"
                      condition="f_enddate >= '{}' "
                      :show-reset-button="reset">
          </datepicker>
        </div>

            <!--<button type="button" class="btn btn-success" @click='fileUpload'>上传文件</button>-->
            <div class="form-group">
              <file-upload class="my-file-uploader" name="myFile3"
                           action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>

            <input type="hidden"  class="form-control" v-model="model.f_filepath">

        </div>
      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success":disabled='!$v.valid' @click='addConfirm'>确认</button>
      <button type="button" class="btn btn-default" @click='addclose'>取消</button>
    </footer>
  </modal>


  <modal :show.sync="updateknow_show"  backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">修改知识库</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal" >
        <div class="form-group">
          <label for="f_title" class="control-label">标题</label>
          <input type="text"  class="form-control" v-model="updaterow.f_title"
                 placeholder='标题'>
        </div>
        <div class="form-group">
          <label for="f_reason" class="control-label">修改原因</label>
          <input type="text"  class="form-control" v-model="updaterow.f_reason"
                 placeholder='修改原因'>
        </div>

            <!--<button type="button" class="btn btn-success" @click='fileUpload'>上传文件</button>-->
            <div class="form-group">
              <file-upload class="my-file-uploader" name="myFile4"
                           action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>

            <input type="hidden"  class="form-control"  v-model="updaterow.f_filepath">
          </div>

      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success" @click='updateknow'>确认</button>
      <button type="button" class="btn btn-default" @click='updateknowclose'>取消</button>
    </footer>
  </modal>

  <modal :show.sync="update_show"  backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">修改公告</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal" >
        <div class="form-group">
          <label for="f_title" class="control-label">标题</label>
          <input type="text"  class="form-control" v-model="updaterow.f_title"
                 placeholder='标题'>
        </div>
        <div class="form-group">
          <label for="f_grade" class="control-label">级别</label>
          <div v-if="updaterow.f_grade === '紧急'">
          <v-select :value.sync="updaterow.f_grade" v-model="updaterow.f_grade"
                    :options='selectgrade' placeholder="紧急">
          </v-select></div>
         <div v-else="updaterow.f_grade === '一般'">
            <v-select :value.sync="updaterow.f_grade" v-model="updaterow.f_grade"
                      :options='selectgrade' placeholder="一般">
            </v-select></div>
          <!--<div v-else>
            <v-select :value.sync="updaterow.f_grade" v-model="updaterow.f_grade"
                      :options='selectgrade'>
            </v-select></div>-->
        </div>
        <div class="form-group">
          <label for="f_enddate" class="control-label">结束时间</label>
          <datepicker id="f_enddate" placeholder="结束日期"
                      v-model="updaterow.f_enddate"
                      :value.sync="updaterow.f_enddate"
                      :disabled-days-of-Week="[]"
                      :format="'yyyy-MM-dd  23:59:59 '"
                      :show-reset-button="reset">
          </datepicker>
        </div>
        <div class="form-group">
          <label for="f_reason" class="control-label">修改原因</label>
          <input type="text"  class="form-control" v-model="updaterow.f_reason"
                 placeholder='修改原因'>
        </div>

            <!--<button type="button" class="btn btn-success" @click='fileUpload'>上传文件</button>-->
            <div class="form-group">
              <file-upload class="my-file-uploader" name="myFile1"
                           action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>

            <input type="hidden"  class="form-control" v-model="updaterow.f_filepath">

        </div>
      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success" @click='updateConfirm'>确认</button>
      <button type="button" class="btn btn-default" @click='updateclose'>取消</button>
    </footer>
  </modal>



  <modal :show.sync="uploadshow" v-ref:modal backdrop="false" z-index="1">
    <header slot="modal-header" class="modal-header">
      <button type="button" class="close" @click="close"><span>&times;</span></button>
      <h4 class="modal-title">文件上传</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <div class="form-group">
        <file-upload class="my-file-uploader" name="myFile2"
                     action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <!-- <button v-show="show" type="button" class="btn btn-default" @click='close'>取消</button>
      <button v-show="show" type="button" class="btn btn-success" @click='confirm(filename)'>确认</button> -->
    </footer>
  </modal>


</template>

<script>
  import {PagedList} from 'vue-client'
  import Vue from 'vue'
  import co from 'co'

  let areaGen = function * (self) {
    let data = {}
    data.f_grade = self.model.f_grade[0] ? self.model.f_grade[0] : ''
  }
  let loadParamGem = async function (self) {
    console.log('获取登录信息，', self.$login, self.$appdata, self.$appdata.getParam('用户类型'), Vue.$login.f.name)
    self.headers.username = Vue.$login.f.name
    self.headers.username = Vue.$login.guid()
    await self.search()
    await self.$LoadParams.loadParam()
  }
  let add = async function (self) {
    console.log('self:', self)
    let param = {
      f_title: self.model.f_title,
      f_operator: self.$login.f.name,
      f_enddate: self.model.f_enddate + ' 23:59:59 ',
      f_type: '公告',
      f_grade: self.model.f_grade[0],
      f_state: '1',
      f_filepath: self.model.f_filepath
    }
    console.log('发布公告', self.model.f_filepath)
    self.$resetpost('rs/logic/addstopgas', param).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('发布成功！')/*
      this.$refs.paged.$refs.criteria.search() */
      this.f_error_reason = ''
    })
    self.add_show = false
    self.search()
  }
  let revoke = async function (self) {
    let param = {
      id: self.updaterow.id,
      f_state: '0'
    }
    let param2 = {
      f_operation_type: '撤销',
      f_operator: self.$login.f.name,
      f_operation_id: self.updaterow.id,
      f_change_type: '公告',
      f_reason: '撤销'
    }
    console.log('撤销公告', param)
    self.$resetpost('rs/entity/t_knowledge_stopgas', param).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('撤销成功！')
      self.$resetpost('rs/entity/t_operationrecord', param2).then(() => {
        console.log('撤销记录成功！')
      })
      this.f_error_reason = ''
    })
    self.search()
  }
  let addKnow = async function (self) {
    console.log('self:', self)
    let param = {
      f_title: self.model.f_title,
      f_operator: self.$login.f.name,
      f_type: '知识库',
      f_state: '1',
      f_filepath: self.model.f_filepath
    }
    console.log('发布知识库', param.f_title)
    self.$resetpost('rs/logic/addknowledge', param).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('发布成功！')
      this.f_error_reason = ''
    })
    self.addknow_show = false
    self.search()
  }
  let updateknow = async function (self) {
    let param = {
      id: self.updaterow.id,
      f_title: self.updaterow.f_title,
      f_operation_type: '修改',
      f_operator: self.$login.f.name,
      f_change_type: '知识库',
      f_reason: self.updaterow.f_reason,
      f_filepath: self.updaterow.f_filepath
    }
    console.log('修改知识库', param)
    self.$resetpost('rs/logic/knowledgerecord', param).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('更新成功！')
      this.f_error_reason = ''
    })
    self.updateknow_show = false
  }
  /* let downloadfile = async function(self){
    let data = {
      filepath:'file:///'+self.updaterow.f_filepath,
      downloadpath:'d:/filedownload',
    }
    console.log('路径',data.filepath)
    self.$resetpost('rs/logic/downloadfile', data).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('下载！')
      this.f_error_reason = ''
    })
  } */
  let update = async function (self) {
    let param = {
      id: self.updaterow.id,
      f_title: self.updaterow.f_title,
      f_enddate: self.updaterow.f_enddate,
      f_grade: self.updaterow.f_grade[0],
      f_operation_type: '修改',
      f_operator: self.$login.f.name,
      f_operation_id: self.updaterow.id,
      f_reason: self.updaterow.f_reason,
      f_filepath: self.updaterow.f_filepath
    }
    console.log('修改公告', param.f_filepath)
    self.$resetpost('rs/logic/InsertRecord', param).then(() => {
      // this.params.rows.splice(index, 1)
      console.log('更新成功！')
      this.f_error_reason = ''
    })
    self.update_show = false
    self.search()
  }
  export default {
    'title': '用户公告',
    data () {
      return {
        model: new PagedList('rs/sql/getStopgas', 10, {orderitem: '`f_grade DESC`'}),
         // 选择一条公告信息，对其进行修改
        rows: [], // 用户档案选择一条时，将只显示一条信息，rows用来存放整页的数据
        headers: {'username': this.$login.f.name, 'blodid': this.$login.guid()},
        contract: [{label: '全部', value: ' is null or f_contract_id is not null'}, {label: '有', value: ' is not null'},
          {label: '无', value: ' is null'}],
        orderDefault: 'f_modify_date desc',
        orderFields: {
          f_userinfo_id: 'no'
        },
        updaterow: null,
        isChange: false,
        userlist: false,
        row: null,
        boxmodel: null,
        // 销户启用
        batcan: false,
        batenable: false,
        uploadshow: false,
        add_show: false,
        update_show: false,
        addknow_show: false,
        updateknow_show: false,
        inputtores: this.$appdata.getParam('抄表员'),
        adjustables: []
      }
    },
    ready () {
      this.search()
      /* loadParamGem(this) */
    },
    methods: {
      download1 (filePath) {
        const url = `${filePath}`
        console.log('url:' + url)
        console.log('filePath:' + filePath)
        window.open(url)
        /* window.open ('https://dldir1.qq.com/qqfile/qq/PCQQ9.1.6/25786/QQ9.1.6.25786.exe') */
      },
      addrecord () {
        insertRecord(this)
      },
      search () {
        console.log('condition:', condition)
        let condition = '1=1'
        this.model.search(condition)
      },
      add () {
        console.log('新增')
        this.add_show = true
      },
      addknow () {
        console.log('add')
        this.addknow_show = true
      },
      addknowclose () {
        this.addknow_show = false
      },
      addclose () {
        this.add_show = false
      },
      fileUpload () {
        this.uploadshow = true
      },
      async addKnow () {
        if (!this.model.f_title) {
          this.$showAlert('输入标题', 'warning', 1500)
          return
        }
        if (!this.model.f_filepath) {
          this.$showAlert('请上传文件', 'warning', 1500)
          return
        }
        await this.$showMessage(`是否确认添加新的知识库`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            addKnow(this)
          }
        })
      },
      async updateknow () {
        if (!this.model.f_title) {
          this.$showAlert('输入标题', 'warning', 1500)
          return
        }
        if (!this.model.f_filepath) {
          this.$showAlert('请上传文件', 'warning', 1500)
          return
        }
        await this.$showMessage(`是否确认修改知识库`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            updateknow(this)
          }
        })
      },
      async addConfirm () {
        if (!this.model.f_title) {
          this.$showAlert('输入标题', 'warning', 1500)
          return
        }
        if (!this.model.f_grade[0]) {
          this.$showAlert('请选择级别', 'warning', 1500)
          return
        }
        if (!this.model.f_enddate) {
          this.$showAlert('请设置结束时间', 'warning', 1500)
          return
        }
        if (!this.model.f_filepath) {
          this.$showAlert('请上传文件', 'warning', 1500)
          return
        }
        await this.$showMessage(`是否确认添加新的公告`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            add(this)
          }
        })
      },
      revoke (row) {
        this.updaterow = row
        this.$showMessage(`是否确认撤销`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            revoke(this)
          }
        })
      },
      modifyUser (row) {
        console.log('modifyrow')
        this.updaterow = row
        if (row.f_type == '公告') {
          this.update_show = true
        } else if (row.f_type == '知识库') {
          this.updateknow_show = true
        }
      },
      updateknowclose () {
        this.updateknow_show = false
        this.search()
      },
      updateclose () {
        this.update_show = false
        this.search()
      },
      async updateConfirm () {
        if (!this.model.f_title) {
          this.$showAlert('输入标题', 'warning', 1500)
          return
        }
        if (!this.model.f_grade[0]) {
          this.$showAlert('请选择级别', 'warning', 1500)
          return
        }
        if (!this.model.f_enddate) {
          this.$showAlert('请设置结束时间', 'warning', 1500)
          return
        }
        if (!this.model.f_filepath) {
          this.$showAlert('请上传文件', 'warning', 1500)
          return
        }
        await this.$showMessage(`是否确认修改公告`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            update(this)
          }
        })
      },
      clean () {
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = ''
        })
      },
     /* download(row){
        this.updaterow=row
        console.log('download')
        downloadfile(this)
      }, */
      renew () {
        this.row = null
        this.areainfo = null
        this.clearCondition()
        this.search()
        // 建档或修正档案成功刷新地址列表
        this.$refs.addressfiles.$refs.paged.$refs.cri.search()
      },
      clearCondition () {
        console.log('清空条件。。', this.$refs.paged)
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = ''
        })
      },

      bulkOperations (name, type) {
        if (name === '批量销户') {
          this.batcan = true
          this.batenable = false
          this.newArea = false
        } else if (name === '批量启用') {
          this.batenable = true
          this.batcan = false
          this.newArea = false
        }
      },
      batchSuccess () {
        this.clearCondition()
        this.clean()
      },
      batchClean () {
        this.batcan = false
        this.batenable = false
        this.newArea = false
        this.search()
      },
      buildFile (row) {
        // console.log('我是建档。。。', row)
        this.row = row
      },
      // 小区批量建档
      bulidFiles (row) {
        this.row = null
        this.areainfo = row
        // 将列表的数据清空
        this.$refs.paged.$refs.grid.model.rows = this.rows
      },
      // 小区批量建档成功
      buildFileSuccess (data) {
        // console.log('建档案成功', data)
        this.model.rows.unshift(data)
      },
      selfSearch (args) {
        args.condition = `${args.condition}`
        this.model.search(args.condition, args.model)
      },
      sort (field, rule) {
        // 将所有排序方式设为不排序，实现相互排斥
        for (let key in this.orderFields) {
          if (key === field) {
            this.orderFields[key] = rule
          } else {
            this.orderFields[key] = 'no'
          }
        }
        // 如果新规则不排序，还原为默认排序
        if (rule === 'no') {
          this.model.paramSource.orderitem = `'${this.orderDefault}'`
        } else {
          this.model.paramSource.orderitem = `'${field} ${rule}'`
        }

        this.search()
      },

      getLocation (row) {
        // 可能会存在添加，完善，建档
        console.log('进入', row)

        addressInfoGen(this, row)
      },
      areaFiles (row) {
        row.isEdit = true
        this.bulidFiles(row)
      }

     /* initAdjustables () {
        console.log('初始化调压箱', this.$GetSaleParam)
        let arr = []
        let filter = this.$login.f.f_orgids
        this.$GetSaleParam.getAdjustable(filter).forEach((item) => {
          let temp = {}
          temp.label = `[${item.value.f_adjustable_id}]-${item.label}`
          temp.value = `${item.value.id}`
          arr.push(temp)
        })
        this.adjustables = [{label: '全部', value: ''}, ...arr]
      }, */
    },
    computed: {
      selectgrade () {
        return [{label: '紧急', value: '紧急'}, {label: '一般', value: '一般'}]
      },
      userstates () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户状态')]
      },
      areas () {
        let rs = []
        for (let i = 0; i < this.$login.f.f_allArea.length; i++) {
          let temp = {
            label: this.$login.f.f_allArea[i].label,
            value: this.$login.f.f_allArea[i].label
          }
          rs.push(temp)
        }
        return [{label: '全部', value: ''}, ...rs]
      },
      firestates () {
        return [
          {label: '全部', value: ''},
          {label: '点火', value: '1'},
          {label: '未点火', value: '0'}
        ]
      },
      jurisdiction () {
        return this.$login.r
      }
    },
    watch: {
      // 每次查询将查询到的数据存储起来，供选择操作后的替换
      'model.state' (val) {
        if (val === '正确') {
          this.rows = this.model.rows
        }
      }
    },
    events: {
      onFileUpload: function (file, res) {
        console.log(res.f_downloadpath)

        if (this.model != null) {
          this.model.f_filepath = res.f_downloadpath
        }

        if (this.updaterow != null) {
          this.updaterow.f_filepath = res.f_downloadpath
        }
        alert('上传成功')
      }
    }
  }
</script>
<style>
  .nav-tabss ul > li > a {
    padding: 5px 10px;
  }
</style>
